From eb370a39aa5f4ddb0266ff4923d58d48ec95c1fe Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sat, 24 Oct 2026 23:36:41 +0000 Subject: [PATCH 01/30] fix(query): check Query values against the key schema and the number rules A Query with a KeyConditionExpression did not check a key condition value's type against the key attribute's AttributeDefinitions type, and did not check that an N value in ExpressionAttributeValues is a number. The storage layer compared the value's inner text with the stored key and ignored the type tag, so {"N": "bob"} on an S partition key read the bob partition while authorization bound no dynamodb:LeadingKeys value to it, and a sort key value of another type answered InternalServerError on SQLite. Add the two checks the service applies before it reads a row, on the expression path (crates/engine/src/query_key_values.rs): - an N value in ExpressionAttributeValues that is not a number answers "The parameter cannot be converted to a numeric value: " (the overflow and 38-digit texts for those cases; an empty value answers the message with the colon). The check covers the whole map, including NS members and values nested in L and M, whether the key condition, the filter or nothing reads them, with the walk PutItem and UpdateItem already use. It runs at request time after the Limit and expression parameter mix checks and before the table lookup, which moves those two checks ahead of the table lookup as well. The server runs the same request-time checks ahead of the IAM decision, so a principal under any LeadingKeys fence form gets ValidationException and no items; - a key condition value whose type is not the key attribute's type answers "One or more parameter values were invalid: Condition parameter type does not match schema type", for the partition key, the sort key under every comparison operator, both BETWEEN bounds, the begins_with prefix and multi-attribute index keys, after the key schema, filter, projection, unused value and Select checks and before the ExclusiveStartKey check. When a compared placeholder is undefined the check returns without a verdict and the undefined placeholder is reported. Measured on the service on 2026-10-24 (113 requests, each sent twice). The legacy KeyConditions path is unchanged; its checks land with #507. Scan is unchanged. Unit tests at the checks and a dual-target wire test file, tests/test_query_key_value_types.py, which fails on main. --- crates/core/src/validation/mod.rs | 10 +- crates/engine/src/lib.rs | 1 + crates/engine/src/query.rs | 59 +-- crates/engine/src/query_key_values.rs | 224 +++++++++ crates/engine/src/query_key_values/tests.rs | 395 ++++++++++++++++ crates/server/src/request_helpers.rs | 14 + tests/test_query_key_value_types.py | 489 ++++++++++++++++++++ 7 files changed, 1156 insertions(+), 36 deletions(-) create mode 100644 crates/engine/src/query_key_values.rs create mode 100644 crates/engine/src/query_key_values/tests.rs create mode 100644 tests/test_query_key_value_types.py diff --git a/crates/core/src/validation/mod.rs b/crates/core/src/validation/mod.rs index c144b46b6..02e24e618 100755 --- a/crates/core/src/validation/mod.rs +++ b/crates/core/src/validation/mod.rs @@ -1903,7 +1903,15 @@ fn validate_lsi_requires_range_key(input: &CreateTableInput) -> Result<(), Dynam Ok(()) } -fn validate_attribute_number(value: &AttributeValue) -> Result<(), DynamoDbError> { +/// Validate every number inside one attribute value (`N`, `NS` members, and +/// the values nested in `L` and `M`) against the `DynamoDB` number rules, with +/// the bare numeric message. +/// +/// # Errors +/// +/// Returns `DynamoDbError::ValidationException` for the first number that is +/// not a number, has more than 38 significant digits, or is out of range. +pub fn validate_attribute_number(value: &AttributeValue) -> Result<(), DynamoDbError> { match value { AttributeValue::N(n) => { number::validate_and_normalize_number(n)?; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 74083fbfa..d24b47286 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -27,6 +27,7 @@ mod legacy_filter; mod list_tables; mod put_item; mod query; +pub mod query_key_values; mod read_helpers; mod request_limits; mod scan; diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index f45526af8..97e07ead2 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -71,6 +71,14 @@ pub async fn handle_query( )?; let input: QueryInput = serde_json::from_value(body).map_err(crate::deserialize_error)?; + // Request-time checks in the service's order: Limit, the expression and + // non-expression parameter mix, then every number in + // ExpressionAttributeValues (measured 2026-10-24: a Limit of 0 and a + // parameter mix are reported ahead of an N value that is not a number, and + // that value is reported ahead of a missing table or index). The server + // runs the same function ahead of the IAM decision; see `query_key_values`. + crate::query_key_values::validate_query_request_values(&input)?; + // P118: Fetch key_info first so we can use table_id for index lookup. let key_info = ctx .table_key_info(&input.table_name) @@ -137,14 +145,7 @@ pub async fn handle_query( )?; } - // Validate Limit >= 1 (REQ-QUERY-001) - if let Some(limit) = input.limit - && limit < 1 - { - return Err(DynamoDbError::ValidationException( - "1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1".to_owned(), - )); - } + // Limit >= 1 is checked at request time in validate_query_request_values. // For index queries, build a key_info that reflects the index's key schema // so the storage layer uses the correct SK column for the index table. @@ -166,35 +167,10 @@ pub async fn handle_query( key_info.clone() }; - // --- Legacy vs expression mutual exclusivity checks --- - let kce_present = input.key_condition_expression.is_some(); - let has_kc = input.key_conditions.as_ref().is_some_and(|m| !m.is_empty()); - let has_fe = input.filter_expression.is_some(); - let has_qf = input.query_filter.as_ref().is_some_and(|m| !m.is_empty()); - let has_pe = input.projection_expression.is_some(); - let has_atg = input - .attributes_to_get - .as_ref() - .is_some_and(|a| !a.is_empty()); + // The legacy versus expression mutual exclusivity check runs at request + // time in validate_query_request_values. let has_cond_op = input.conditional_operator.is_some(); - // KeyConditions legitimately combines with FilterExpression and - // ProjectionExpression, so it joins the mixing check only when - // KeyConditionExpression is also present. - extenddb_core::validation::validate_no_expression_param_mixing( - &[ - ("AttributesToGet", has_atg), - ("QueryFilter", has_qf), - ("ConditionalOperator", has_cond_op), - ("KeyConditions", has_kc && kce_present), - ], - &[ - ("ProjectionExpression", has_pe), - ("FilterExpression", has_fe), - ("KeyConditionExpression", kce_present), - ], - )?; - // An explicitly empty KeyConditionExpression is rejected up front, before // the expression-parameter-usage checks (matching real DynamoDB). reject_empty_key_condition_expression(input.key_condition_expression.as_deref())?; @@ -471,6 +447,19 @@ pub async fn handle_query( )?; } + // A key condition value whose type is not the key attribute's type is + // refused after the key schema, filter, projection, unused value and + // Select checks and before the ExclusiveStartKey check (measured + // 2026-10-24). The legacy KeyConditions path makes its own checks when it + // desugars. + if legacy_kc_maps.is_none() { + crate::query_key_values::validate_key_condition_types( + &key_condition, + effective_maps, + &query_key_info.attribute_definitions, + )?; + } + // Validate ExclusiveStartKey matches the key schema if let Some(ref start_key) = input.exclusive_start_key { validate_query_exclusive_start_key(start_key, &key_info, index_info.as_ref())?; diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs new file mode 100644 index 000000000..e49968648 --- /dev/null +++ b/crates/engine/src/query_key_values.rs @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Checks on the values a `Query` carries, as the service applies them before +//! any row is read. +//! +//! Measured on 2026-10-24 (tables with S/S, S/N and B/B keys, a GSI and an +//! LSI): +//! +//! 1. an `N` value in `ExpressionAttributeValues` that is not a number answers +//! `The parameter cannot be converted to a numeric value: ` (or the +//! overflow, underflow and 38-digit messages). Every value in the map is +//! checked, whether the key condition, the filter or nothing reads it. The +//! check runs at request time, after the `Limit` check and the expression +//! and non-expression parameter mix check, and before the table is looked +//! up; see [`validate_query_request_values`]; +//! 2. a key condition value whose type is not the key attribute's +//! `AttributeDefinitions` type answers `One or more parameter values were +//! invalid: Condition parameter type does not match schema type`, on the +//! partition and the sort key, on a table, a GSI and an LSI, for `=`, the +//! ordering operators, `BETWEEN` and `begins_with`. The check runs after the +//! key schema, filter, projection, unused value and `Select` checks and +//! before the `ExclusiveStartKey` check; see +//! [`validate_key_condition_types`]. +//! +//! Without these checks a backend compares the value's inner text with the +//! stored key and ignores the type tag, so `{"N": "bob"}` on an S key reads the +//! `bob` partition, while authorization binds no `dynamodb:LeadingKeys` value +//! to a number it cannot parse. + +use std::collections::HashMap; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::expression::{ + Expr, ExpressionMaps, KeyCondition, PathElement, SortKeyCondition, +}; +use extenddb_core::types::{AttributeDefinition, AttributeValue, QueryInput, ScalarAttributeType}; + +/// The service's text for a key condition value of the wrong type. +pub const KEY_CONDITION_TYPE_MISMATCH: &str = "One or more parameter values were invalid: Condition parameter type does not match schema type"; + +/// The service's text for a `Limit` below 1 on `Query`. +pub const LIMIT_BELOW_ONE: &str = "1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1"; + +/// The bare numeric message the number validator uses for an empty `N`. +const EMPTY_NUMBER: &str = "The parameter cannot be converted to a numeric value"; + +/// The `Query` checks that run on the request alone, before the table is +/// looked up, in the service's order: `Limit`, the expression and +/// non-expression parameter mix, then every number in +/// `ExpressionAttributeValues`. +/// +/// The server runs the same function ahead of the IAM decision, so a principal +/// whose `dynamodb:LeadingKeys` fence cannot bind a number that does not parse +/// gets the request's `ValidationException` rather than +/// `AccessDeniedException`. +/// +/// # Errors +/// +/// Returns `DynamoDbError::ValidationException` with the service's text. +pub fn validate_query_request_values(input: &QueryInput) -> Result<(), DynamoDbError> { + if let Some(limit) = input.limit + && limit < 1 + { + return Err(DynamoDbError::ValidationException( + LIMIT_BELOW_ONE.to_owned(), + )); + } + + let kce_present = input.key_condition_expression.is_some(); + let has_kc = input.key_conditions.as_ref().is_some_and(|m| !m.is_empty()); + let has_qf = input.query_filter.as_ref().is_some_and(|m| !m.is_empty()); + let has_atg = input + .attributes_to_get + .as_ref() + .is_some_and(|a| !a.is_empty()); + // KeyConditions combines with FilterExpression and ProjectionExpression, so + // it joins the mix check only when KeyConditionExpression is also present. + extenddb_core::validation::validate_no_expression_param_mixing( + &[ + ("AttributesToGet", has_atg), + ("QueryFilter", has_qf), + ("ConditionalOperator", input.conditional_operator.is_some()), + ("KeyConditions", has_kc && kce_present), + ], + &[ + ( + "ProjectionExpression", + input.projection_expression.is_some(), + ), + ("FilterExpression", input.filter_expression.is_some()), + ("KeyConditionExpression", kce_present), + ], + )?; + + if let Some(values) = &input.expression_attribute_values { + validate_expression_attribute_value_numbers(values)?; + } + Ok(()) +} + +/// Refuse the first `N` value in `ExpressionAttributeValues` (including `NS` +/// members and values nested in `L` and `M`) that is not a number, with the +/// bare numeric message: no `ExpressionAttributeValues contains invalid value` +/// wrapper, which the service uses on `UpdateItem` and not on `Query`. The +/// placeholders are visited in sorted order so the reported value is +/// deterministic when several are invalid. An empty `N` answers the message +/// with the colon and nothing after it, as the service does on `Query`. +/// +/// # Errors +/// +/// Returns `DynamoDbError::ValidationException` with the service's text. +pub fn validate_expression_attribute_value_numbers( + values: &HashMap, +) -> Result<(), DynamoDbError> { + let mut keys: Vec<&String> = values.keys().collect(); + keys.sort(); + for key in keys { + match extenddb_core::validation::validate_attribute_number(&values[key]) { + Ok(()) => {} + Err(DynamoDbError::ValidationException(msg)) if msg == EMPTY_NUMBER => { + return Err(DynamoDbError::ValidationException(format!( + "{EMPTY_NUMBER}: " + ))); + } + Err(other) => return Err(other), + } + } + Ok(()) +} + +/// Refuse a key condition value whose type is not the key's +/// `AttributeDefinitions` type. +/// +/// Every value the condition compares is checked: the partition key value(s), +/// the sort key value (or both `BETWEEN` bounds, or the `begins_with` prefix) +/// and the extra equality conditions of a multi-attribute key schema. A path +/// that does not resolve to an attribute name, a value that is not a +/// placeholder, and a key attribute with no definition are left to the checks +/// that already refuse them. When any compared placeholder is undefined the +/// whole check is skipped: the service reports the undefined placeholder +/// first, and the storage layer does so here. +/// +/// # Errors +/// +/// Returns `DynamoDbError::ValidationException` with +/// [`KEY_CONDITION_TYPE_MISMATCH`]. +pub fn validate_key_condition_types( + key_condition: &KeyCondition, + maps: &ExpressionMaps, + attribute_definitions: &[AttributeDefinition], +) -> Result<(), DynamoDbError> { + let mut pairs: Vec<(&[PathElement], &Expr)> = + vec![(&key_condition.pk_path, &key_condition.pk_value)]; + for (path, value) in &key_condition.extra_pk_conditions { + pairs.push((path, value)); + } + match &key_condition.sk_condition { + Some(SortKeyCondition::Compare { path, value, .. }) => pairs.push((path, value)), + Some(SortKeyCondition::Between { path, low, high }) => { + pairs.push((path, low)); + pairs.push((path, high)); + } + Some(SortKeyCondition::BeginsWith { path, prefix }) => pairs.push((path, prefix)), + None => {} + } + for (path, value) in &key_condition.extra_sk_conditions { + pairs.push((path, value)); + } + + let any_undefined = pairs.iter().any( + |(_, value)| matches!(value, Expr::Placeholder(name) if !maps.values.contains_key(name)), + ); + if any_undefined { + return Ok(()); + } + + for (path, value) in pairs { + let Some(attr_name) = resolve_attr_name(path, &maps.names) else { + continue; + }; + let Some(expected) = attribute_definitions + .iter() + .find(|ad| ad.attribute_name == attr_name) + .map(|ad| ad.attribute_type) + else { + continue; + }; + let Expr::Placeholder(name) = value else { + continue; + }; + let Some(av) = maps.values.get(name) else { + continue; + }; + if !type_matches(expected, av) { + return Err(DynamoDbError::ValidationException( + KEY_CONDITION_TYPE_MISMATCH.to_owned(), + )); + } + } + Ok(()) +} + +fn type_matches(expected: ScalarAttributeType, value: &AttributeValue) -> bool { + matches!( + (expected, value), + (ScalarAttributeType::S, AttributeValue::S(_)) + | (ScalarAttributeType::N, AttributeValue::N(_)) + | (ScalarAttributeType::B, AttributeValue::B(_)) + ) +} + +/// The top-level attribute name of a key path, through `#name` references. +fn resolve_attr_name(path: &[PathElement], names: &HashMap) -> Option { + match path.first()? { + PathElement::Attribute(name) => match name.strip_prefix('#') { + Some(reference) => names.get(reference).cloned(), + None => Some(name.clone()), + }, + PathElement::Index(_) => None, + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/query_key_values/tests.rs b/crates/engine/src/query_key_values/tests.rs new file mode 100644 index 000000000..6130dd875 --- /dev/null +++ b/crates/engine/src/query_key_values/tests.rs @@ -0,0 +1,395 @@ +// SPDX-License-Identifier: Apache-2.0 + +use std::collections::HashMap; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::expression::{ + ExpressionMaps, KeyCondition, parse_key_condition, tokenize_with_limit, +}; +use extenddb_core::types::{AttributeDefinition, AttributeValue, QueryInput, ScalarAttributeType}; + +use super::{ + KEY_CONDITION_TYPE_MISMATCH, LIMIT_BELOW_ONE, validate_expression_attribute_value_numbers, + validate_key_condition_types, validate_query_request_values, +}; + +fn defs(pairs: &[(&str, ScalarAttributeType)]) -> Vec { + pairs + .iter() + .map(|(name, ty)| AttributeDefinition { + attribute_name: (*name).to_owned(), + attribute_type: *ty, + }) + .collect() +} + +fn parse(kce: &str) -> KeyCondition { + let tokens = tokenize_with_limit(kce, 1000).expect("tokenize"); + parse_key_condition(&tokens).expect("parse") +} + +fn maps(names: &[(&str, &str)], values: &[(&str, AttributeValue)]) -> ExpressionMaps { + ExpressionMaps::new( + names + .iter() + .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) + .collect(), + values + .iter() + .map(|(k, v)| ((*k).to_owned(), v.clone())) + .collect(), + ) +} + +fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_owned()) +} + +fn n(v: &str) -> AttributeValue { + AttributeValue::N(v.to_owned()) +} + +fn message(result: Result<(), DynamoDbError>) -> Option { + match result { + Ok(()) => None, + Err(DynamoDbError::ValidationException(msg)) => Some(msg), + Err(other) => panic!("unexpected error {other:?}"), + } +} + +const SS: &[(&str, ScalarAttributeType)] = &[ + ("pk", ScalarAttributeType::S), + ("sk", ScalarAttributeType::S), +]; + +#[test] +fn partition_value_of_another_type_is_refused() { + let kc = parse("pk = :u"); + for wrong in [ + n("5"), + AttributeValue::B(vec![1]), + AttributeValue::Bool(true), + AttributeValue::Null, + ] { + let m = maps(&[], &[("u", wrong)]); + assert_eq!( + message(validate_key_condition_types(&kc, &m, &defs(SS))).as_deref(), + Some(KEY_CONDITION_TYPE_MISMATCH) + ); + } +} + +#[test] +fn matching_types_pass() { + let kc = parse("pk = :u AND sk BETWEEN :a AND :b"); + let m = maps(&[], &[("u", s("x")), ("a", s("a")), ("b", s("b"))]); + assert!(validate_key_condition_types(&kc, &m, &defs(SS)).is_ok()); + + let kc = parse("pk = :u AND begins_with(sk, :p)"); + let m = maps(&[], &[("u", s("x")), ("p", s("a"))]); + assert!(validate_key_condition_types(&kc, &m, &defs(SS)).is_ok()); + + let n_sk = defs(&[ + ("pk", ScalarAttributeType::S), + ("sk", ScalarAttributeType::N), + ]); + let kc = parse("pk = :u AND sk > :v"); + let m = maps(&[], &[("u", s("x")), ("v", n("5"))]); + assert!(validate_key_condition_types(&kc, &m, &n_sk).is_ok()); +} + +#[test] +fn sort_key_value_of_another_type_is_refused_for_every_operator() { + for kce in [ + "pk = :u AND sk = :v", + "pk = :u AND sk < :v", + "pk = :u AND sk <= :v", + "pk = :u AND sk > :v", + "pk = :u AND sk >= :v", + "pk = :u AND :v <= sk", + "pk = :u AND begins_with(sk, :v)", + ] { + let kc = parse(kce); + let m = maps(&[], &[("u", s("x")), ("v", n("5"))]); + assert_eq!( + message(validate_key_condition_types(&kc, &m, &defs(SS))).as_deref(), + Some(KEY_CONDITION_TYPE_MISMATCH), + "{kce}" + ); + } +} + +#[test] +fn either_between_bound_of_another_type_is_refused() { + let kc = parse("pk = :u AND sk BETWEEN :a AND :b"); + for (a, b) in [(n("1"), s("b")), (s("a"), n("2")), (n("1"), n("2"))] { + let m = maps(&[], &[("u", s("x")), ("a", a), ("b", b)]); + assert_eq!( + message(validate_key_condition_types(&kc, &m, &defs(SS))).as_deref(), + Some(KEY_CONDITION_TYPE_MISMATCH) + ); + } +} + +#[test] +fn string_on_a_number_or_binary_key_is_refused() { + let n_sk = defs(&[ + ("pk", ScalarAttributeType::S), + ("sk", ScalarAttributeType::N), + ]); + let kc = parse("pk = :u AND sk = :v"); + let m = maps(&[], &[("u", s("x")), ("v", s("5"))]); + assert_eq!( + message(validate_key_condition_types(&kc, &m, &n_sk)).as_deref(), + Some(KEY_CONDITION_TYPE_MISMATCH) + ); + + let b_pk = defs(&[ + ("bpk", ScalarAttributeType::B), + ("bsk", ScalarAttributeType::B), + ]); + let kc = parse("bpk = :u"); + for wrong in [s("x"), n("5")] { + let m = maps(&[], &[("u", wrong)]); + assert_eq!( + message(validate_key_condition_types(&kc, &m, &b_pk)).as_deref(), + Some(KEY_CONDITION_TYPE_MISMATCH) + ); + } +} + +#[test] +fn name_reference_resolves_to_the_defined_attribute() { + let kc = parse("#p = :u"); + let m = maps(&[("p", "pk")], &[("u", n("5"))]); + assert_eq!( + message(validate_key_condition_types(&kc, &m, &defs(SS))).as_deref(), + Some(KEY_CONDITION_TYPE_MISMATCH) + ); + let m = maps(&[("p", "pk")], &[("u", s("x"))]); + assert!(validate_key_condition_types(&kc, &m, &defs(SS)).is_ok()); +} + +#[test] +fn index_key_schema_uses_the_index_attribute_definition() { + // A GSI on gpk (S) with a range key gsk (S) on a table whose base sort key is N. + let d = defs(&[ + ("pk", ScalarAttributeType::S), + ("sk", ScalarAttributeType::N), + ("gpk", ScalarAttributeType::S), + ("gsk", ScalarAttributeType::S), + ]); + let kc = parse("gpk = :g AND gsk = :s"); + let m = maps(&[], &[("g", s("x")), ("s", n("5"))]); + assert_eq!( + message(validate_key_condition_types(&kc, &m, &d)).as_deref(), + Some(KEY_CONDITION_TYPE_MISMATCH) + ); + let m = maps(&[], &[("g", s("x")), ("s", s("g"))]); + assert!(validate_key_condition_types(&kc, &m, &d).is_ok()); +} + +#[test] +fn multipart_hash_conditions_are_checked() { + let d = defs(&[ + ("g1", ScalarAttributeType::S), + ("g2", ScalarAttributeType::N), + ("r", ScalarAttributeType::S), + ]); + let mut kc = parse("g1 = :a AND g2 = :b AND r > :c"); + let names = HashMap::new(); + kc.resolve_multipart(&["g1", "g2"], &names) + .expect("resolve"); + assert_eq!(kc.extra_pk_conditions.len(), 1); + let m = maps(&[], &[("a", s("x")), ("b", s("1")), ("c", s("r"))]); + assert_eq!( + message(validate_key_condition_types(&kc, &m, &d)).as_deref(), + Some(KEY_CONDITION_TYPE_MISMATCH) + ); + let m = maps(&[], &[("a", s("x")), ("b", n("1")), ("c", s("r"))]); + assert!(validate_key_condition_types(&kc, &m, &d).is_ok()); +} + +#[test] +fn undefined_placeholder_and_undefined_attribute_are_left_to_other_checks() { + let kc = parse("pk = :u AND sk = :zz"); + let m = maps(&[], &[("u", n("5"))]); + // The partition value is wrong, and :zz is undefined: the service reports + // the undefined placeholder first, so the type check stands aside. + assert!(validate_key_condition_types(&kc, &m, &defs(SS)).is_ok()); + let m = maps(&[], &[("u", s("x"))]); + assert!(validate_key_condition_types(&kc, &m, &defs(SS)).is_ok()); + + // No AttributeDefinition for the attribute: not this check's refusal. + let kc = parse("other = :u"); + let m = maps(&[], &[("u", n("5"))]); + assert!(validate_key_condition_types(&kc, &m, &defs(SS)).is_ok()); +} + +fn query(body: serde_json::Value) -> QueryInput { + serde_json::from_value(body).expect("QueryInput") +} + +#[test] +fn number_values_that_are_not_numbers_are_refused_with_the_bare_message() { + let cases = [ + ( + "bob", + "The parameter cannot be converted to a numeric value: bob", + ), + ( + "1e", + "The parameter cannot be converted to a numeric value: 1e", + ), + ( + "12abc", + "The parameter cannot be converted to a numeric value: 12abc", + ), + ( + " 5", + "The parameter cannot be converted to a numeric value: 5", + ), + ("", "The parameter cannot be converted to a numeric value: "), + ( + "1e200", + "Number overflow. Attempting to store a number with magnitude larger than supported range", + ), + ]; + for (raw, expected) in cases { + let values = HashMap::from([(":u".to_owned(), n(raw))]); + assert_eq!( + message(validate_expression_attribute_value_numbers(&values)).as_deref(), + Some(expected), + "{raw:?}" + ); + } + let values = HashMap::from([(":u".to_owned(), n(&"1".repeat(39)))]); + assert_eq!( + message(validate_expression_attribute_value_numbers(&values)).as_deref(), + Some("Attempting to store more than 38 significant digits in a Number") + ); +} + +#[test] +fn number_values_that_are_numbers_and_other_types_pass() { + let values = HashMap::from([ + (":u".to_owned(), n("5")), + (":v".to_owned(), n("-1.5e3")), + (":w".to_owned(), s("bob")), + (":x".to_owned(), AttributeValue::Bool(true)), + (":y".to_owned(), AttributeValue::L(vec![n("1"), s("bob")])), + ]); + assert!(validate_expression_attribute_value_numbers(&values).is_ok()); +} + +#[test] +fn every_value_in_the_map_is_checked_whatever_reads_it() { + // :n is read by nothing in the key condition: checked all the same. + let values = HashMap::from([(":p".to_owned(), s("x")), (":n".to_owned(), n("bob"))]); + assert_eq!( + message(validate_expression_attribute_value_numbers(&values)).as_deref(), + Some("The parameter cannot be converted to a numeric value: bob") + ); +} + +#[test] +fn numbers_nested_in_sets_lists_and_maps_are_checked() { + let nested = [ + AttributeValue::NS(["1".to_owned(), "bob".to_owned()].into_iter().collect()), + AttributeValue::L(vec![s("a"), n("bob")]), + AttributeValue::M([("a".to_owned(), n("bob"))].into_iter().collect()), + AttributeValue::M( + [( + "a".to_owned(), + AttributeValue::L(vec![AttributeValue::M( + [("b".to_owned(), n("bob"))].into_iter().collect(), + )]), + )] + .into_iter() + .collect(), + ), + ]; + for value in nested { + let values = HashMap::from([(":p".to_owned(), s("x")), (":n".to_owned(), value.clone())]); + assert_eq!( + message(validate_expression_attribute_value_numbers(&values)).as_deref(), + Some("The parameter cannot be converted to a numeric value: bob"), + "{value:?}" + ); + } +} + +#[test] +fn first_invalid_number_in_placeholder_order_is_reported() { + let values = HashMap::from([(":b".to_owned(), n("two")), (":a".to_owned(), n("one"))]); + assert_eq!( + message(validate_expression_attribute_value_numbers(&values)).as_deref(), + Some("The parameter cannot be converted to a numeric value: one") + ); +} + +#[test] +fn request_time_checks_run_limit_then_mix_then_numbers() { + let bad_number = serde_json::json!({ + "TableName": "t", + "KeyConditionExpression": "pk = :u", + "ExpressionAttributeValues": {":u": {"N": "bob"}}, + }); + + let mut with_limit = bad_number.clone(); + with_limit["Limit"] = serde_json::json!(0); + assert_eq!( + message(validate_query_request_values(&query(with_limit))).as_deref(), + Some(LIMIT_BELOW_ONE) + ); + + let mut with_mix = bad_number.clone(); + with_mix["KeyConditions"] = serde_json::json!({ + "pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]} + }); + assert_eq!( + message(validate_query_request_values(&query(with_mix))).as_deref(), + Some( + "Can not use both expression and non-expression parameters in the same request: \ + Non-expression parameters: {KeyConditions} Expression parameters: {KeyConditionExpression}" + ) + ); + + assert_eq!( + message(validate_query_request_values(&query(bad_number))).as_deref(), + Some("The parameter cannot be converted to a numeric value: bob") + ); + + // A number only a FilterExpression reads, and one nothing reads. + for body in [ + serde_json::json!({ + "TableName": "t", + "KeyConditionExpression": "pk = :p", + "FilterExpression": "a = :n", + "ExpressionAttributeValues": {":p": {"S": "x"}, ":n": {"N": "bob"}}, + }), + serde_json::json!({ + "TableName": "t", + "KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": {":p": {"S": "x"}, ":n": {"N": "bob"}}, + }), + ] { + assert_eq!( + message(validate_query_request_values(&query(body))).as_deref(), + Some("The parameter cannot be converted to a numeric value: bob") + ); + } + + // Legacy KeyConditions alone does not join the mix check; a well-formed + // request passes. + let legacy = serde_json::json!({ + "TableName": "t", + "KeyConditions": { + "pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]} + }, + "FilterExpression": "a = :n", + "ExpressionAttributeValues": {":n": {"N": "5"}}, + "Limit": 1, + }); + assert!(validate_query_request_values(&query(legacy)).is_ok()); +} diff --git a/crates/server/src/request_helpers.rs b/crates/server/src/request_helpers.rs index e7d12abf9..9f34b2632 100755 --- a/crates/server/src/request_helpers.rs +++ b/crates/server/src/request_helpers.rs @@ -184,6 +184,20 @@ pub(crate) async fn authorize_request( authz_resource::validate_tag_resource_arn_shape(arn)?; } + // A Query's request-time checks (Limit, the expression and non-expression + // parameter mix, every number in ExpressionAttributeValues) run before the + // IAM decision, for every principal. The engine makes the same checks at + // request time; they run here as well because authorization binds no + // dynamodb:LeadingKeys value to a number it cannot parse, and a fence that + // needs the key present (ForAnyValue, a Null guard, the plain operators) + // would otherwise answer AccessDeniedException where ValidationException is + // the request's error. A body the engine cannot deserialize is left to it. + if operation == "Query" + && let Ok(query) = serde_json::from_value::(input.clone()) + { + extenddb_engine::query_key_values::validate_query_request_values(&query)?; + } + // Every other ARN-bearing field (StreamArn, BackupArn, the export TableArn, // a restore SourceTableArn) must parse to the resource kind the operation // takes, or the request is refused with ValidationException before the IAM diff --git a/tests/test_query_key_value_types.py b/tests/test_query_key_value_types.py new file mode 100644 index 000000000..02ee3b317 --- /dev/null +++ b/tests/test_query_key_value_types.py @@ -0,0 +1,489 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Query key condition values checked against the key schema. + +A ``KeyConditionExpression`` value is refused before any row is read when an +``N`` value is not a number (``The parameter cannot be converted to a numeric +value: ``) or when a key condition value's type is not the key +attribute's ``AttributeDefinitions`` type (``One or more parameter values were +invalid: Condition parameter type does not match schema type``). Every expected +answer below was measured against the service on 2026-10-24 (15:10 UTC and +21:00 UTC) on tables with S/S, S/N and B/B keys, a GSI and an LSI. The rows +also pin where the two checks fall against the other Query checks: the numeric +check after Limit and the expression parameter mix check and before the table +lookup; the type check after the key schema, filter, projection, unused value +and Select checks and before the ExclusiveStartKey check. + +Dual-target: runs against the service and against extenddb with the same +assertions. The LeadingKeys class needs the extenddb management API and is +skipped against the service. + +Run: + EXTENDDB_TEST_ENDPOINT=https://localhost:18443 \\ + EXTENDDB_ADMIN_USER=admin EXTENDDB_ADMIN_PASSWORD= \\ + pytest tests/test_query_key_value_types.py -v +""" + +from __future__ import annotations + +import os +import uuid +from typing import Any + +import boto3 +import pytest +from botocore.config import Config as BotoConfig +from botocore.exceptions import ClientError + +from conftest import scoped_table, wait_for_active + +NUMERIC = "The parameter cannot be converted to a numeric value: " +TYPE_MISMATCH = ( + "One or more parameter values were invalid: " + "Condition parameter type does not match schema type" +) + +S = {"AttributeType": "S"} + + +def _err(exc_info) -> tuple[str, str]: + err = exc_info.value.response["Error"] + return err["Code"], err["Message"] + + +@pytest.fixture(scope="module") +def ss_table(dynamodb_client): + """pk S, sk S; LSI lsi1 on lsk S; GSI gsi1 on gpk S (hash only).""" + with scoped_table( + dynamodb_client, + attribute_definitions=[ + {"AttributeName": "pk", **S}, + {"AttributeName": "sk", **S}, + {"AttributeName": "lsk", **S}, + {"AttributeName": "gpk", **S}, + ], + key_schema=[ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"}, + ], + LocalSecondaryIndexes=[{ + "IndexName": "lsi1", + "KeySchema": [ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "lsk", "KeyType": "RANGE"}, + ], + "Projection": {"ProjectionType": "ALL"}, + }], + GlobalSecondaryIndexes=[{ + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "gpk", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"}, + }], + ) as name: + for pk in ("alice", "bob"): + dynamodb_client.put_item(TableName=name, Item={ + "pk": {"S": pk}, "sk": {"S": "1"}, "lsk": {"S": "l"}, "gpk": {"S": pk}}) + yield name + + +@pytest.fixture(scope="module") +def ns_table(dynamodb_client): + """pk S, sk N; GSI gsi1 on gpk S / gsk S.""" + with scoped_table( + dynamodb_client, + attribute_definitions=[ + {"AttributeName": "pk", **S}, + {"AttributeName": "sk", "AttributeType": "N"}, + {"AttributeName": "gpk", **S}, + {"AttributeName": "gsk", **S}, + ], + key_schema=[ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"}, + ], + GlobalSecondaryIndexes=[{ + "IndexName": "gsi1", + "KeySchema": [ + {"AttributeName": "gpk", "KeyType": "HASH"}, + {"AttributeName": "gsk", "KeyType": "RANGE"}, + ], + "Projection": {"ProjectionType": "ALL"}, + }], + ) as name: + for pk in ("alice", "bob"): + dynamodb_client.put_item(TableName=name, Item={ + "pk": {"S": pk}, "sk": {"N": "5"}, "gpk": {"S": pk}, "gsk": {"S": "g"}}) + yield name + + +@pytest.fixture(scope="module") +def bb_table(dynamodb_client): + """bpk B, bsk B.""" + with scoped_table( + dynamodb_client, + attribute_definitions=[ + {"AttributeName": "bpk", "AttributeType": "B"}, + {"AttributeName": "bsk", "AttributeType": "B"}, + ], + key_schema=[ + {"AttributeName": "bpk", "KeyType": "HASH"}, + {"AttributeName": "bsk", "KeyType": "RANGE"}, + ], + ) as name: + dynamodb_client.put_item(TableName=name, Item={"bpk": {"B": b"bob"}, "bsk": {"B": b"x"}}) + yield name + + +NB = {"N": "bob"} +N5 = {"N": "5"} +SX = {"S": "x"} +B_BOB = {"B": b"bob"} +MISSING = "no-such-table-kv-types" +LEGACY_PK = {"pk": {"ComparisonOperator": "EQ", "AttributeValueList": [SX]}} +L_NB = {"L": [{"S": "a"}, NB]} +M_NB = {"M": {"a": NB}} +NS_NB = {"NS": ["1", "bob"]} + +LIMIT_MSG = ( + "1 validation error detected: Value at 'Limit' failed to satisfy constraint: " + "Member must have value greater than or equal to 1" +) +MIX_MSG = ( + "Can not use both expression and non-expression parameters in the same request: " + "Non-expression parameters: {KeyConditions} Expression parameters: {KeyConditionExpression}" +) +OVERFLOW_MSG = ( + "Number overflow. Attempting to store a number with magnitude larger than supported range" +) +DIGITS_MSG = "Attempting to store more than 38 significant digits in a Number" +MISSED_PK = "Query condition missed key schema element: pk" +MISSED_GPK = "Query condition missed key schema element: gpk" +RESERVED_KCE = ( + "Invalid KeyConditionExpression: Attribute name is a reserved keyword; reserved keyword: other" +) +NO_INDEX = "The table does not have the specified index: nope" +UNUSED_X = "Value provided in ExpressionAttributeValues unused in expressions: keys: {:x}" +GSI_CONSISTENT = "Consistent reads are not supported on global secondary indexes" +FILTER_BEGINS_WITH_N = ( + "Invalid FilterExpression: Incorrect operand type for operator or function; " + "operator or function: begins_with, operand type: N" +) +PROJECTION_OVERLAP = ( + "Invalid ProjectionExpression: Two document paths overlap with each other; " + "must remove or rewrite one of these paths; path one: [a], path two: [a, b]" +) +FILTER_RESERVED = ( + "Invalid FilterExpression: Attribute name is a reserved keyword; reserved keyword: name" +) +SELECT_PROJECTION = ( + "1 validation error detected: Cannot specify the ProjectionExpression when choosing to " + "get ALL_ATTRIBUTES" +) +V = "ValidationException" +RNF = "ResourceNotFoundException" + + +def kce(expr, values, **extra): + return {"KeyConditionExpression": expr, "ExpressionAttributeValues": values, **extra} + + +# (row, table, Query arguments, expected error code, expected message). +# Tables: ss (pk S, sk S, LSI lsi1 on lsk S, GSI gsi1 on gpk S), ns (pk S, sk N, +# GSI gsi1 on gpk S / gsk S), bb (bpk B, bsk B), missing (no such table). +ROWS = [ + # The numeric check against the other Query checks. + ("a1 missing table", "missing", kce("pk = :u", {":u": NB}), V, NUMERIC + "bob"), + ("a2 unknown IndexName", "ss", kce("pk = :u", {":u": NB}, IndexName="nope"), V, NUMERIC + "bob"), + ("a3 undefined placeholder", "ss", kce("pk = :u AND sk = :zz", {":u": NB}), V, NUMERIC + "bob"), + ("a4 unused value", "ss", kce("pk = :u", {":u": NB, ":x": SX}), V, NUMERIC + "bob"), + ("a5 syntax error", "ss", kce("pk = :u AND", {":u": NB}), V, NUMERIC + "bob"), + ("a6 Limit 0", "ss", kce("pk = :u", {":u": NB}, Limit=0), V, LIMIT_MSG), + ("a7 N bob only in FilterExpression", "ss", + kce("pk = :p", {":p": SX, ":n": NB}, FilterExpression="a = :n"), V, NUMERIC + "bob"), + ("a8 N bob unused", "ss", kce("pk = :p", {":p": SX, ":n": NB}), V, NUMERIC + "bob"), + ("a9 N bob in filter beside pk = N 5", "ss", + kce("pk = :p", {":p": N5, ":n": NB}, FilterExpression="a = :n"), V, NUMERIC + "bob"), + ("a10 ConsistentRead on GSI", "ss", + kce("gpk = :u", {":u": NB}, IndexName="gsi1", ConsistentRead=True), V, NUMERIC + "bob"), + ("a11 N empty", "ss", kce("pk = :u", {":u": {"N": ""}}), V, NUMERIC), + ("a12 N 1e", "ss", kce("pk = :u", {":u": {"N": "1e"}}), V, NUMERIC + "1e"), + ("a13 N 12abc", "ss", kce("pk = :u", {":u": {"N": "12abc"}}), V, NUMERIC + "12abc"), + ("a14 sk only", "ss", kce("sk = :u", {":u": NB}), V, NUMERIC + "bob"), + ("a15 KeyConditions and KeyConditionExpression", "ss", + kce("pk = :u", {":u": NB}, KeyConditions=LEGACY_PK), V, MIX_MSG), + ("a16 BETWEEN bounds reversed", "ss", + kce("pk = :u AND sk BETWEEN :a AND :b", {":u": NB, ":a": {"S": "b"}, ":b": {"S": "a"}}), + V, NUMERIC + "bob"), + ("a17 nested path", "ss", kce("pk.x = :u", {":u": NB}), V, NUMERIC + "bob"), + ("a18 pk >", "ss", kce("pk > :u", {":u": NB}), V, NUMERIC + "bob"), + ("a19 ExclusiveStartKey bad", "ss", + kce("pk = :u", {":u": NB}, ExclusiveStartKey={"zz": SX}), V, NUMERIC + "bob"), + ("a20 pk = B AND sk = N bob", "ss", + kce("pk = :u AND sk = :s", {":u": B_BOB, ":s": NB}), V, NUMERIC + "bob"), + ("a21 pk = S AND sk = N bob", "ss", + kce("pk = :u AND sk = :s", {":u": SX, ":s": NB}), V, NUMERIC + "bob"), + ("a22 N 1e200", "ss", kce("pk = :u", {":u": {"N": "1e200"}}), V, OVERFLOW_MSG), + ("a23 N 39 digits", "ss", kce("pk = :u", {":u": {"N": "1" * 39}}), V, DIGITS_MSG), + ("a24 Select ALL_ATTRIBUTES with ProjectionExpression", "ss", + kce("pk = :u", {":u": NB}, Select="ALL_ATTRIBUTES", ProjectionExpression="a"), + V, NUMERIC + "bob"), + ("a25 reserved word in filter", "ss", + kce("pk = :u", {":u": NB, ":n": SX}, FilterExpression="name = :n"), V, NUMERIC + "bob"), + ("a26 undefined name in filter", "ss", + kce("pk = :u", {":u": NB, ":n": SX}, FilterExpression="#n = :n"), V, NUMERIC + "bob"), + ("a27 two sort key conditions", "ss", + kce("pk = :u AND sk = :s AND sk > :t", {":u": NB, ":s": N5, ":t": {"N": "6"}}), + V, NUMERIC + "bob"), + ("a28 sk = N bob with unused value", "ss", + kce("pk = :u AND sk = :s", {":u": SX, ":s": NB, ":x": SX}), V, NUMERIC + "bob"), + ("a29 ProjectionExpression overlap", "ss", + kce("pk = :u", {":u": NB}, ProjectionExpression="a, a.b"), V, NUMERIC + "bob"), + ("a30 N space 5", "ss", kce("pk = :u", {":u": {"N": " 5"}}), V, NUMERIC + " 5"), + # The type check against the other key condition checks. + ("b1 sk = N 5 only", "ss", kce("sk = :s", {":s": N5}), V, MISSED_PK), + ("b2 reserved word in key condition", "ss", + kce("pk = :u AND other = :s", {":u": SX, ":s": N5}), V, RESERVED_KCE), + ("b4 BETWEEN N bounds on S sk", "ss", + kce("pk = :u AND sk BETWEEN :a AND :b", {":u": SX, ":a": {"N": "1"}, ":b": {"N": "2"}}), + V, TYPE_MISMATCH), + ("b6 sk > N 5", "ss", kce("pk = :u AND sk > :s", {":u": SX, ":s": N5}), V, TYPE_MISMATCH), + ("b7 sk < B", "ss", kce("pk = :u AND sk < :s", {":u": SX, ":s": B_BOB}), V, TYPE_MISMATCH), + ("b9 unknown IndexName", "ss", kce("pk = :u", {":u": N5}, IndexName="nope"), V, NO_INDEX), + ("b10 Limit 0", "ss", kce("pk = :u", {":u": N5}, Limit=0), V, LIMIT_MSG), + ("b11 unused value", "ss", kce("pk = :u", {":u": N5, ":x": SX}), V, UNUSED_X), + ("b13 missing table", "missing", kce("pk = :u", {":u": N5}), RNF, "Requested resource not found"), + ("b14 GSI gpk = N 5", "ss", kce("gpk = :g", {":g": N5}, IndexName="gsi1"), V, TYPE_MISMATCH), + ("b15 LSI lsk = N 5", "ss", + kce("pk = :u AND lsk = :l", {":u": SX, ":l": N5}, IndexName="lsi1"), V, TYPE_MISMATCH), + ("b16 GSI with base pk = N 5", "ss", kce("pk = :u", {":u": N5}, IndexName="gsi1"), V, MISSED_GPK), + ("b17 GSI with base pk = S", "ss", kce("pk = :u", {":u": SX}, IndexName="gsi1"), V, MISSED_GPK), + ("b18 N sk = S 5", "ns", kce("pk = :u AND sk = :s", {":u": SX, ":s": {"S": "5"}}), V, TYPE_MISMATCH), + ("b19 N sk BETWEEN S", "ns", + kce("pk = :u AND sk BETWEEN :a AND :b", {":u": SX, ":a": {"S": "1"}, ":b": {"S": "2"}}), + V, TYPE_MISMATCH), + ("b20 N sk begins_with S", "ns", + kce("pk = :u AND begins_with(sk, :b)", {":u": SX, ":b": {"S": "1"}}), V, TYPE_MISMATCH), + ("b22 pk = N 5 AND N sk = S 5", "ns", + kce("pk = :u AND sk = :s", {":u": N5, ":s": {"S": "5"}}), V, TYPE_MISMATCH), + ("b23 N sk = N bob", "ns", kce("pk = :u AND sk = :s", {":u": SX, ":s": NB}), V, NUMERIC + "bob"), + ("b24 B pk = S", "bb", kce("bpk = :u", {":u": SX}), V, TYPE_MISMATCH), + ("b25 B pk = N 5", "bb", kce("bpk = :u", {":u": N5}), V, TYPE_MISMATCH), + ("b26 B pk = N bob", "bb", kce("bpk = :u", {":u": NB}), V, NUMERIC + "bob"), + ("b27 B sk begins_with S", "bb", + kce("bpk = :u AND begins_with(bsk, :b)", {":u": B_BOB, ":b": SX}), V, TYPE_MISMATCH), + ("b28 ConsistentRead on GSI", "ss", + kce("gpk = :g", {":g": N5}, IndexName="gsi1", ConsistentRead=True), V, GSI_CONSISTENT), + ("b29 filter begins_with N", "ss", + kce("pk = :u", {":u": N5, ":n": {"N": "1"}}, FilterExpression="begins_with(a, :n)"), + V, FILTER_BEGINS_WITH_N), + ("b30 ProjectionExpression overlap", "ss", + kce("pk = :u", {":u": N5}, ProjectionExpression="a, a.b"), V, PROJECTION_OVERLAP), + ("b31 ExclusiveStartKey bad", "ss", + kce("pk = :u", {":u": N5}, ExclusiveStartKey={"zz": SX}), V, TYPE_MISMATCH), + ("b32 pk = N 5 AND sk = N bob", "ss", + kce("pk = :u AND sk = :s", {":u": N5, ":s": NB}), V, NUMERIC + "bob"), + ("b33 pk = B AND sk = N 5", "ss", + kce("pk = :u AND sk = :s", {":u": B_BOB, ":s": N5}), V, TYPE_MISMATCH), + ("b35 pk = NULL", "ss", kce("pk = :u", {":u": {"NULL": True}}), V, TYPE_MISMATCH), + ("b36 pk = SS", "ss", kce("pk = :u", {":u": {"SS": ["a"]}}), V, TYPE_MISMATCH), + ("b37 pk = L", "ss", kce("pk = :u", {":u": {"L": [SX]}}), V, TYPE_MISMATCH), + ("b38 pk = M", "ss", kce("pk = :u", {":u": {"M": {"a": SX}}}), V, TYPE_MISMATCH), + ("b41 reserved word in filter", "ss", + kce("pk = :u", {":u": N5, ":n": SX}, FilterExpression="name = :n"), V, FILTER_RESERVED), + ("b42 Select ALL_ATTRIBUTES with ProjectionExpression", "ss", + kce("pk = :u", {":u": N5}, Select="ALL_ATTRIBUTES", ProjectionExpression="a"), + V, SELECT_PROJECTION), + ("b43 non-key second clause", "ss", + kce("pk = :u AND other = :s", {":u": N5, ":s": SX}), V, RESERVED_KCE), + ("b45 pk = N 5 through #p", "ss", + kce("#p = :u", {":u": N5}, ExpressionAttributeNames={"#p": "pk"}), V, TYPE_MISMATCH), + ("b46 reversed operands", "ss", + kce("pk = :u AND :s <= sk", {":u": SX, ":s": N5}), V, TYPE_MISMATCH), + ("b47 GSI gsk = N 5", "ns", + kce("gpk = :g AND gsk = :s", {":g": SX, ":s": N5}, IndexName="gsi1"), V, TYPE_MISMATCH), + # Nested N values, values no expression reads, and the Limit and mix checks + # against the table and index lookups (measured 2026-10-24 21:06 UTC). + ("c1 L with N bob in filter", "ss", + kce("pk = :p", {":p": SX, ":l": L_NB}, FilterExpression="a = :l"), V, NUMERIC + "bob"), + ("c2 L with N bob unused", "ss", kce("pk = :p", {":p": SX, ":l": L_NB}), V, NUMERIC + "bob"), + ("c3 M with N bob in filter", "ss", + kce("pk = :p", {":p": SX, ":m": M_NB}, FilterExpression="a = :m"), V, NUMERIC + "bob"), + ("c4 M with N bob unused", "ss", kce("pk = :p", {":p": SX, ":m": M_NB}), V, NUMERIC + "bob"), + ("c5 NS with bob in filter", "ss", + kce("pk = :p", {":p": SX, ":n": NS_NB}, FilterExpression="a = :n"), V, NUMERIC + "bob"), + ("c6 NS with bob unused", "ss", kce("pk = :p", {":p": SX, ":n": NS_NB}), V, NUMERIC + "bob"), + ("c7 L with N empty in filter", "ss", + kce("pk = :p", {":p": SX, ":l": {"L": [{"N": ""}]}}, FilterExpression="a = :l"), V, NUMERIC), + ("c8 M in L in M with N bob", "ss", + kce("pk = :p", {":p": SX, ":m": {"M": {"a": {"L": [M_NB]}}}}), V, NUMERIC + "bob"), + ("c9 N bob unused on a missing table", "missing", + kce("pk = :p", {":p": SX, ":n": NB}), V, NUMERIC + "bob"), + ("c12 N bob with no key condition", "ss", + {"ExpressionAttributeValues": {":n": NB}}, V, NUMERIC + "bob"), + ("c13 N bob beside legacy KeyConditions", "ss", + {"KeyConditions": LEGACY_PK, "ExpressionAttributeValues": {":n": NB}}, V, NUMERIC + "bob"), + ("d1 Limit 0 on a missing table", "missing", kce("pk = :p", {":p": SX}, Limit=0), V, LIMIT_MSG), + ("d2 Limit 0 with unknown IndexName", "ss", + kce("pk = :p", {":p": SX}, IndexName="nope", Limit=0), V, LIMIT_MSG), + ("d3 Limit 0 with ConsistentRead on GSI", "ss", + kce("gpk = :p", {":p": SX}, IndexName="gsi1", ConsistentRead=True, Limit=0), V, LIMIT_MSG), + ("d4 KeyConditions and KeyConditionExpression on a missing table", "missing", + kce("pk = :p", {":p": SX}, KeyConditions=LEGACY_PK), V, MIX_MSG), + ("d5 Limit 0 with KeyConditions and KeyConditionExpression", "ss", + kce("pk = :p", {":p": SX}, Limit=0, KeyConditions=LEGACY_PK), V, LIMIT_MSG), + ("d6 Limit 0 with N bob and an undefined placeholder", "ss", + kce("pk = :p AND sk = :zz", {":p": SX, ":n": NB}, Limit=0), V, LIMIT_MSG), + # The other value types the earlier record covers. + ("pk = BOOL", "ss", kce("pk = :u", {":u": {"BOOL": True}}), V, TYPE_MISMATCH), + ("pk = N bob AND pk > S alice", "ss", + kce("pk = :u AND pk > :v", {":u": NB, ":v": {"S": "alice"}}), V, NUMERIC + "bob"), +] + + +class TestKeyConditionValueTypes: + """Each row: a Query and the service's answer.""" + + @pytest.fixture + def tables(self, ss_table, ns_table, bb_table): + return {"ss": ss_table, "ns": ns_table, "bb": bb_table, "missing": MISSING} + + @pytest.mark.parametrize("row,table,kwargs,code,expected", ROWS, ids=[r[0] for r in ROWS]) + def test_rows(self, dynamodb_client_no_validation, tables, row, table, kwargs, code, expected): + with pytest.raises(ClientError) as exc_info: + dynamodb_client_no_validation.query(TableName=tables[table], **kwargs) + assert _err(exc_info) == (code, expected) + + def test_matching_types_read_the_named_partition(self, dynamodb_client, ss_table): + resp = dynamodb_client.query( + TableName=ss_table, KeyConditionExpression="pk = :u", + ExpressionAttributeValues={":u": {"S": "bob"}}) + assert [it["pk"]["S"] for it in resp["Items"]] == ["bob"] + + def test_control_matching_types_on_every_table(self, dynamodb_client, ss_table, ns_table, bb_table): + assert dynamodb_client.query( + TableName=ss_table, KeyConditionExpression="pk = :u AND sk = :s", + ExpressionAttributeValues={":u": {"S": "nope"}, ":s": SX})["Count"] == 0 + assert dynamodb_client.query( + TableName=ns_table, KeyConditionExpression="pk = :u AND sk > :s", + ExpressionAttributeValues={":u": {"S": "bob"}, ":s": {"N": "1"}})["Count"] == 1 + assert dynamodb_client.query( + TableName=bb_table, KeyConditionExpression="bpk = :u", + ExpressionAttributeValues={":u": B_BOB})["Count"] == 1 + + +class TestLeadingKeysWithAnInvalidKeyValue: + """A principal under each LeadingKeys fence form gets ValidationException and + no items for a Query whose ExpressionAttributeValues carries an N value that + is not a number, whether the key condition, the filter or nothing reads it. + + extenddb only: the fences need users created through the management API.""" + + @pytest.fixture(autouse=True) + def setup(self): + endpoint = os.environ.get("EXTENDDB_TEST_ENDPOINT", "").strip() + admin_user = os.environ.get("EXTENDDB_ADMIN_USER", "").strip() + admin_pass = os.environ.get("EXTENDDB_ADMIN_PASSWORD", "").strip() + if not endpoint: + pytest.skip("LeadingKeys fences need the extenddb management API") + if not admin_user or not admin_pass: + pytest.fail("MISCONFIGURED: EXTENDDB_ADMIN_USER and EXTENDDB_ADMIN_PASSWORD are required") + from management_helpers import ManagementClient + + self.endpoint = endpoint + self.region = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") + self.mgmt = ManagementClient(endpoint, admin_user, admin_pass) + self.account_id = f"{uuid.uuid4().int % 10**12:012d}" + resp = self.mgmt.create_account(self.account_id, f"kv-test-{self.account_id}") + assert resp.status_code == 201, resp.text + self._users: list[str] = [] + yield + for u in self._users: + try: + self.mgmt.delete_user(self.account_id, u) + except Exception: + pass + self.mgmt.delete_account(self.account_id) + + def _client(self, policy: dict | None) -> Any: + name = f"kv-{uuid.uuid4().hex[:8]}" + resp = self.mgmt.create_user(self.account_id, name, "TestPass123!") + assert resp.status_code == 201, resp.text + self._users.append(name) + resp = self.mgmt.create_access_key(self.account_id, name) + assert resp.status_code == 201, resp.text + creds = resp.json() + if policy is not None: + resp = self.mgmt.put_user_policy(self.account_id, name, "p", policy) + assert resp.status_code == 204, resp.text + return boto3.client( + "dynamodb", endpoint_url=self.endpoint, region_name=self.region, + aws_access_key_id=creds["access_key_id"], + aws_secret_access_key=creds["secret_access_key"], + verify=False, + config=BotoConfig(retries={"max_attempts": 0}, parameter_validation=False)) + + def _fence(self, condition: dict, table: str) -> dict: + arn = f"arn:aws:dynamodb:{self.region}:{self.account_id}:table/{table}" + return { + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Allow", + "Action": "dynamodb:*", + "Resource": [arn, arn + "/index/*"], + "Condition": condition, + }], + } + + def test_every_fence_form_gets_validation_exception_and_no_items(self): + owner = self._client({ + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"}], + }) + table = f"kv-{uuid.uuid4().hex[:8]}" + owner.create_table( + TableName=table, + AttributeDefinitions=[{"AttributeName": "pk", **S}], + KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}], + BillingMode="PAY_PER_REQUEST") + wait_for_active(owner, table) + for pk in ("alice", "bob"): + owner.put_item(TableName=table, Item={"pk": {"S": pk}}) + + fences = { + "ForAllValues": {"ForAllValues:StringEquals": {"dynamodb:LeadingKeys": ["alice"]}}, + "ForAnyValue": {"ForAnyValue:StringEquals": {"dynamodb:LeadingKeys": ["alice"]}}, + "Null false": {"Null": {"dynamodb:LeadingKeys": "false"}, + "ForAllValues:StringEquals": {"dynamodb:LeadingKeys": ["alice"]}}, + "StringEquals": {"StringEquals": {"dynamodb:LeadingKeys": "alice"}}, + "StringLike": {"StringLike": {"dynamodb:LeadingKeys": "ali*"}}, + "StringNotEquals": {"StringNotEquals": {"dynamodb:LeadingKeys": "bob"}}, + } + # The reported shape, and an N value that only the filter reads or + # nothing reads beside a key value the fence would bind. + requests = { + "pk = N bob": {"TableName": table, "KeyConditionExpression": "pk = :u", + "ExpressionAttributeValues": {":u": NB}}, + "pk = S alice, N bob in filter": { + "TableName": table, "KeyConditionExpression": "pk = :u", + "FilterExpression": "a = :n", + "ExpressionAttributeValues": {":u": {"S": "alice"}, ":n": NB}}, + "pk = S bob, N bob unused": { + "TableName": table, "KeyConditionExpression": "pk = :u", + "ExpressionAttributeValues": {":u": {"S": "bob"}, ":n": NB}}, + } + failures = [] + clients = {label: self._client(self._fence(condition, table)) + for label, condition in fences.items()} + clients["owner"] = owner + for shape, request in requests.items(): + for label, client in clients.items(): + try: + resp = client.query(**request) + failures.append(f"{shape} / {label}: {resp['Count']} items returned") + except ClientError as exc: + err = exc.response["Error"] + if (err["Code"], err["Message"]) != ("ValidationException", NUMERIC + "bob"): + failures.append(f"{shape} / {label}: {err['Code']} {err['Message']}") + owner.delete_table(TableName=table) + assert not failures, "\n".join(failures) From f0017ce90ef654ac7957ca1e8f62a8b56b61491d Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sun, 25 Oct 2026 00:35:19 +0000 Subject: [PATCH 02/30] fix(query): run the request-time checks on the raw body, enums in the service's order The server ran its pre-IAM checks only when the body deserialized as QueryInput, and the engine checked the ReturnConsumedCapacity and Select enums before them, so a Query carrying an invalid Select and an N value that is not a number answered the Select message, or AccessDeniedException for a principal whose LeadingKeys fence needs a value. The checks now read the raw body in the service's order, measured 2026-10-24: Limit, the expression and non-expression parameter mix, ReturnConsumedCapacity, every number in ExpressionAttributeValues, then Select. The engine and the server run the same function. --- crates/engine/src/query.rs | 41 ++------- crates/engine/src/query_key_values.rs | 95 +++++++++++++++------ crates/engine/src/query_key_values/tests.rs | 66 +++++++++++--- crates/server/src/request_helpers.rs | 22 ++--- tests/test_query_key_value_types.py | 35 ++++++-- 5 files changed, 173 insertions(+), 86 deletions(-) diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 97e07ead2..a4e633073 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -43,42 +43,15 @@ pub async fn handle_query( body: Value, ctx: &OperationContext, ) -> Result { - // Pre-scanned before typed deserialization, sequentially: Query stops at - // the FIRST invalid enum, checking ReturnConsumedCapacity ahead of Select. - // Measured 2026-08-24 (us-east-1): both invalid answers "1 validation - // error detected" naming returnConsumedCapacity alone. (Scan is the - // opposite on both counts: it aggregates, select-first; see handle_scan.) - crate::validate_enum_fields( - &body, - &[crate::EnumField { - json_name: "ReturnConsumedCapacity", - valid: &["INDEXES", "TOTAL", "NONE"], - clause: crate::EnumClause::Named("returnConsumedCapacity"), - }], - )?; - crate::validate_enum_fields( - &body, - &[crate::EnumField { - json_name: "Select", - valid: &[ - "SPECIFIC_ATTRIBUTES", - "COUNT", - "ALL_ATTRIBUTES", - "ALL_PROJECTED_ATTRIBUTES", - ], - clause: crate::EnumClause::Named("select"), - }], - )?; + // Request-time checks on the raw body, in the service's order: Limit, the + // expression and non-expression parameter mix, the ReturnConsumedCapacity + // enum, every number in ExpressionAttributeValues, the Select enum. They + // run before typed deserialization so a field that does not deserialize + // does not stop the ones before it. The server runs the same function + // ahead of the IAM decision; see `query_key_values`. + crate::query_key_values::validate_query_request_body(&body)?; let input: QueryInput = serde_json::from_value(body).map_err(crate::deserialize_error)?; - // Request-time checks in the service's order: Limit, the expression and - // non-expression parameter mix, then every number in - // ExpressionAttributeValues (measured 2026-10-24: a Limit of 0 and a - // parameter mix are reported ahead of an N value that is not a number, and - // that value is reported ahead of a missing table or index). The server - // runs the same function ahead of the IAM decision; see `query_key_values`. - crate::query_key_values::validate_query_request_values(&input)?; - // P118: Fetch key_info first so we can use table_id for index lookup. let key_info = ctx .table_key_info(&input.table_name) diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index e49968648..7bfb356ba 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -12,7 +12,7 @@ //! checked, whether the key condition, the filter or nothing reads it. The //! check runs at request time, after the `Limit` check and the expression //! and non-expression parameter mix check, and before the table is looked -//! up; see [`validate_query_request_values`]; +//! up; see [`validate_query_request_body`]; //! 2. a key condition value whose type is not the key attribute's //! `AttributeDefinitions` type answers `One or more parameter values were //! invalid: Condition parameter type does not match schema type`, on the @@ -33,7 +33,8 @@ use extenddb_core::error::DynamoDbError; use extenddb_core::expression::{ Expr, ExpressionMaps, KeyCondition, PathElement, SortKeyCondition, }; -use extenddb_core::types::{AttributeDefinition, AttributeValue, QueryInput, ScalarAttributeType}; +use extenddb_core::types::{AttributeDefinition, AttributeValue, ScalarAttributeType}; +use serde_json::Value; /// The service's text for a key condition value of the wrong type. pub const KEY_CONDITION_TYPE_MISMATCH: &str = "One or more parameter values were invalid: Condition parameter type does not match schema type"; @@ -44,10 +45,18 @@ pub const LIMIT_BELOW_ONE: &str = "1 validation error detected: Value at 'Limit' /// The bare numeric message the number validator uses for an empty `N`. const EMPTY_NUMBER: &str = "The parameter cannot be converted to a numeric value"; -/// The `Query` checks that run on the request alone, before the table is -/// looked up, in the service's order: `Limit`, the expression and -/// non-expression parameter mix, then every number in -/// `ExpressionAttributeValues`. +/// The `Query` checks that run on the request body alone, before the body is +/// deserialized and before the table is looked up, in the service's order: +/// `Limit`, the expression and non-expression parameter mix, the +/// `ReturnConsumedCapacity` enum, every number in `ExpressionAttributeValues`, +/// then the `Select` enum (measured 2026-10-24: a `Limit` of 0 and a parameter +/// mix are reported ahead of an invalid enum value of either field, an invalid +/// `ReturnConsumedCapacity` ahead of an `N` value that is not a number, and +/// that value ahead of an invalid `Select`). +/// +/// The checks read the raw body, so a field that does not deserialize (an +/// invalid `Select`, for one) does not stop the ones before it. A field of the +/// wrong JSON shape is left to the deserializer, which runs next. /// /// The server runs the same function ahead of the IAM decision, so a principal /// whose `dynamodb:LeadingKeys` fence cannot bind a number that does not parse @@ -57,8 +66,8 @@ const EMPTY_NUMBER: &str = "The parameter cannot be converted to a numeric value /// # Errors /// /// Returns `DynamoDbError::ValidationException` with the service's text. -pub fn validate_query_request_values(input: &QueryInput) -> Result<(), DynamoDbError> { - if let Some(limit) = input.limit +pub fn validate_query_request_body(body: &Value) -> Result<(), DynamoDbError> { + if let Some(limit) = body.get("Limit").and_then(Value::as_i64) && limit < 1 { return Err(DynamoDbError::ValidationException( @@ -66,36 +75,74 @@ pub fn validate_query_request_values(input: &QueryInput) -> Result<(), DynamoDbE )); } - let kce_present = input.key_condition_expression.is_some(); - let has_kc = input.key_conditions.as_ref().is_some_and(|m| !m.is_empty()); - let has_qf = input.query_filter.as_ref().is_some_and(|m| !m.is_empty()); - let has_atg = input - .attributes_to_get - .as_ref() - .is_some_and(|a| !a.is_empty()); + let kce_present = present(body, "KeyConditionExpression"); // KeyConditions combines with FilterExpression and ProjectionExpression, so // it joins the mix check only when KeyConditionExpression is also present. extenddb_core::validation::validate_no_expression_param_mixing( &[ - ("AttributesToGet", has_atg), - ("QueryFilter", has_qf), - ("ConditionalOperator", input.conditional_operator.is_some()), - ("KeyConditions", has_kc && kce_present), + ("AttributesToGet", non_empty(body, "AttributesToGet")), + ("QueryFilter", non_empty(body, "QueryFilter")), + ("ConditionalOperator", present(body, "ConditionalOperator")), + ( + "KeyConditions", + non_empty(body, "KeyConditions") && kce_present, + ), ], &[ ( "ProjectionExpression", - input.projection_expression.is_some(), + present(body, "ProjectionExpression"), ), - ("FilterExpression", input.filter_expression.is_some()), + ("FilterExpression", present(body, "FilterExpression")), ("KeyConditionExpression", kce_present), ], )?; - if let Some(values) = &input.expression_attribute_values { - validate_expression_attribute_value_numbers(values)?; + // Query stops at the first invalid enum, ReturnConsumedCapacity ahead of + // Select (measured 2026-08-24); the numbers sit between the two. + crate::validate_enum_fields( + body, + &[crate::EnumField { + json_name: "ReturnConsumedCapacity", + valid: &["INDEXES", "TOTAL", "NONE"], + clause: crate::EnumClause::Named("returnConsumedCapacity"), + }], + )?; + + if let Some(raw) = body.get("ExpressionAttributeValues") + && let Ok(values) = serde_json::from_value::>(raw.clone()) + { + validate_expression_attribute_value_numbers(&values)?; + } + + crate::validate_enum_fields( + body, + &[crate::EnumField { + json_name: "Select", + valid: &[ + "SPECIFIC_ATTRIBUTES", + "COUNT", + "ALL_ATTRIBUTES", + "ALL_PROJECTED_ATTRIBUTES", + ], + clause: crate::EnumClause::Named("select"), + }], + ) +} + +/// Whether `field` is in the body with a value other than `null`, as a typed +/// `Option` field would deserialize to `Some`. +fn present(body: &Value, field: &str) -> bool { + body.get(field).is_some_and(|v| !v.is_null()) +} + +/// Whether `field` is a non-empty JSON object or array in the body. +fn non_empty(body: &Value, field: &str) -> bool { + match body.get(field) { + Some(Value::Object(map)) => !map.is_empty(), + Some(Value::Array(items)) => !items.is_empty(), + _ => false, } - Ok(()) } /// Refuse the first `N` value in `ExpressionAttributeValues` (including `NS` diff --git a/crates/engine/src/query_key_values/tests.rs b/crates/engine/src/query_key_values/tests.rs index 6130dd875..d98e66f05 100644 --- a/crates/engine/src/query_key_values/tests.rs +++ b/crates/engine/src/query_key_values/tests.rs @@ -6,11 +6,11 @@ use extenddb_core::error::DynamoDbError; use extenddb_core::expression::{ ExpressionMaps, KeyCondition, parse_key_condition, tokenize_with_limit, }; -use extenddb_core::types::{AttributeDefinition, AttributeValue, QueryInput, ScalarAttributeType}; +use extenddb_core::types::{AttributeDefinition, AttributeValue, ScalarAttributeType}; use super::{ KEY_CONDITION_TYPE_MISMATCH, LIMIT_BELOW_ONE, validate_expression_attribute_value_numbers, - validate_key_condition_types, validate_query_request_values, + validate_key_condition_types, validate_query_request_body, }; fn defs(pairs: &[(&str, ScalarAttributeType)]) -> Vec { @@ -226,10 +226,6 @@ fn undefined_placeholder_and_undefined_attribute_are_left_to_other_checks() { assert!(validate_key_condition_types(&kc, &m, &defs(SS)).is_ok()); } -fn query(body: serde_json::Value) -> QueryInput { - serde_json::from_value(body).expect("QueryInput") -} - #[test] fn number_values_that_are_not_numbers_are_refused_with_the_bare_message() { let cases = [ @@ -339,7 +335,7 @@ fn request_time_checks_run_limit_then_mix_then_numbers() { let mut with_limit = bad_number.clone(); with_limit["Limit"] = serde_json::json!(0); assert_eq!( - message(validate_query_request_values(&query(with_limit))).as_deref(), + message(validate_query_request_body(&with_limit)).as_deref(), Some(LIMIT_BELOW_ONE) ); @@ -348,7 +344,7 @@ fn request_time_checks_run_limit_then_mix_then_numbers() { "pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]} }); assert_eq!( - message(validate_query_request_values(&query(with_mix))).as_deref(), + message(validate_query_request_body(&with_mix)).as_deref(), Some( "Can not use both expression and non-expression parameters in the same request: \ Non-expression parameters: {KeyConditions} Expression parameters: {KeyConditionExpression}" @@ -356,7 +352,7 @@ fn request_time_checks_run_limit_then_mix_then_numbers() { ); assert_eq!( - message(validate_query_request_values(&query(bad_number))).as_deref(), + message(validate_query_request_body(&bad_number)).as_deref(), Some("The parameter cannot be converted to a numeric value: bob") ); @@ -375,7 +371,7 @@ fn request_time_checks_run_limit_then_mix_then_numbers() { }), ] { assert_eq!( - message(validate_query_request_values(&query(body))).as_deref(), + message(validate_query_request_body(&body)).as_deref(), Some("The parameter cannot be converted to a numeric value: bob") ); } @@ -391,5 +387,53 @@ fn request_time_checks_run_limit_then_mix_then_numbers() { "ExpressionAttributeValues": {":n": {"N": "5"}}, "Limit": 1, }); - assert!(validate_query_request_values(&query(legacy)).is_ok()); + assert!(validate_query_request_body(&legacy).is_ok()); +} + +#[test] +fn enum_checks_sit_on_either_side_of_the_numbers() { + // Measured 2026-10-24: an invalid ReturnConsumedCapacity is reported ahead + // of an N value that is not a number, and that value ahead of an invalid + // Select; a Limit of 0 and a parameter mix ahead of either enum. + let bad_number = serde_json::json!({ + "TableName": "t", + "KeyConditionExpression": "pk = :u", + "ExpressionAttributeValues": {":u": {"N": "bob"}}, + }); + let mut rcc = bad_number.clone(); + rcc["ReturnConsumedCapacity"] = serde_json::json!("bad"); + assert_eq!( + message(validate_query_request_body(&rcc)).as_deref(), + Some( + "1 validation error detected: Value 'bad' at 'returnConsumedCapacity' failed to \ + satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]" + ) + ); + let mut select = bad_number.clone(); + select["Select"] = serde_json::json!("bad"); + assert_eq!( + message(validate_query_request_body(&select)).as_deref(), + Some("The parameter cannot be converted to a numeric value: bob") + ); + for field in ["ReturnConsumedCapacity", "Select"] { + let mut limit = bad_number.clone(); + limit[field] = serde_json::json!("bad"); + limit["Limit"] = serde_json::json!(0); + assert_eq!( + message(validate_query_request_body(&limit)).as_deref(), + Some(LIMIT_BELOW_ONE), + "{field}" + ); + } + // With the numbers valid, an invalid Select is still reported. + let mut only_select = serde_json::json!({ + "TableName": "t", + "KeyConditionExpression": "pk = :u", + "ExpressionAttributeValues": {":u": {"S": "bob"}}, + }); + only_select["Select"] = serde_json::json!("bad"); + assert!( + message(validate_query_request_body(&only_select)) + .is_some_and(|m| m.contains("at 'select' failed to satisfy constraint")) + ); } diff --git a/crates/server/src/request_helpers.rs b/crates/server/src/request_helpers.rs index 9f34b2632..82c694729 100755 --- a/crates/server/src/request_helpers.rs +++ b/crates/server/src/request_helpers.rs @@ -185,17 +185,17 @@ pub(crate) async fn authorize_request( } // A Query's request-time checks (Limit, the expression and non-expression - // parameter mix, every number in ExpressionAttributeValues) run before the - // IAM decision, for every principal. The engine makes the same checks at - // request time; they run here as well because authorization binds no - // dynamodb:LeadingKeys value to a number it cannot parse, and a fence that - // needs the key present (ForAnyValue, a Null guard, the plain operators) - // would otherwise answer AccessDeniedException where ValidationException is - // the request's error. A body the engine cannot deserialize is left to it. - if operation == "Query" - && let Ok(query) = serde_json::from_value::(input.clone()) - { - extenddb_engine::query_key_values::validate_query_request_values(&query)?; + // parameter mix, the ReturnConsumedCapacity and Select enums, every number + // in ExpressionAttributeValues) run before the IAM decision, for every + // principal. The engine makes the same checks at request time; they run + // here as well because authorization binds no dynamodb:LeadingKeys value + // to a number it cannot parse, and a fence that needs the key present + // (ForAnyValue, a Null guard, the plain operators) would otherwise answer + // AccessDeniedException where ValidationException is the request's error. + // The checks read the raw body, so a field that does not deserialize does + // not skip them. + if operation == "Query" { + extenddb_engine::query_key_values::validate_query_request_body(input)?; } // Every other ARN-bearing field (StreamArn, BackupArn, the export TableArn, diff --git a/tests/test_query_key_value_types.py b/tests/test_query_key_value_types.py index 02ee3b317..f01033488 100644 --- a/tests/test_query_key_value_types.py +++ b/tests/test_query_key_value_types.py @@ -8,12 +8,13 @@ value: ``) or when a key condition value's type is not the key attribute's ``AttributeDefinitions`` type (``One or more parameter values were invalid: Condition parameter type does not match schema type``). Every expected -answer below was measured against the service on 2026-10-24 (15:10 UTC and -21:00 UTC) on tables with S/S, S/N and B/B keys, a GSI and an LSI. The rows -also pin where the two checks fall against the other Query checks: the numeric -check after Limit and the expression parameter mix check and before the table -lookup; the type check after the key schema, filter, projection, unused value -and Select checks and before the ExclusiveStartKey check. +answer below was measured against the service on 2026-10-24 (15:10, 21:00, +21:06 and 23:42 UTC) on tables with S/S, S/N and B/B keys, a GSI and an LSI. +The rows also pin where the two checks fall against the other Query checks: +the numeric check after Limit, the expression parameter mix check and the +ReturnConsumedCapacity enum, and before the Select enum and the table lookup; +the type check after the key schema, filter, projection, unused value and +Select checks and before the ExclusiveStartKey check. Dual-target: runs against the service and against extenddb with the same assertions. The LeadingKeys class needs the extenddb management API and is @@ -180,6 +181,10 @@ def bb_table(dynamodb_client): "1 validation error detected: Cannot specify the ProjectionExpression when choosing to " "get ALL_ATTRIBUTES" ) +RCC_MSG = ( + "1 validation error detected: Value 'bad' at 'returnConsumedCapacity' failed to satisfy " + "constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]" +) V = "ValidationException" RNF = "ResourceNotFoundException" @@ -334,6 +339,21 @@ def kce(expr, values, **extra): kce("pk = :p", {":p": SX}, Limit=0, KeyConditions=LEGACY_PK), V, LIMIT_MSG), ("d6 Limit 0 with N bob and an undefined placeholder", "ss", kce("pk = :p AND sk = :zz", {":p": SX, ":n": NB}, Limit=0), V, LIMIT_MSG), + # The two enum checks against the numeric check, Limit and the mix. + ("f1 invalid Select with N bob", "ss", kce("pk = :u", {":u": NB}, Select="bad"), V, NUMERIC + "bob"), + ("f2 invalid ReturnConsumedCapacity with N bob", "ss", + kce("pk = :u", {":u": NB}, ReturnConsumedCapacity="bad"), V, RCC_MSG), + ("f3 invalid Select with Limit 0", "ss", + kce("pk = :u", {":u": {"S": "alice"}}, Select="bad", Limit=0), V, LIMIT_MSG), + ("f4 invalid ReturnConsumedCapacity with Limit 0", "ss", + kce("pk = :u", {":u": {"S": "alice"}}, ReturnConsumedCapacity="bad", Limit=0), V, LIMIT_MSG), + ("f5 invalid Select with KeyConditions and KeyConditionExpression", "ss", + kce("pk = :u", {":u": {"S": "alice"}}, Select="bad", + KeyConditions={"pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "alice"}]}}), + V, MIX_MSG), + ("f6 Limit -1 with N bob", "ss", kce("pk = :u", {":u": NB}, Limit=-1), V, LIMIT_MSG), + ("f7 Limit 0 with a type mismatch and N bob", "ss", + kce("pk = :u AND sk = :s", {":u": N5, ":s": NB}, Limit=0), V, LIMIT_MSG), # The other value types the earlier record covers. ("pk = BOOL", "ss", kce("pk = :u", {":u": {"BOOL": True}}), V, TYPE_MISMATCH), ("pk = N bob AND pk > S alice", "ss", @@ -471,6 +491,9 @@ def test_every_fence_form_gets_validation_exception_and_no_items(self): "pk = S bob, N bob unused": { "TableName": table, "KeyConditionExpression": "pk = :u", "ExpressionAttributeValues": {":u": {"S": "bob"}, ":n": NB}}, + "pk = N bob, invalid Select": { + "TableName": table, "KeyConditionExpression": "pk = :u", + "ExpressionAttributeValues": {":u": NB}, "Select": "bad"}, } failures = [] clients = {label: self._client(self._fence(condition, table)) From e4f660d620f8ccb7eefc7a1cbadd8d738f9410af Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sun, 25 Oct 2026 00:35:43 +0000 Subject: [PATCH 03/30] docs(query): name the request-time function in the comments that point at it --- crates/engine/src/query.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index a4e633073..9b3e6d7e8 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -118,7 +118,7 @@ pub async fn handle_query( )?; } - // Limit >= 1 is checked at request time in validate_query_request_values. + // Limit >= 1 is checked at request time in validate_query_request_body. // For index queries, build a key_info that reflects the index's key schema // so the storage layer uses the correct SK column for the index table. @@ -141,7 +141,7 @@ pub async fn handle_query( }; // The legacy versus expression mutual exclusivity check runs at request - // time in validate_query_request_values. + // time in validate_query_request_body. let has_cond_op = input.conditional_operator.is_some(); // An explicitly empty KeyConditionExpression is rejected up front, before From 4a4e92f4d4ac6a31921645ef896e4cff8fdc14a9 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sat, 24 Oct 2026 02:22:31 +0000 Subject: [PATCH 04/30] fix(cassandra): pass the bare index name in IndexNotFound so the Query sentence matches the other backends --- crates/storage-cassandra/src/data/index.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/storage-cassandra/src/data/index.rs b/crates/storage-cassandra/src/data/index.rs index 4ebd72dac..3aa353ac6 100644 --- a/crates/storage-cassandra/src/data/index.rs +++ b/crates/storage-cassandra/src/data/index.rs @@ -147,7 +147,7 @@ pub async fn fetch_index_by_name( let row = rows .into_iter() .next() - .ok_or_else(|| StorageError::IndexNotFound(format!("Index {index_name} not found")))?; + .ok_or_else(|| StorageError::IndexNotFound(index_name.to_owned()))?; let index_id: String = get_column(&row, "index_id", "fetch_index_by_name")?; let index_type: String = get_column(&row, "index_type", "fetch_index_by_name")?; From 03caeed76d08f716fedca6a88319253a8bc36560 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sun, 25 Oct 2026 11:44:43 +0000 Subject: [PATCH 05/30] fix(query): accept Unicode decimal digits in the number check and report a shape fault ahead of the request-time checks The request-time number check refused an N value written with a Unicode decimal digit (fullwidth, Arabic-Indic, Devanagari) that the service accepts as the digit it stands for, so a Query that returns rows on the service answered ValidationException here. The check now folds every general category Nd digit to ASCII before the number rules run and echoes the value as the request wrote it when the rules refuse it; the Nd zero code points of Unicode 15.0 live in a module of their own. The fold applies to the check only: the handler and the server's key binding read the value as written. The write paths are unchanged. The checks run on the raw body before deserialization, so a field of the wrong JSON type elsewhere in the body (a string ExpressionAttributeValues beside a Limit of 0, a string ExpressionAttributeNames beside a malformed N, a numeric Select) answered the check's ValidationException where the service and the previous release answered SerializationException. When a check fails, the body is now deserialized as the typed input and a SerializationException from that is returned instead; a ValidationException the deserializer raises does not preempt the check, and a body that passes every check is not deserialized twice. The server's call before dispatch goes through the same function. Measured against the service on 2026-10-25 (11:31 UTC) on tables with S/N and S/S keys, each request twice. Unit tests cover the digit table, the folded check and the shape-fault order; the wire file gains the measured rows for both. --- crates/engine/src/decimal_digits.rs | 122 ++++++++++++++++ crates/engine/src/lib.rs | 1 + crates/engine/src/query_key_values.rs | 88 ++++++++++-- crates/engine/src/query_key_values/tests.rs | 133 +++++++++++++++++ tests/test_query_key_value_types.py | 152 +++++++++++++++++++- 5 files changed, 481 insertions(+), 15 deletions(-) create mode 100644 crates/engine/src/decimal_digits.rs diff --git a/crates/engine/src/decimal_digits.rs b/crates/engine/src/decimal_digits.rs new file mode 100644 index 000000000..7717634dd --- /dev/null +++ b/crates/engine/src/decimal_digits.rs @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Unicode decimal digits (general category `Nd`) folded to ASCII for the +//! request-time number check. +//! +//! Measured 2026-10-25 (us-east-1, each request twice): the service reads a +//! fullwidth, Arabic-Indic or Devanagari digit in an `N` value as the digit it +//! stands for (`{"N": "\u{ff11}"}` in a `FilterExpression` answers OK; thirty +//! nine Devanagari ones answer `Attempting to store more than 38 significant +//! digits in a Number`), and refuses a superscript (`\u{b2}`), a vulgar +//! fraction (`\u{bd}`), a fullwidth minus (`\u{ff0d}`) and a fullwidth full +//! stop (`\u{ff0e}`) with `The parameter cannot be converted to a numeric +//! value: `. The accepted characters are exactly those of category `Nd`; +//! the refused ones are `No` or `Pd` and `Po`. +//! +//! Every `Nd` run in Unicode 15.0 is ten consecutive code points starting at +//! its zero, so the table below holds the 68 zeros (generated with Python's +//! `unicodedata`, Unicode 15.0.0) and a digit's value is its offset from the +//! run's zero. + +use std::borrow::Cow; + +/// The zero of every `Nd` run in Unicode 15.0, ascending. +const ND_ZEROS: [u32; 68] = [ + 0x0030, 0x0660, 0x06F0, 0x07C0, 0x0966, 0x09E6, 0x0A66, 0x0AE6, 0x0B66, 0x0BE6, 0x0C66, 0x0CE6, + 0x0D66, 0x0DE6, 0x0E50, 0x0ED0, 0x0F20, 0x1040, 0x1090, 0x17E0, 0x1810, 0x1946, 0x19D0, 0x1A80, + 0x1A90, 0x1B50, 0x1BB0, 0x1C40, 0x1C50, 0xA620, 0xA8D0, 0xA900, 0xA9D0, 0xA9F0, 0xAA50, 0xABF0, + 0xFF10, 0x104A0, 0x10D30, 0x11066, 0x110F0, 0x11136, 0x111D0, 0x112F0, 0x11450, 0x114D0, + 0x11650, 0x116C0, 0x11730, 0x118E0, 0x11950, 0x11C50, 0x11D50, 0x11DA0, 0x11F50, 0x16A60, + 0x16AC0, 0x16B50, 0x1D7CE, 0x1D7D8, 0x1D7E2, 0x1D7EC, 0x1D7F6, 0x1E140, 0x1E2F0, 0x1E4F0, + 0x1E950, 0x1FBF0, +]; + +/// The ASCII digit `c` stands for when `c` is a Unicode decimal digit +/// (general category `Nd`), or `None` for every other character. +pub(crate) fn ascii_digit(c: char) -> Option { + let cp = u32::from(c); + // The zero of the run that could hold `cp`: the last zero at or below it. + let run = ND_ZEROS + .partition_point(|&zero| zero <= cp) + .checked_sub(1)?; + let offset = cp - ND_ZEROS[run]; + u8::try_from(offset) + .ok() + .filter(|offset| *offset < 10) + .map(|offset| char::from(b'0' + offset)) +} + +/// `s` with every Unicode decimal digit replaced by the ASCII digit it stands +/// for. Borrows `s` when it has no such digit outside ASCII. +pub(crate) fn fold_decimal_digits(s: &str) -> Cow<'_, str> { + if s.is_ascii() || !s.chars().any(|c| !c.is_ascii() && ascii_digit(c).is_some()) { + return Cow::Borrowed(s); + } + Cow::Owned(s.chars().map(|c| ascii_digit(c).unwrap_or(c)).collect()) +} + +#[cfg(test)] +mod tests { + use super::{ND_ZEROS, ascii_digit, fold_decimal_digits}; + + #[test] + fn measured_digits_fold_to_their_ascii_value() { + // Fullwidth one, Arabic-Indic one, Devanagari one (X545-1 K1 to K3), + // fullwidth seven (H545-2 C11). + assert_eq!(ascii_digit('\u{ff11}'), Some('1')); + assert_eq!(ascii_digit('\u{661}'), Some('1')); + assert_eq!(ascii_digit('\u{967}'), Some('1')); + assert_eq!(ascii_digit('\u{ff17}'), Some('7')); + assert_eq!(ascii_digit('0'), Some('0')); + assert_eq!(ascii_digit('9'), Some('9')); + } + + #[test] + fn measured_controls_are_not_digits() { + // Superscript two, vulgar half, fullwidth minus, fullwidth full stop + // (H545-2 C13 to C16): refused by the service. + for c in ['\u{b2}', '\u{bd}', '\u{ff0d}', '\u{ff0e}'] { + assert_eq!(ascii_digit(c), None, "{c:?}"); + } + // Neighbours of a run and non-digit characters. + assert_eq!(ascii_digit('\u{ff10}'), Some('0')); + assert_eq!(ascii_digit('\u{ff19}'), Some('9')); + assert_eq!(ascii_digit('\u{ff1a}'), None); + assert_eq!(ascii_digit('\u{ff0f}'), None); + assert_eq!(ascii_digit('a'), None); + assert_eq!(ascii_digit('.'), None); + assert_eq!(ascii_digit('e'), None); + assert_eq!(ascii_digit('\u{1FBF9}'), Some('9')); + assert_eq!(ascii_digit('\u{1FBFA}'), None); + assert_eq!(ascii_digit(char::MAX), None); + assert_eq!(ascii_digit('\u{0}'), None); + } + + #[test] + fn zeros_are_ascending_and_distinct_runs() { + for pair in ND_ZEROS.windows(2) { + assert!(pair[0] + 10 <= pair[1], "{pair:?}"); + } + } + + #[test] + fn folding_keeps_every_other_character() { + assert_eq!(fold_decimal_digits("\u{ff11}"), "1"); + assert_eq!(fold_decimal_digits("1\u{ff12}"), "12"); + assert_eq!(fold_decimal_digits("1e\u{ff12}"), "1e2"); + assert_eq!(fold_decimal_digits(&"\u{967}".repeat(39)), "1".repeat(39)); + assert_eq!(fold_decimal_digits("\u{ff0d}1"), "\u{ff0d}1"); + assert_eq!(fold_decimal_digits("1\u{ff0e}5"), "1\u{ff0e}5"); + assert_eq!(fold_decimal_digits("\u{b2}"), "\u{b2}"); + assert_eq!(fold_decimal_digits("-1.5e3"), "-1.5e3"); + assert_eq!(fold_decimal_digits(""), ""); + assert!(matches!( + fold_decimal_digits("bob"), + std::borrow::Cow::Borrowed(_) + )); + assert!(matches!( + fold_decimal_digits("\u{ff0d}"), + std::borrow::Cow::Borrowed(_) + )); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index d24b47286..2cb47da7f 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -12,6 +12,7 @@ mod batch_get_item; mod batch_write_item; pub mod capacity_helpers; mod create_table; +mod decimal_digits; mod delete_item; mod delete_table; mod describe_endpoints; diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index 7bfb356ba..68e47b657 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -33,7 +33,8 @@ use extenddb_core::error::DynamoDbError; use extenddb_core::expression::{ Expr, ExpressionMaps, KeyCondition, PathElement, SortKeyCondition, }; -use extenddb_core::types::{AttributeDefinition, AttributeValue, ScalarAttributeType}; +use extenddb_core::types::{AttributeDefinition, AttributeValue, QueryInput, ScalarAttributeType}; +use serde::de::DeserializeOwned; use serde_json::Value; /// The service's text for a key condition value of the wrong type. @@ -55,18 +56,54 @@ const EMPTY_NUMBER: &str = "The parameter cannot be converted to a numeric value /// that value ahead of an invalid `Select`). /// /// The checks read the raw body, so a field that does not deserialize (an -/// invalid `Select`, for one) does not stop the ones before it. A field of the -/// wrong JSON shape is left to the deserializer, which runs next. +/// invalid `Select`, for one) does not stop the ones before it. When a check +/// fails, the body is deserialized as a [`QueryInput`], and a +/// `SerializationException` from that (a field of the wrong JSON shape +/// anywhere in the body) is the answer instead, as the service reports a shape +/// fault ahead of every validation (measured 2026-10-25: a `Limit` of 0 with a +/// string `ExpressionAttributeValues`, a string `ExpressionAttributeNames` with +/// an `N` value that is not a number, and a `Limit` of 0 with `Select: 5` all +/// answer `SerializationException`). A `ValidationException` the deserializer +/// raises (an empty set, a duplicate, an invalid `AttributeValue`) does not +/// preempt the check. A body that passes every check is not deserialized here. /// /// The server runs the same function ahead of the IAM decision, so a principal /// whose `dynamodb:LeadingKeys` fence cannot bind a number that does not parse /// gets the request's `ValidationException` rather than -/// `AccessDeniedException`. +/// `AccessDeniedException`. That call goes through this function too, so it +/// answers the shape fault first as well. /// /// # Errors /// -/// Returns `DynamoDbError::ValidationException` with the service's text. +/// Returns `DynamoDbError::ValidationException` with the service's text, or +/// `DynamoDbError::SerializationException` for a body of the wrong shape. pub fn validate_query_request_body(body: &Value) -> Result<(), DynamoDbError> { + query_request_checks(body).map_err(|check| shape_fault_first::(body, check)) +} + +/// When a request-time check has failed with `check`, the deserializer's +/// `SerializationException` for `body` if there is one, else `check`. The two +/// enum fields stay in the body: an enum value that is a string but not a +/// member deserializes to a `ValidationException`, which this ignores, and one +/// of another JSON type is a shape fault the service reports ahead of the +/// checks (measured 2026-10-25: `Select: 5` with a `Limit` of 0 answers +/// `SerializationException: NUMBER_VALUE cannot be converted to String`). +pub(crate) fn shape_fault_first( + body: &Value, + check: DynamoDbError, +) -> DynamoDbError { + match serde_json::from_value::(body.clone()) { + Err(e) => match crate::deserialize_error(e) { + shape @ DynamoDbError::SerializationException(_) => shape, + _ => check, + }, + Ok(_) => check, + } +} + +/// The `Query` checks in the service's order; see +/// [`validate_query_request_body`]. +fn query_request_checks(body: &Value) -> Result<(), DynamoDbError> { if let Some(limit) = body.get("Limit").and_then(Value::as_i64) && limit < 1 { @@ -153,6 +190,12 @@ fn non_empty(body: &Value, field: &str) -> bool { /// deterministic when several are invalid. An empty `N` answers the message /// with the colon and nothing after it, as the service does on `Query`. /// +/// A Unicode decimal digit (general category `Nd`) counts as the digit it +/// stands for, as the service reads it (measured 2026-10-25: a fullwidth or +/// Arabic-Indic digit is accepted, thirty nine Devanagari ones answer the 38 +/// digit message); see [`crate::decimal_digits`]. The message echoes the value +/// as the request wrote it. +/// /// # Errors /// /// Returns `DynamoDbError::ValidationException` with the service's text. @@ -162,19 +205,36 @@ pub fn validate_expression_attribute_value_numbers( let mut keys: Vec<&String> = values.keys().collect(); keys.sort(); for key in keys { - match extenddb_core::validation::validate_attribute_number(&values[key]) { - Ok(()) => {} - Err(DynamoDbError::ValidationException(msg)) if msg == EMPTY_NUMBER => { - return Err(DynamoDbError::ValidationException(format!( - "{EMPTY_NUMBER}: " - ))); - } - Err(other) => return Err(other), - } + validate_value_numbers(&values[key])?; } Ok(()) } +/// Every number inside one attribute value (`N`, `NS` members, and the values +/// nested in `L` and `M`), with Unicode decimal digits folded for the check. +fn validate_value_numbers(value: &AttributeValue) -> Result<(), DynamoDbError> { + match value { + AttributeValue::N(n) => validate_number_text(n), + AttributeValue::NS(set) => set.iter().try_for_each(|n| validate_number_text(n)), + AttributeValue::L(list) => list.iter().try_for_each(validate_value_numbers), + AttributeValue::M(map) => map.values().try_for_each(validate_value_numbers), + _ => Ok(()), + } +} + +/// One number text against the number rules, with the service's `Query` +/// message for an empty value and the original text echoed for a malformed one. +fn validate_number_text(text: &str) -> Result<(), DynamoDbError> { + let folded = crate::decimal_digits::fold_decimal_digits(text); + match extenddb_core::validation::number::validate_and_normalize_number(&folded) { + Ok(_) => Ok(()), + Err(DynamoDbError::ValidationException(msg)) if msg.starts_with(EMPTY_NUMBER) => Err( + DynamoDbError::ValidationException(format!("{EMPTY_NUMBER}: {text}")), + ), + Err(other) => Err(other), + } +} + /// Refuse a key condition value whose type is not the key's /// `AttributeDefinitions` type. /// diff --git a/crates/engine/src/query_key_values/tests.rs b/crates/engine/src/query_key_values/tests.rs index d98e66f05..e3a03dc2f 100644 --- a/crates/engine/src/query_key_values/tests.rs +++ b/crates/engine/src/query_key_values/tests.rs @@ -437,3 +437,136 @@ fn enum_checks_sit_on_either_side_of_the_numbers() { .is_some_and(|m| m.contains("at 'select' failed to satisfy constraint")) ); } + +#[test] +fn unicode_decimal_digits_count_as_the_digits_they_stand_for() { + // Measured 2026-10-25 (X545-1 K1 to K6, F1 to F6, U1 to U6; H545-2 C11, + // C12, C17): a fullwidth, Arabic-Indic or Devanagari digit is accepted as a + // key condition, filter or unused value; thirty nine Devanagari ones answer + // the 38 digit message; `1\u{ff12}` and `1e\u{ff12}` are accepted. + for raw in [ + "\u{ff11}", + "\u{661}", + "\u{967}", + "1\u{ff12}", + "1e\u{ff12}", + "\u{ff17}", + ] { + let values = HashMap::from([(":u".to_owned(), n(raw))]); + assert!( + validate_expression_attribute_value_numbers(&values).is_ok(), + "{raw:?}" + ); + } + let values = HashMap::from([(":u".to_owned(), n(&"\u{967}".repeat(39)))]); + assert_eq!( + message(validate_expression_attribute_value_numbers(&values)).as_deref(), + Some("Attempting to store more than 38 significant digits in a Number") + ); + // A fullwidth digit as an NS member (H545-2 C18, X545-1 NS1). + let values = HashMap::from([( + ":u".to_owned(), + AttributeValue::NS(["\u{ff11}".to_owned()].into_iter().collect()), + )]); + assert!(validate_expression_attribute_value_numbers(&values).is_ok()); +} + +#[test] +fn characters_that_are_not_decimal_digits_are_refused_with_the_text_as_sent() { + // Measured 2026-10-25 (X545-1 K7 to K10; H545-2 C13 to C16): a superscript, + // a vulgar fraction, a fullwidth minus and a fullwidth full stop are refused + // and the message echoes the value as the request wrote it. + for raw in ["\u{b2}", "\u{bd}", "\u{ff0d}1", "1\u{ff0e}5", "\u{ff11}bob"] { + let values = HashMap::from([(":u".to_owned(), n(raw))]); + assert_eq!( + message(validate_expression_attribute_value_numbers(&values)).as_deref(), + Some(format!("The parameter cannot be converted to a numeric value: {raw}").as_str()), + "{raw:?}" + ); + } +} + +#[test] +fn a_shape_fault_in_another_field_is_reported_ahead_of_the_checks() { + // Measured 2026-10-25 (X545-1 S1 to S6, S8): a field of the wrong JSON type + // anywhere in the body answers SerializationException even when a Limit, + // mix, enum or number check would fail. + let shape_faults = [ + serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "Limit": 0, "ExpressionAttributeValues": "x", + }), + serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "ExpressionAttributeNames": "x", + "ExpressionAttributeValues": {":p": {"N": "bob"}}, + }), + serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "Limit": "1", "ExpressionAttributeValues": {":p": {"N": "bob"}}, + }), + serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "AttributesToGet": {"a": 1}, "ProjectionExpression": "a", + "ExpressionAttributeValues": {":p": {"S": "x"}}, + }), + serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "QueryFilter": [1], "FilterExpression": "a = :p", + "ExpressionAttributeValues": {":p": {"S": "x"}}, + }), + serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "Select": 5, "ExpressionAttributeValues": {":p": {"N": "bob"}}, + }), + serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "Limit": 0, "Select": 5, "ExpressionAttributeValues": {":p": {"S": "x"}}, + }), + ]; + for body in shape_faults { + assert!( + matches!( + validate_query_request_body(&body), + Err(DynamoDbError::SerializationException(_)) + ), + "{body}" + ); + } + + // A string enum value that is not a member is the checks' own answer, not a + // shape fault (X545-1 S7 and the 2026-10-24 enum rows). + let mut select = serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "Limit": 0, "ExpressionAttributeValues": {":p": {"S": "x"}}, + }); + select["Select"] = serde_json::json!("bad"); + assert_eq!( + message(validate_query_request_body(&select)).as_deref(), + Some(LIMIT_BELOW_ONE) + ); + select["ReturnConsumedCapacity"] = serde_json::json!("bad"); + select["Limit"] = serde_json::json!(1); + assert!( + message(validate_query_request_body(&select)) + .is_some_and(|m| m.contains("at 'returnConsumedCapacity' failed to satisfy constraint")) + ); + + // A ValidationException the deserializer raises does not preempt a check: + // an empty NS beside a Limit of 0 answers the Limit text. + let empty_set = serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "Limit": 0, "ExpressionAttributeValues": {":p": {"S": "x"}, ":s": {"NS": []}}, + }); + assert_eq!( + message(validate_query_request_body(&empty_set)).as_deref(), + Some(LIMIT_BELOW_ONE) + ); + + // A body that passes every check is left to the handler's deserializer. + let shape_fault_only = serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": "x", + }); + assert!(validate_query_request_body(&shape_fault_only).is_ok()); +} diff --git a/tests/test_query_key_value_types.py b/tests/test_query_key_value_types.py index f01033488..cb5c802ea 100644 --- a/tests/test_query_key_value_types.py +++ b/tests/test_query_key_value_types.py @@ -9,7 +9,10 @@ attribute's ``AttributeDefinitions`` type (``One or more parameter values were invalid: Condition parameter type does not match schema type``). Every expected answer below was measured against the service on 2026-10-24 (15:10, 21:00, -21:06 and 23:42 UTC) on tables with S/S, S/N and B/B keys, a GSI and an LSI. +21:06 and 23:42 UTC) and 2026-10-25 (11:31 UTC) on tables with S/S, S/N and +B/B keys, a GSI and an LSI. A Unicode decimal digit in an N value counts as +the digit it stands for; a field of the wrong JSON type anywhere in the body +answers SerializationException ahead of every check. The rows also pin where the two checks fall against the other Query checks: the numeric check after Limit, the expression parameter mix check and the ReturnConsumedCapacity enum, and before the Select enum and the table lookup; @@ -115,6 +118,10 @@ def ns_table(dynamodb_client): for pk in ("alice", "bob"): dynamodb_client.put_item(TableName=name, Item={ "pk": {"S": pk}, "sk": {"N": "5"}, "gpk": {"S": pk}, "gsk": {"S": "g"}}) + # The item the Unicode digit rows read: sk N 1 and a N 1 in ASCII. + dynamodb_client.put_item(TableName=name, Item={ + "pk": {"S": "carol"}, "sk": {"N": "1"}, "a": {"N": "1"}, + "gpk": {"S": "carol"}, "gsk": {"S": "g"}}) yield name @@ -165,6 +172,14 @@ def bb_table(dynamodb_client): ) NO_INDEX = "The table does not have the specified index: nope" UNUSED_X = "Value provided in ExpressionAttributeValues unused in expressions: keys: {:x}" +UNUSED_F = "Value provided in ExpressionAttributeValues unused in expressions: keys: {:f}" +# Unicode decimal digits (general category Nd) and characters that are not. +FW_ONE = "\uff11" # fullwidth digit one +AR_ONE = "\u0661" # Arabic-Indic digit one +DEVA_ONE = "\u0967" # Devanagari digit one +# Superscript two, vulgar half, fullwidth minus then 1, 1 fullwidth full stop 5. +NOT_DIGITS = ["\u00b2", "\u00bd", "\uff0d1", "1\uff0e5"] +CAROL = {"S": "carol"} GSI_CONSISTENT = "Consistent reads are not supported on global secondary indexes" FILTER_BEGINS_WITH_N = ( "Invalid FilterExpression: Incorrect operand type for operator or function; " @@ -354,6 +369,35 @@ def kce(expr, values, **extra): ("f6 Limit -1 with N bob", "ss", kce("pk = :u", {":u": NB}, Limit=-1), V, LIMIT_MSG), ("f7 Limit 0 with a type mismatch and N bob", "ss", kce("pk = :u AND sk = :s", {":u": N5, ":s": NB}, Limit=0), V, LIMIT_MSG), + # Unicode decimal digits are read as the digits they stand for; other + # characters are refused with the value echoed as sent (measured + # 2026-10-25 11:31 UTC on an S/N table). + ("g1 39 Devanagari ones as sk", "ns", + kce("pk = :u AND sk = :s", {":u": CAROL, ":s": {"N": DEVA_ONE * 39}}), V, DIGITS_MSG), + ("g2 39 Devanagari ones in filter", "ns", + kce("pk = :u AND sk = :s", {":u": CAROL, ":s": {"N": "1"}, ":f": {"N": DEVA_ONE * 39}}, + FilterExpression="a = :f"), V, DIGITS_MSG), + ("g3 39 Devanagari ones unused", "ns", + kce("pk = :u AND sk = :s", {":u": CAROL, ":s": {"N": "1"}, ":f": {"N": DEVA_ONE * 39}}), + V, DIGITS_MSG), + *[(f"g4 {raw!r} as sk", "ns", + kce("pk = :u AND sk = :s", {":u": CAROL, ":s": {"N": raw}}), V, NUMERIC + raw) + for raw in NOT_DIGITS], + *[(f"g5 {raw!r} in filter", "ns", + kce("pk = :u AND sk = :s", {":u": CAROL, ":s": {"N": "1"}, ":f": {"N": raw}}, + FilterExpression="a = :f"), V, NUMERIC + raw) + for raw in NOT_DIGITS], + *[(f"g6 {raw!r} unused", "ns", + kce("pk = :u AND sk = :s", {":u": CAROL, ":s": {"N": "1"}, ":f": {"N": raw}}), + V, NUMERIC + raw) + for raw in NOT_DIGITS], + *[(f"g7 {raw!r} unused passes the number check", "ns", + kce("pk = :u AND sk = :s", {":u": CAROL, ":s": {"N": "1"}, ":f": {"N": raw}}), + V, UNUSED_F) + for raw in (FW_ONE, AR_ONE, DEVA_ONE, "1\uff12", "1e\uff12")], + ("g8 NS with a fullwidth digit unused", "ns", + kce("pk = :u AND sk = :s", {":u": CAROL, ":s": {"N": "1"}, ":f": {"NS": [FW_ONE]}}), + V, UNUSED_F), # The other value types the earlier record covers. ("pk = BOOL", "ss", kce("pk = :u", {":u": {"BOOL": True}}), V, TYPE_MISMATCH), ("pk = N bob AND pk > S alice", "ss", @@ -392,6 +436,112 @@ def test_control_matching_types_on_every_table(self, dynamodb_client, ss_table, ExpressionAttributeValues={":u": B_BOB})["Count"] == 1 +class TestUnicodeDecimalDigitsAreRead: + """A Unicode decimal digit in an N value is the digit it stands for: as a + key condition value it reads the item stored with the ASCII digit, as a + filter value it matches the ASCII attribute (measured 2026-10-25 11:31 UTC + on an S/N table holding sk N 1 and a N 1).""" + + DIGITS = [FW_ONE, AR_ONE, DEVA_ONE] + DIGIT_IDS = ["fullwidth", "arabic-indic", "devanagari"] + + @pytest.mark.parametrize("digit", DIGITS, ids=DIGIT_IDS) + def test_key_condition_value_reads_the_ascii_item(self, dynamodb_client, ns_table, digit): + resp = dynamodb_client.query( + TableName=ns_table, KeyConditionExpression="pk = :u AND sk = :s", + ExpressionAttributeValues={":u": CAROL, ":s": {"N": digit}}) + assert resp["Count"] == 1 + assert resp["Items"][0]["sk"] == {"N": "1"} + + @pytest.mark.parametrize("digit", DIGITS, ids=DIGIT_IDS) + def test_filter_value_matches_the_ascii_attribute(self, dynamodb_client, ns_table, digit): + resp = dynamodb_client.query( + TableName=ns_table, KeyConditionExpression="pk = :u AND sk = :s", + FilterExpression="a = :f", + ExpressionAttributeValues={":u": CAROL, ":s": {"N": "1"}, ":f": {"N": digit}}) + assert resp["Count"] == 1 + assert resp["Items"][0]["a"] == {"N": "1"} + + @pytest.mark.parametrize("raw", ["1\uff12", "1e\uff12"], ids=["1-fullwidth-2", "1e-fullwidth-2"]) + def test_mixed_digits_are_one_number(self, dynamodb_client, ns_table, raw): + # Read as 12 and 1e2: accepted, matching nothing stored. + as_key = dynamodb_client.query( + TableName=ns_table, KeyConditionExpression="pk = :u AND sk = :s", + ExpressionAttributeValues={":u": CAROL, ":s": {"N": raw}}) + assert (as_key["Count"], as_key["ScannedCount"]) == (0, 0) + in_filter = dynamodb_client.query( + TableName=ns_table, KeyConditionExpression="pk = :u AND sk = :s", + FilterExpression="a = :f", + ExpressionAttributeValues={":u": CAROL, ":s": {"N": "1"}, ":f": {"N": raw}}) + assert (in_filter["Count"], in_filter["ScannedCount"]) == (0, 1) + + def test_fullwidth_digit_in_a_number_set_passes_the_check(self, dynamodb_client, ns_table): + resp = dynamodb_client.query( + TableName=ns_table, KeyConditionExpression="pk = :u AND sk = :s", + FilterExpression="contains(ns, :f)", + ExpressionAttributeValues={":u": CAROL, ":s": {"N": "1"}, ":f": {"NS": [FW_ONE]}}) + assert (resp["Count"], resp["ScannedCount"]) == (0, 1) + + +def _raw_query(client, body: dict): + """POST ``body`` as the Query JSON exactly as written, signed with the + client's credentials, so a field of the wrong JSON type reaches the server + (boto3 would refuse or reshape it).""" + import json + + from botocore.awsrequest import AWSRequest + + req = AWSRequest(method="POST", url=client.meta.endpoint_url, data=json.dumps(body), + headers={"Content-Type": "application/x-amz-json-1.0", + "X-Amz-Target": "DynamoDB_20120810.Query"}) + client._request_signer.sign("Query", req) + resp = client._endpoint.http_session.send(req.prepare()) + return resp.status_code, json.loads(resp.content.decode("utf-8", "replace") or "{}") + + +SHAPE_FAULTS = [ + ("Limit 0 with ExpressionAttributeValues string", + {"KeyConditionExpression": "pk = :p", "Limit": 0, "ExpressionAttributeValues": "x"}), + ("ExpressionAttributeNames string with N bob", + {"KeyConditionExpression": "pk = :p", "ExpressionAttributeNames": "x", + "ExpressionAttributeValues": {":p": NB}}), + ("Limit string with N bob", + {"KeyConditionExpression": "pk = :p", "Limit": "1", "ExpressionAttributeValues": {":p": NB}}), + ("AttributesToGet object with ProjectionExpression", + {"KeyConditionExpression": "pk = :p", "AttributesToGet": {"a": 1}, "ProjectionExpression": "a", + "ExpressionAttributeValues": {":p": SX}}), + ("QueryFilter array with FilterExpression", + {"KeyConditionExpression": "pk = :p", "QueryFilter": [1], "FilterExpression": "a = :p", + "ExpressionAttributeValues": {":p": SX}}), + ("Select number with N bob", + {"KeyConditionExpression": "pk = :p", "Select": 5, "ExpressionAttributeValues": {":p": NB}}), + ("Limit 0 with Select number", + {"KeyConditionExpression": "pk = :p", "Limit": 0, "Select": 5, + "ExpressionAttributeValues": {":p": SX}}), +] + + +class TestShapeFaultsAreReportedFirst: + """A field of the wrong JSON type anywhere in the body answers + SerializationException ahead of the Limit, parameter mix, enum and number + checks (measured 2026-10-25 11:31 UTC). The message texts differ between + the service and extenddb, so only the error type is asserted.""" + + @pytest.mark.parametrize("row,body", SHAPE_FAULTS, ids=[r[0] for r in SHAPE_FAULTS]) + def test_rows(self, dynamodb_client, ss_table, row, body): + status, payload = _raw_query(dynamodb_client, {"TableName": ss_table, **body}) + assert status == 400 + assert payload.get("__type", "").endswith("SerializationException"), payload + + def test_control_without_a_shape_fault_answers_the_check(self, dynamodb_client, ss_table): + status, payload = _raw_query(dynamodb_client, { + "TableName": ss_table, "KeyConditionExpression": "pk = :p", "Limit": 0, + "ExpressionAttributeValues": {":p": NB}}) + assert status == 400 + assert payload.get("__type", "").endswith("ValidationException") + assert payload.get("message", payload.get("Message")) == LIMIT_MSG + + class TestLeadingKeysWithAnInvalidKeyValue: """A principal under each LeadingKeys fence form gets ValidationException and no items for a Query whose ExpressionAttributeValues carries an N value that From bde92d3f11930294c8da437aacabc66ac1b33f04 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sun, 25 Oct 2026 13:46:22 +0000 Subject: [PATCH 06/30] fix(query): leave an unknown type descriptor to the request-time checks, and assert only acceptance for Unicode digits The shape-fault pass returned the deserializer's SerializationException for an AttributeValue with an unknown type descriptor, so Limit 0 beside {"X": "1"} changed class. The service answers the Limit ValidationException for that body (measured 2026-10-25), and the check's answer is returned again. The Unicode digit tests asserted that a key condition or filter written with a Unicode digit reads the item stored with the ASCII digit. This change makes the request-time check accept such a value; it does not change how the handler reads it, so the tests assert only that the value is accepted. A new test checks that a partition key value written with Unicode digits returns no item of a partition a ForAllValues LeadingKeys fence keeps the caller from. --- crates/engine/src/decimal_digits.rs | 13 ++-- crates/engine/src/query_key_values.rs | 12 ++++ crates/engine/src/query_key_values/tests.rs | 23 +++++-- tests/test_query_key_value_types.py | 70 ++++++++++++++------- 4 files changed, 84 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/decimal_digits.rs b/crates/engine/src/decimal_digits.rs index 7717634dd..8aeb24130 100644 --- a/crates/engine/src/decimal_digits.rs +++ b/crates/engine/src/decimal_digits.rs @@ -17,6 +17,11 @@ //! its zero, so the table below holds the 68 zeros (generated with Python's //! `unicodedata`, Unicode 15.0.0) and a digit's value is its offset from the //! run's zero. +//! +//! The fold applies to the check only. The handler and the server's +//! `dynamodb:LeadingKeys` binding read the value as the request wrote it, so +//! both see the same text; reading a Unicode digit as the digit has to change +//! both together. use std::borrow::Cow; @@ -61,8 +66,8 @@ mod tests { #[test] fn measured_digits_fold_to_their_ascii_value() { - // Fullwidth one, Arabic-Indic one, Devanagari one (X545-1 K1 to K3), - // fullwidth seven (H545-2 C11). + // Fullwidth one, Arabic-Indic one, Devanagari one and fullwidth seven, + // measured 2026-10-25. assert_eq!(ascii_digit('\u{ff11}'), Some('1')); assert_eq!(ascii_digit('\u{661}'), Some('1')); assert_eq!(ascii_digit('\u{967}'), Some('1')); @@ -73,8 +78,8 @@ mod tests { #[test] fn measured_controls_are_not_digits() { - // Superscript two, vulgar half, fullwidth minus, fullwidth full stop - // (H545-2 C13 to C16): refused by the service. + // Superscript two, vulgar half, fullwidth minus, fullwidth full stop: + // refused by the service (measured 2026-10-25). for c in ['\u{b2}', '\u{bd}', '\u{ff0d}', '\u{ff0e}'] { assert_eq!(ascii_digit(c), None, "{c:?}"); } diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index 68e47b657..54886bf96 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -88,12 +88,20 @@ pub fn validate_query_request_body(body: &Value) -> Result<(), DynamoDbError> { /// of another JSON type is a shape fault the service reports ahead of the /// checks (measured 2026-10-25: `Select: 5` with a `Limit` of 0 answers /// `SerializationException: NUMBER_VALUE cannot be converted to String`). +/// +/// An AttributeValue with an unknown type descriptor is not a shape fault to +/// the service: `Limit: 0` beside `{"X": "1"}` answers the `Limit` +/// `ValidationException` (measured 2026-10-25), so the deserializer's +/// `SerializationException` for that message does not preempt the check. pub(crate) fn shape_fault_first( body: &Value, check: DynamoDbError, ) -> DynamoDbError { match serde_json::from_value::(body.clone()) { Err(e) => match crate::deserialize_error(e) { + DynamoDbError::SerializationException(msg) if msg.contains(UNKNOWN_TYPE_DESCRIPTOR) => { + check + } shape @ DynamoDbError::SerializationException(_) => shape, _ => check, }, @@ -101,6 +109,10 @@ pub(crate) fn shape_fault_first( } } +/// The deserializer's text for an AttributeValue whose type descriptor is not +/// one of the service's. +const UNKNOWN_TYPE_DESCRIPTOR: &str = "unknown AttributeValue type descriptor"; + /// The `Query` checks in the service's order; see /// [`validate_query_request_body`]. fn query_request_checks(body: &Value) -> Result<(), DynamoDbError> { diff --git a/crates/engine/src/query_key_values/tests.rs b/crates/engine/src/query_key_values/tests.rs index e3a03dc2f..e9958fe59 100644 --- a/crates/engine/src/query_key_values/tests.rs +++ b/crates/engine/src/query_key_values/tests.rs @@ -440,8 +440,7 @@ fn enum_checks_sit_on_either_side_of_the_numbers() { #[test] fn unicode_decimal_digits_count_as_the_digits_they_stand_for() { - // Measured 2026-10-25 (X545-1 K1 to K6, F1 to F6, U1 to U6; H545-2 C11, - // C12, C17): a fullwidth, Arabic-Indic or Devanagari digit is accepted as a + // Measured 2026-10-25: a fullwidth, Arabic-Indic or Devanagari digit is accepted as a // key condition, filter or unused value; thirty nine Devanagari ones answer // the 38 digit message; `1\u{ff12}` and `1e\u{ff12}` are accepted. for raw in [ @@ -463,7 +462,7 @@ fn unicode_decimal_digits_count_as_the_digits_they_stand_for() { message(validate_expression_attribute_value_numbers(&values)).as_deref(), Some("Attempting to store more than 38 significant digits in a Number") ); - // A fullwidth digit as an NS member (H545-2 C18, X545-1 NS1). + // A fullwidth digit as an NS member. let values = HashMap::from([( ":u".to_owned(), AttributeValue::NS(["\u{ff11}".to_owned()].into_iter().collect()), @@ -473,7 +472,7 @@ fn unicode_decimal_digits_count_as_the_digits_they_stand_for() { #[test] fn characters_that_are_not_decimal_digits_are_refused_with_the_text_as_sent() { - // Measured 2026-10-25 (X545-1 K7 to K10; H545-2 C13 to C16): a superscript, + // Measured 2026-10-25: a superscript, // a vulgar fraction, a fullwidth minus and a fullwidth full stop are refused // and the message echoes the value as the request wrote it. for raw in ["\u{b2}", "\u{bd}", "\u{ff0d}1", "1\u{ff0e}5", "\u{ff11}bob"] { @@ -488,7 +487,7 @@ fn characters_that_are_not_decimal_digits_are_refused_with_the_text_as_sent() { #[test] fn a_shape_fault_in_another_field_is_reported_ahead_of_the_checks() { - // Measured 2026-10-25 (X545-1 S1 to S6, S8): a field of the wrong JSON type + // Measured 2026-10-25: a field of the wrong JSON type // anywhere in the body answers SerializationException even when a Limit, // mix, enum or number check would fail. let shape_faults = [ @@ -535,7 +534,7 @@ fn a_shape_fault_in_another_field_is_reported_ahead_of_the_checks() { } // A string enum value that is not a member is the checks' own answer, not a - // shape fault (X545-1 S7 and the 2026-10-24 enum rows). + // shape fault. let mut select = serde_json::json!({ "TableName": "t", "KeyConditionExpression": "pk = :p", "Limit": 0, "ExpressionAttributeValues": {":p": {"S": "x"}}, @@ -563,6 +562,18 @@ fn a_shape_fault_in_another_field_is_reported_ahead_of_the_checks() { Some(LIMIT_BELOW_ONE) ); + // Neither does an unknown type descriptor, which the deserializer reports + // as a SerializationException: the service answers the Limit text + // (measured 2026-10-25). + let unknown_type = serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "Limit": 0, "ExpressionAttributeValues": {":p": {"S": "x"}, ":a": {"X": "1"}}, + }); + assert_eq!( + message(validate_query_request_body(&unknown_type)).as_deref(), + Some(LIMIT_BELOW_ONE) + ); + // A body that passes every check is left to the handler's deserializer. let shape_fault_only = serde_json::json!({ "TableName": "t", "KeyConditionExpression": "pk = :p", diff --git a/tests/test_query_key_value_types.py b/tests/test_query_key_value_types.py index cb5c802ea..c336b6acc 100644 --- a/tests/test_query_key_value_types.py +++ b/tests/test_query_key_value_types.py @@ -436,44 +436,31 @@ def test_control_matching_types_on_every_table(self, dynamodb_client, ss_table, ExpressionAttributeValues={":u": B_BOB})["Count"] == 1 -class TestUnicodeDecimalDigitsAreRead: - """A Unicode decimal digit in an N value is the digit it stands for: as a - key condition value it reads the item stored with the ASCII digit, as a - filter value it matches the ASCII attribute (measured 2026-10-25 11:31 UTC - on an S/N table holding sk N 1 and a N 1).""" +class TestUnicodeDecimalDigitsPassTheCheck: + """A Unicode decimal digit in an N value passes the request-time number + check: the service reads it as the digit it stands for (measured 2026-10-25 + 11:31 UTC). Reading such a value as the digit is not part of this change, + so only the acceptance is asserted, in the positions where the request + reaches no numeric key comparison.""" DIGITS = [FW_ONE, AR_ONE, DEVA_ONE] DIGIT_IDS = ["fullwidth", "arabic-indic", "devanagari"] @pytest.mark.parametrize("digit", DIGITS, ids=DIGIT_IDS) - def test_key_condition_value_reads_the_ascii_item(self, dynamodb_client, ns_table, digit): - resp = dynamodb_client.query( - TableName=ns_table, KeyConditionExpression="pk = :u AND sk = :s", - ExpressionAttributeValues={":u": CAROL, ":s": {"N": digit}}) - assert resp["Count"] == 1 - assert resp["Items"][0]["sk"] == {"N": "1"} - - @pytest.mark.parametrize("digit", DIGITS, ids=DIGIT_IDS) - def test_filter_value_matches_the_ascii_attribute(self, dynamodb_client, ns_table, digit): + def test_filter_value_is_accepted(self, dynamodb_client, ns_table, digit): resp = dynamodb_client.query( TableName=ns_table, KeyConditionExpression="pk = :u AND sk = :s", FilterExpression="a = :f", ExpressionAttributeValues={":u": CAROL, ":s": {"N": "1"}, ":f": {"N": digit}}) - assert resp["Count"] == 1 - assert resp["Items"][0]["a"] == {"N": "1"} + assert resp["ScannedCount"] == 1 @pytest.mark.parametrize("raw", ["1\uff12", "1e\uff12"], ids=["1-fullwidth-2", "1e-fullwidth-2"]) - def test_mixed_digits_are_one_number(self, dynamodb_client, ns_table, raw): - # Read as 12 and 1e2: accepted, matching nothing stored. - as_key = dynamodb_client.query( - TableName=ns_table, KeyConditionExpression="pk = :u AND sk = :s", - ExpressionAttributeValues={":u": CAROL, ":s": {"N": raw}}) - assert (as_key["Count"], as_key["ScannedCount"]) == (0, 0) - in_filter = dynamodb_client.query( + def test_mixed_digits_in_the_filter_are_accepted(self, dynamodb_client, ns_table, raw): + resp = dynamodb_client.query( TableName=ns_table, KeyConditionExpression="pk = :u AND sk = :s", FilterExpression="a = :f", ExpressionAttributeValues={":u": CAROL, ":s": {"N": "1"}, ":f": {"N": raw}}) - assert (in_filter["Count"], in_filter["ScannedCount"]) == (0, 1) + assert (resp["Count"], resp["ScannedCount"]) == (0, 1) def test_fullwidth_digit_in_a_number_set_passes_the_check(self, dynamodb_client, ns_table): resp = dynamodb_client.query( @@ -660,3 +647,38 @@ def test_every_fence_form_gets_validation_exception_and_no_items(self): failures.append(f"{shape} / {label}: {err['Code']} {err['Message']}") owner.delete_table(TableName=table) assert not failures, "\n".join(failures) + + def test_a_unicode_digit_key_value_reads_no_fenced_partition(self): + """A partition key value written with Unicode digits is not bound to a + LeadingKeys value, so it must not read a partition the fence keeps the + principal from. The service's answer for a fenced principal cannot be + measured here; the test asserts only that no item of partition 20 is + returned, whatever the answer is.""" + owner = self._client({ + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"}], + }) + table = f"kv-{uuid.uuid4().hex[:8]}" + owner.create_table( + TableName=table, + AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "N"}], + KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}], + BillingMode="PAY_PER_REQUEST") + wait_for_active(owner, table) + for pk in ("10", "20"): + owner.put_item(TableName=table, Item={"pk": {"N": pk}, "v": {"S": "p" + pk}}) + fenced = self._client(self._fence( + {"ForAllValues:StringEquals": {"dynamodb:LeadingKeys": ["10"]}}, table)) + leaks = [] + for label, value in (("fullwidth", "\uff12\uff10"), ("arabic-indic", "\u0662\u0660"), + ("devanagari", "\u0968\u0966")): + try: + resp = fenced.query( + TableName=table, KeyConditionExpression="pk = :p", + ExpressionAttributeValues={":p": {"N": value}}) + except ClientError: + continue + if any(item.get("v") == {"S": "p20"} for item in resp["Items"]): + leaks.append(label) + owner.delete_table(TableName=table) + assert not leaks, leaks From 20621876fe84c867895d44c3ff6d08f80e5bee1d Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sun, 25 Oct 2026 09:34:39 +0000 Subject: [PATCH 07/30] fix(scan): check the numbers in ExpressionAttributeValues at request time Scan did not check that the N values in ExpressionAttributeValues are numbers, so a filter on {"N": "bob"}, a nested one in an L, M or NS, an overflow, an underflow, a 39 digit value or an empty N answered 200 with Count 0. The service refuses each with the same ValidationException text Query uses, whether or not an expression reads the value. Move the early Scan checks to a request-time function on the raw body, in the order measured on 2026-10-25: the Limit, Segment and TotalSegments ranges (one aggregated message, "Value at 'Limit'" with no value echoed), the expression and non-expression parameter mix, the ReturnConsumedCapacity enum, every number in ExpressionAttributeValues, then the Select enum. Both enums invalid now answers the ReturnConsumedCapacity error alone, as the service does; the earlier aggregation of the two no longer matched it. The Segment pairing checks stay in the handler after the table lookup. The two Scan tests that asserted the old segment range text now assert the measured text. --- crates/engine/src/lib.rs | 3 +- crates/engine/src/query_key_values.rs | 4 +- crates/engine/src/scan.rs | 88 +------ crates/engine/src/scan_request.rs | 133 ++++++++++ crates/engine/src/scan_request/tests.rs | 329 ++++++++++++++++++++++++ tests/test_query_scan.py | 20 +- 6 files changed, 488 insertions(+), 89 deletions(-) create mode 100644 crates/engine/src/scan_request.rs create mode 100644 crates/engine/src/scan_request/tests.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2cb47da7f..a8ab1d5fc 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -32,6 +32,7 @@ pub mod query_key_values; mod read_helpers; mod request_limits; mod scan; +pub mod scan_request; mod search_vectors; pub mod stream_capture; mod streams; @@ -217,7 +218,7 @@ pub(crate) const RETURN_VALUES_MEMBERS: &[&str] = /// Pre-validate enum fields in a JSON body and return a combined error if /// multiple are invalid, in the order listed. Whether an operation aggregates /// its enum violations or stops at the first is per operation on the service -/// (PutItem/DeleteItem/Scan aggregate; UpdateItem and Query stop at the +/// (PutItem and DeleteItem aggregate; UpdateItem, Query and Scan stop at the /// first), so callers choose by passing one list or several sequential calls. pub(crate) fn validate_enum_fields( body: &serde_json::Value, diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index 54886bf96..42d10ee79 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -181,12 +181,12 @@ fn query_request_checks(body: &Value) -> Result<(), DynamoDbError> { /// Whether `field` is in the body with a value other than `null`, as a typed /// `Option` field would deserialize to `Some`. -fn present(body: &Value, field: &str) -> bool { +pub(crate) fn present(body: &Value, field: &str) -> bool { body.get(field).is_some_and(|v| !v.is_null()) } /// Whether `field` is a non-empty JSON object or array in the body. -fn non_empty(body: &Value, field: &str) -> bool { +pub(crate) fn non_empty(body: &Value, field: &str) -> bool { match body.get(field) { Some(Value::Object(map)) => !map.is_empty(), Some(Value::Array(items)) => !items.is_empty(), diff --git a/crates/engine/src/scan.rs b/crates/engine/src/scan.rs index 1c1de2274..2a2214d84 100755 --- a/crates/engine/src/scan.rs +++ b/crates/engine/src/scan.rs @@ -41,58 +41,19 @@ pub async fn handle_scan( body: Value, ctx: &OperationContext, ) -> Result { - // Pre-scanned before typed deserialization. Scan AGGREGATES its invalid - // enums with Select's clause ahead of ReturnConsumedCapacity's, the - // opposite of Query on both counts (Query stops at the first, RCC-first). - // Measured 2026-08-24 (us-east-1): both invalid answers "2 validation - // errors detected: ... 'select' ...; ... 'returnConsumedCapacity' ...". - crate::validate_enum_fields( - &body, - &[ - crate::EnumField { - json_name: "Select", - valid: &[ - "SPECIFIC_ATTRIBUTES", - "COUNT", - "ALL_ATTRIBUTES", - "ALL_PROJECTED_ATTRIBUTES", - ], - clause: crate::EnumClause::Named("select"), - }, - crate::EnumField { - json_name: "ReturnConsumedCapacity", - valid: &["INDEXES", "TOTAL", "NONE"], - clause: crate::EnumClause::Named("returnConsumedCapacity"), - }, - ], - )?; + // Request-time checks on the raw body, in the service's order: the Limit, + // Segment and TotalSegments ranges, the expression and non-expression + // parameter mix, the ReturnConsumedCapacity enum, every number in + // ExpressionAttributeValues, the Select enum. They run before typed + // deserialization so a field that does not deserialize does not stop the + // ones before it; see `scan_request`. + crate::scan_request::validate_scan_request_body(&body)?; let input: ScanInput = serde_json::from_value(body).map_err(crate::deserialize_error)?; // Validate Filter/Projection expressions before the existence - // check; index resolution, Segment/Limit/Select and key checks stay after. - - // --- Legacy vs expression mutual exclusivity checks --- - let has_fe = input.filter_expression.is_some(); - let has_sf = input.scan_filter.as_ref().is_some_and(|m| !m.is_empty()); - let has_pe = input.projection_expression.is_some(); - let has_atg = input - .attributes_to_get - .as_ref() - .is_some_and(|a| !a.is_empty()); + // check; index resolution, Segment pairing, Select and key checks stay after. let has_cond_op = input.conditional_operator.is_some(); - extenddb_core::validation::validate_no_expression_param_mixing( - &[ - ("AttributesToGet", has_atg), - ("ScanFilter", has_sf), - ("ConditionalOperator", has_cond_op), - ], - &[ - ("ProjectionExpression", has_pe), - ("FilterExpression", has_fe), - ], - )?; - let maps = build_expression_maps( input.expression_attribute_names.as_ref(), input.expression_attribute_values.as_ref(), @@ -299,7 +260,9 @@ pub async fn handle_scan( )?; } - // Validate Segment/TotalSegments — DynamoDB returns different messages per direction + // Validate Segment/TotalSegments pairing. The range of each field is + // checked at request time in validate_scan_request_body; the service + // reports a missing partner with a message per direction. match (input.segment, input.total_segments) { (Some(_), None) => { return Err(DynamoDbError::ValidationException( @@ -314,26 +277,6 @@ pub async fn handle_scan( )); } (Some(seg), Some(total)) => { - if total < 1 { - return Err(DynamoDbError::ValidationException( - "The parameter TotalSegments should be greater than or equal to 1".to_owned(), - )); - } - if total > 1_000_000 { - return Err(DynamoDbError::ValidationException(format!( - "1 validation error detected: Value '{total}' at 'totalSegments' failed to satisfy constraint: Member must have value less than or equal to 1000000" - ))); - } - if seg < 0 { - return Err(DynamoDbError::ValidationException(format!( - "1 validation error detected: Value '{seg}' at 'segment' failed to satisfy constraint: Member must have value greater than or equal to 0" - ))); - } - if seg > 999_999 { - return Err(DynamoDbError::ValidationException(format!( - "1 validation error detected: Value '{seg}' at 'segment' failed to satisfy constraint: Member must have value less than or equal to 999999" - ))); - } if seg >= total { return Err(DynamoDbError::ValidationException(format!( "The Segment parameter is zero-based and must be less than parameter TotalSegments: \ @@ -344,14 +287,7 @@ pub async fn handle_scan( (None, None) => {} } - // Validate Limit >= 1 - if let Some(limit) = input.limit - && limit < 1 - { - return Err(DynamoDbError::ValidationException(format!( - "1 validation error detected: Value '{limit}' at 'limit' failed to satisfy constraint: Member must have value greater than or equal to 1" - ))); - } + // Limit >= 1 is checked at request time in validate_scan_request_body. // For index scans, build a key_info that reflects the index's key schema. let scan_key_info = if let Some(ref idx) = index_info { diff --git a/crates/engine/src/scan_request.rs b/crates/engine/src/scan_request.rs new file mode 100644 index 000000000..e1f89f410 --- /dev/null +++ b/crates/engine/src/scan_request.rs @@ -0,0 +1,133 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The `Scan` checks that run on the request body alone, before the body is +//! deserialized and before the table is looked up, in the service's order. +//! +//! Measured 2026-10-25 (us-east-1, each request twice): +//! +//! 1. the range constraints on `Limit` (at least 1), `Segment` (0 to 999999) +//! and `TotalSegments` (1 to 1000000), aggregated into one message in that +//! order with no value echoed: `2 validation errors detected: Value at +//! 'Limit' failed to satisfy constraint: Member must have value greater than +//! or equal to 1; Value at 'Segment' ...`. Each field is checked when +//! present, whether or not the other segment field is; +//! 2. the expression and non-expression parameter mix; +//! 3. the `ReturnConsumedCapacity` enum; +//! 4. every number in `ExpressionAttributeValues`, `NS` members and values +//! nested in `L` and `M` included, whether a `FilterExpression` reads the +//! value, nothing reads it, or the request carries no expression at all; +//! 5. the `Select` enum. Both enums invalid answers the `ReturnConsumedCapacity` +//! error alone, so the two are not aggregated. +//! +//! Each of these is reported ahead of the next one, ahead of the table lookup, +//! and ahead of the checks the handler makes after deserializing the body +//! (Segment without TotalSegments and the reverse, Segment not below +//! TotalSegments, the undefined placeholder, unused value, filter syntax, +//! IndexName, ConsistentRead, Select with ProjectionExpression and +//! ExclusiveStartKey checks). + +use std::collections::HashMap; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::types::AttributeValue; +use serde_json::Value; + +use crate::query_key_values::{non_empty, present, validate_expression_attribute_value_numbers}; + +/// The `Scan` checks that run on the raw request body, in the service's order: +/// the `Limit`, `Segment` and `TotalSegments` ranges, the expression and +/// non-expression parameter mix, the `ReturnConsumedCapacity` enum, every +/// number in `ExpressionAttributeValues`, then the `Select` enum. +/// +/// The checks read the raw body, so a field that does not deserialize (an +/// invalid `Select`, for one) does not stop the ones before it. A field of the +/// wrong JSON shape is left to the deserializer, which runs next. +/// +/// # Errors +/// +/// Returns `DynamoDbError::ValidationException` with the service's text. +pub fn validate_scan_request_body(body: &Value) -> Result<(), DynamoDbError> { + validate_ranges(body)?; + + extenddb_core::validation::validate_no_expression_param_mixing( + &[ + ("AttributesToGet", non_empty(body, "AttributesToGet")), + ("ScanFilter", non_empty(body, "ScanFilter")), + ("ConditionalOperator", present(body, "ConditionalOperator")), + ], + &[ + ( + "ProjectionExpression", + present(body, "ProjectionExpression"), + ), + ("FilterExpression", present(body, "FilterExpression")), + ], + )?; + + crate::validate_enum_fields( + body, + &[crate::EnumField { + json_name: "ReturnConsumedCapacity", + valid: &["INDEXES", "TOTAL", "NONE"], + clause: crate::EnumClause::Named("returnConsumedCapacity"), + }], + )?; + + if let Some(raw) = body.get("ExpressionAttributeValues") + && let Ok(values) = serde_json::from_value::>(raw.clone()) + { + validate_expression_attribute_value_numbers(&values)?; + } + + crate::validate_enum_fields( + body, + &[crate::EnumField { + json_name: "Select", + valid: &[ + "SPECIFIC_ATTRIBUTES", + "COUNT", + "ALL_ATTRIBUTES", + "ALL_PROJECTED_ATTRIBUTES", + ], + clause: crate::EnumClause::Named("select"), + }], + ) +} + +/// The range constraints on `Limit`, `Segment` and `TotalSegments`, aggregated +/// in that order as the service reports them. The field name is capitalised +/// and the value is not echoed, unlike the `select` and `segment` style the +/// other `1 validation error detected` messages use. +fn validate_ranges(body: &Value) -> Result<(), DynamoDbError> { + let mut errors: Vec = Vec::new(); + let mut check = |field: &str, below: i64, above: i64| { + let Some(value) = body.get(field).and_then(Value::as_i64) else { + return; + }; + if value < below { + errors.push(format!( + "Value at '{field}' failed to satisfy constraint: Member must have value greater than or equal to {below}" + )); + } else if value > above { + errors.push(format!( + "Value at '{field}' failed to satisfy constraint: Member must have value less than or equal to {above}" + )); + } + }; + check("Limit", 1, i64::MAX); + check("Segment", 0, 999_999); + check("TotalSegments", 1, 1_000_000); + if errors.is_empty() { + return Ok(()); + } + let count = errors.len(); + Err(DynamoDbError::ValidationException(format!( + "{count} validation error{} detected: {}", + if count == 1 { "" } else { "s" }, + errors.join("; ") + ))) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/scan_request/tests.rs b/crates/engine/src/scan_request/tests.rs new file mode 100644 index 000000000..80af8ae17 --- /dev/null +++ b/crates/engine/src/scan_request/tests.rs @@ -0,0 +1,329 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Every expected text below was measured against the service on 2026-10-25 +//! (us-east-1, each request twice). + +use extenddb_core::error::DynamoDbError; +use serde_json::{Value, json}; + +use super::validate_scan_request_body; + +const NUMERIC_BOB: &str = "The parameter cannot be converted to a numeric value: bob"; +const LIMIT_RANGE: &str = "Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1"; +const RCC_ENUM: &str = "1 validation error detected: Value 'NOPE' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]"; +const SELECT_ENUM: &str = "1 validation error detected: Value 'NOPE' at 'select' failed to satisfy constraint: Member must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]"; + +fn message(result: Result<(), DynamoDbError>) -> Option { + match result { + Ok(()) => None, + Err(DynamoDbError::ValidationException(msg)) => Some(msg), + Err(other) => panic!("unexpected error {other:?}"), + } +} + +fn check(body: &Value) -> Option { + message(validate_scan_request_body(body)) +} + +/// A Scan whose filter reads `:n = {"N": "bob"}`. +fn bad_number() -> Value { + json!({ + "TableName": "t", + "FilterExpression": "a = :n", + "ExpressionAttributeValues": {":n": {"N": "bob"}}, + }) +} + +fn with(mut body: Value, field: &str, value: Value) -> Value { + body[field] = value; + body +} + +#[test] +fn numbers_are_checked_whether_or_not_an_expression_reads_them() { + assert_eq!(check(&bad_number()).as_deref(), Some(NUMERIC_BOB)); + // Nothing reads :n; the filter reads :p. + assert_eq!( + check(&json!({ + "TableName": "t", + "FilterExpression": "a = :p", + "ExpressionAttributeValues": {":p": {"S": "x"}, ":n": {"N": "bob"}}, + })) + .as_deref(), + Some(NUMERIC_BOB) + ); + // No expression at all, a ScanFilter only, a ProjectionExpression only. + for body in [ + json!({"TableName": "t", "ExpressionAttributeValues": {":n": {"N": "bob"}}}), + json!({ + "TableName": "t", + "ScanFilter": {"a": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]}}, + "ExpressionAttributeValues": {":n": {"N": "bob"}}, + }), + json!({ + "TableName": "t", + "ProjectionExpression": "a", + "ExpressionAttributeValues": {":n": {"N": "bob"}}, + }), + ] { + assert_eq!(check(&body).as_deref(), Some(NUMERIC_BOB), "{body}"); + } +} + +#[test] +fn nested_numbers_and_the_other_number_faults_are_reported_with_the_service_text() { + let cases = [ + (json!({"L": [{"S": "a"}, {"N": "bob"}]}), NUMERIC_BOB), + (json!({"M": {"a": {"N": "bob"}}}), NUMERIC_BOB), + (json!({"NS": ["1", "bob"]}), NUMERIC_BOB), + ( + json!({"M": {"a": {"L": [{"M": {"b": {"N": "bob"}}}]}}}), + NUMERIC_BOB, + ), + ( + json!({"N": "1e200"}), + "Number overflow. Attempting to store a number with magnitude larger than supported range", + ), + ( + json!({"N": "1e-200"}), + "Number underflow. Attempting to store a number with magnitude smaller than supported range", + ), + ( + json!({"N": "1".repeat(39)}), + "Attempting to store more than 38 significant digits in a Number", + ), + ( + json!({"N": ""}), + "The parameter cannot be converted to a numeric value: ", + ), + ( + json!({"N": " 1"}), + "The parameter cannot be converted to a numeric value: 1", + ), + ]; + for (value, expected) in cases { + let body = json!({ + "TableName": "t", + "FilterExpression": "a = :p", + "ExpressionAttributeValues": {":p": {"S": "x"}, ":n": value}, + }); + assert_eq!(check(&body).as_deref(), Some(expected), "{body}"); + } + // A well-formed exponent passes. + assert!( + check(&json!({ + "TableName": "t", + "FilterExpression": "a = :n", + "ExpressionAttributeValues": {":n": {"N": "1.0e1"}}, + })) + .is_none() + ); +} + +#[test] +fn limit_segment_and_total_segments_ranges_come_first_and_aggregate() { + let base = bad_number(); + assert_eq!( + check(&with(base.clone(), "Limit", json!(0))).as_deref(), + Some(&*format!("1 validation error detected: {LIMIT_RANGE}")) + ); + assert_eq!( + check(&with(base.clone(), "Limit", json!(-1))).as_deref(), + Some(&*format!("1 validation error detected: {LIMIT_RANGE}")) + ); + // Each segment field is range checked when present, with or without the + // other one. + for (field, value, text) in [ + ( + "Segment", + -1, + "Value at 'Segment' failed to satisfy constraint: Member must have value greater than or equal to 0", + ), + ( + "Segment", + 1_000_000, + "Value at 'Segment' failed to satisfy constraint: Member must have value less than or equal to 999999", + ), + ( + "TotalSegments", + 0, + "Value at 'TotalSegments' failed to satisfy constraint: Member must have value greater than or equal to 1", + ), + ( + "TotalSegments", + 1_000_001, + "Value at 'TotalSegments' failed to satisfy constraint: Member must have value less than or equal to 1000000", + ), + ] { + assert_eq!( + check(&with(base.clone(), field, json!(value))).as_deref(), + Some(&*format!("1 validation error detected: {text}")), + "{field} {value}" + ); + let partner = if field == "Segment" { + ("TotalSegments", 2) + } else { + ("Segment", 0) + }; + let paired = with( + with(base.clone(), field, json!(value)), + partner.0, + json!(partner.1), + ); + assert_eq!( + check(&paired).as_deref(), + Some(&*format!("1 validation error detected: {text}")), + "{field} {value} with {}", + partner.0 + ); + } + // Limit, Segment, TotalSegments, in that order, one message. + let three = with( + with( + with(json!({"TableName": "t"}), "Limit", json!(0)), + "Segment", + json!(-1), + ), + "TotalSegments", + json!(1_000_001), + ); + assert_eq!( + check(&three).as_deref(), + Some( + "3 validation errors detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1; Value at 'Segment' failed to satisfy constraint: Member must have value greater than or equal to 0; Value at 'TotalSegments' failed to satisfy constraint: Member must have value less than or equal to 1000000" + ) + ); + // Values at the bounds pass. + assert!( + check( + &json!({"TableName": "t", "Limit": 1, "Segment": 999_999, "TotalSegments": 1_000_000}) + ) + .is_none() + ); + // A range fault beats the parameter mix and the ReturnConsumedCapacity enum. + let mix = with( + with(base.clone(), "Segment", json!(-1)), + "ScanFilter", + json!({"a": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]}}), + ); + assert!(check(&mix).is_some_and(|m| m.contains("Value at 'Segment'"))); + let rcc = with( + with(base, "Limit", json!(0)), + "ReturnConsumedCapacity", + json!("NOPE"), + ); + assert_eq!( + check(&rcc).as_deref(), + Some(&*format!("1 validation error detected: {LIMIT_RANGE}")) + ); +} + +#[test] +fn parameter_mix_beats_the_enum_and_the_numbers() { + let scan_filter = + json!({"a": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]}}); + let mix = with(bad_number(), "ScanFilter", scan_filter.clone()); + assert_eq!( + check(&mix).as_deref(), + Some( + "Can not use both expression and non-expression parameters in the same request: \ + Non-expression parameters: {ScanFilter} Expression parameters: {FilterExpression}" + ) + ); + assert_eq!( + check(&with(mix, "ReturnConsumedCapacity", json!("NOPE"))).as_deref(), + Some( + "Can not use both expression and non-expression parameters in the same request: \ + Non-expression parameters: {ScanFilter} Expression parameters: {FilterExpression}" + ) + ); + let atg = with( + with(bad_number(), "AttributesToGet", json!(["a"])), + "ProjectionExpression", + json!("a"), + ); + assert_eq!( + check(&atg).as_deref(), + Some( + "Can not use both expression and non-expression parameters in the same request: \ + Non-expression parameters: {AttributesToGet} Expression parameters: {ProjectionExpression, FilterExpression}" + ) + ); + assert_eq!( + check(&with(bad_number(), "ConditionalOperator", json!("AND"))).as_deref(), + Some( + "Can not use both expression and non-expression parameters in the same request: \ + Non-expression parameters: {ConditionalOperator} Expression parameters: {FilterExpression}" + ) + ); + // ConditionalOperator with no expression does not join the mix; the + // numbers are reported. + assert_eq!( + check(&json!({ + "TableName": "t", + "ConditionalOperator": "AND", + "ExpressionAttributeValues": {":n": {"N": "bob"}}, + })) + .as_deref(), + Some(NUMERIC_BOB) + ); + // An empty ScanFilter or AttributesToGet does not join the mix. + assert!( + check(&json!({ + "TableName": "t", + "ScanFilter": {}, + "AttributesToGet": [], + "FilterExpression": "a = :n", + "ExpressionAttributeValues": {":n": {"N": "1"}}, + })) + .is_none() + ); +} + +#[test] +fn enum_checks_sit_on_either_side_of_the_numbers() { + assert_eq!( + check(&with(bad_number(), "ReturnConsumedCapacity", json!("NOPE"))).as_deref(), + Some(RCC_ENUM) + ); + assert_eq!( + check(&with(bad_number(), "Select", json!("NOPE"))).as_deref(), + Some(NUMERIC_BOB) + ); + // Both invalid: ReturnConsumedCapacity alone, not aggregated with Select. + let both = with( + with(json!({"TableName": "t"}), "Select", json!("NOPE")), + "ReturnConsumedCapacity", + json!("NOPE"), + ); + assert_eq!(check(&both).as_deref(), Some(RCC_ENUM)); + // With the numbers valid, an invalid Select is reported. + assert_eq!( + check(&json!({"TableName": "t", "Select": "NOPE"})).as_deref(), + Some(SELECT_ENUM) + ); + // A valid request passes. + assert!( + check(&json!({ + "TableName": "t", + "Select": "COUNT", + "ReturnConsumedCapacity": "TOTAL", + "Limit": 5, + "FilterExpression": "a = :n", + "ExpressionAttributeValues": {":n": {"N": "5"}}, + })) + .is_none() + ); +} + +#[test] +fn values_that_do_not_deserialize_are_left_to_the_deserializer() { + // A string Limit and a malformed ExpressionAttributeValues are not range + // or number faults here; the typed deserializer reports them next. + assert!(check(&json!({"TableName": "t", "Limit": "0"})).is_none()); + assert!( + check(&json!({"TableName": "t", "ExpressionAttributeValues": {":n": {"X": "bob"}}})) + .is_none() + ); +} diff --git a/tests/test_query_scan.py b/tests/test_query_scan.py index 44a82f4a2..04019c990 100755 --- a/tests/test_query_scan.py +++ b/tests/test_query_scan.py @@ -614,17 +614,17 @@ def test_scan_segment_at_max_accepted(self, dynamodb_client, scan_table): def test_scan_segment_one_over_max_rejected( self, dynamodb_client_no_validation, scan_table ): - """Segment > 999999 returns the Coral-format ValidationException.""" + """Segment > 999999 returns the range ValidationException (measured 2026-10-25).""" with pytest.raises(ClientError) as exc_info: dynamodb_client_no_validation.scan( TableName=scan_table, Segment=1_000_000, TotalSegments=1_000_000 ) err = exc_info.value.response["Error"] assert err["Code"] == "ValidationException" - msg = err["Message"] - assert "1 validation error detected" in msg - assert "'1000000' at 'segment'" in msg - assert "Member must have value less than or equal to 999999" in msg + assert err["Message"] == ( + "1 validation error detected: Value at 'Segment' failed to satisfy " + "constraint: Member must have value less than or equal to 999999" + ) def test_scan_total_segments_at_max_accepted(self, dynamodb_client, scan_table): """TotalSegments=1000000 with Segment=0 is at the documented bound.""" @@ -635,17 +635,17 @@ def test_scan_total_segments_at_max_accepted(self, dynamodb_client, scan_table): def test_scan_total_segments_one_over_max_rejected( self, dynamodb_client_no_validation, scan_table ): - """TotalSegments > 1000000 returns the Coral-format ValidationException.""" + """TotalSegments > 1000000 returns the range ValidationException (measured 2026-10-25).""" with pytest.raises(ClientError) as exc_info: dynamodb_client_no_validation.scan( TableName=scan_table, Segment=0, TotalSegments=1_000_001 ) err = exc_info.value.response["Error"] assert err["Code"] == "ValidationException" - msg = err["Message"] - assert "1 validation error detected" in msg - assert "'1000001' at 'totalSegments'" in msg - assert "Member must have value less than or equal to 1000000" in msg + assert err["Message"] == ( + "1 validation error detected: Value at 'TotalSegments' failed to satisfy " + "constraint: Member must have value less than or equal to 1000000" + ) def test_scan_all_projected_attributes_without_index_rejected( self, dynamodb_client, scan_table From 6f1e28421351cd9857070e1bfc59793207735de3 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sun, 25 Oct 2026 09:36:47 +0000 Subject: [PATCH 08/30] test(scan): wire tests for the request-time number check and its position Every N value shape the service refuses on Scan (a word, a nested L, M or NS member, overflow, underflow, 39 digits, empty, a leading space), read by the filter or by nothing, and the order against every other early check: the Limit, Segment and TotalSegments ranges, the parameter mix and the ReturnConsumedCapacity enum ahead of it; the Select enum, the Segment pairing, the table lookup, IndexName, ConsistentRead, Select with ProjectionExpression, ExclusiveStartKey, undefined placeholder and filter syntax checks behind it. Expected texts measured on 2026-10-25. --- tests/test_scan_number_values.py | 330 +++++++++++++++++++++++++++++++ 1 file changed, 330 insertions(+) create mode 100644 tests/test_scan_number_values.py diff --git a/tests/test_scan_number_values.py b/tests/test_scan_number_values.py new file mode 100644 index 000000000..df354ef4d --- /dev/null +++ b/tests/test_scan_number_values.py @@ -0,0 +1,330 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Scan checks the numbers in ``ExpressionAttributeValues`` at request time. + +An ``N`` value that is not a number, an ``N`` nested in an ``L`` or ``M``, an +``NS`` member, an overflow, an underflow, a value with more than 38 +significant digits or an empty ``N`` is refused with ``ValidationException`` +before any row is read, whether a ``FilterExpression`` reads the value, +nothing reads it, or the request carries no expression at all. Every expected +answer below was measured against the service on 2026-10-25 (09:23 to 09:28 +UTC) with each request sent twice. + +The rows also pin where the check falls against the other early Scan checks: +after the ``Limit``, ``Segment`` and ``TotalSegments`` range constraints (one +aggregated message, ``Value at 'Limit'`` with no value echoed), the expression +and non-expression parameter mix and the ``ReturnConsumedCapacity`` enum; and +before the ``Select`` enum, the Segment pairing checks, the table lookup, the +IndexName, ConsistentRead, Select with ProjectionExpression, +ExclusiveStartKey, undefined placeholder, unused value and filter syntax +checks. + +Dual-target: runs against the service and against extenddb with the same +assertions. + +Run: + EXTENDDB_TEST_ENDPOINT=https://localhost:18443 \\ + EXTENDDB_ADMIN_USER=admin EXTENDDB_ADMIN_PASSWORD= \\ + pytest tests/test_scan_number_values.py -v +""" + +from __future__ import annotations + +import pytest +from botocore.exceptions import ClientError + +from conftest import scoped_table + +NUMERIC = "The parameter cannot be converted to a numeric value: " +OVERFLOW = ( + "Number overflow. Attempting to store a number with magnitude larger than " + "supported range" +) +UNDERFLOW = ( + "Number underflow. Attempting to store a number with magnitude smaller than " + "supported range" +) +TOO_MANY_DIGITS = "Attempting to store more than 38 significant digits in a Number" +LIMIT_RANGE = ( + "Value at 'Limit' failed to satisfy constraint: " + "Member must have value greater than or equal to 1" +) +RCC_ENUM = ( + "1 validation error detected: Value 'NOPE' at 'returnConsumedCapacity' failed " + "to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]" +) +SELECT_ENUM = ( + "1 validation error detected: Value 'NOPE' at 'select' failed to satisfy " + "constraint: Member must satisfy enum value set: " + "[SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]" +) + +S = {"AttributeType": "S"} +SX = {"S": "x"} +NB = {"N": "bob"} +NB_FILTER = {"FilterExpression": "a = :n", "ExpressionAttributeValues": {":n": NB}} +OK_FILTER = {"FilterExpression": "a = :n", "ExpressionAttributeValues": {":n": {"N": "1"}}} +SCAN_FILTER = {"a": {"ComparisonOperator": "EQ", "AttributeValueList": [SX]}} + + +def _err(exc_info) -> tuple[str, str]: + err = exc_info.value.response["Error"] + return err["Code"], err["Message"] + + +def _scan_error(client, **kwargs) -> tuple[str, str]: + with pytest.raises(ClientError) as exc_info: + client.scan(**kwargs) + return _err(exc_info) + + +@pytest.fixture(scope="module") +def table(dynamodb_client): + """pk S, sk S; GSI gsi1 on gpk S (hash only).""" + with scoped_table( + dynamodb_client, + attribute_definitions=[ + {"AttributeName": "pk", **S}, + {"AttributeName": "sk", **S}, + {"AttributeName": "gpk", **S}, + ], + key_schema=[ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"}, + ], + GlobalSecondaryIndexes=[{ + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "gpk", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"}, + }], + ) as name: + for pk in ("alice", "bob"): + dynamodb_client.put_item(TableName=name, Item={ + "pk": {"S": pk}, "sk": {"S": "1"}, "gpk": {"S": pk}, "a": {"N": "1"}}) + yield name + + +class TestNumberValues: + """Every number in ExpressionAttributeValues is checked.""" + + @pytest.mark.parametrize("value, expected", [ + pytest.param(NB, NUMERIC + "bob", id="N-bob"), + pytest.param({"L": [SX, NB]}, NUMERIC + "bob", id="L-with-N-bob"), + pytest.param({"M": {"a": NB}}, NUMERIC + "bob", id="M-with-N-bob"), + pytest.param({"NS": ["1", "bob"]}, NUMERIC + "bob", id="NS-with-bob"), + pytest.param({"M": {"a": {"L": [{"M": {"b": NB}}]}}}, NUMERIC + "bob", id="M-L-M-N-bob"), + pytest.param({"N": "1e200"}, OVERFLOW, id="overflow"), + pytest.param({"N": "1e-200"}, UNDERFLOW, id="underflow"), + pytest.param({"N": "1" * 39}, TOO_MANY_DIGITS, id="39-digits"), + pytest.param({"N": ""}, NUMERIC, id="empty"), + pytest.param({"N": " 1"}, NUMERIC + " 1", id="leading-space"), + ]) + def test_value_read_by_the_filter(self, dynamodb_client, table, value, expected): + assert _scan_error( + dynamodb_client, TableName=table, + FilterExpression="a = :n", ExpressionAttributeValues={":n": value}, + ) == ("ValidationException", expected) + + @pytest.mark.parametrize("value, expected", [ + pytest.param(NB, NUMERIC + "bob", id="N-bob"), + pytest.param({"L": [SX, NB]}, NUMERIC + "bob", id="L-with-N-bob"), + pytest.param({"M": {"a": NB}}, NUMERIC + "bob", id="M-with-N-bob"), + pytest.param({"NS": ["1", "bob"]}, NUMERIC + "bob", id="NS-with-bob"), + pytest.param({"M": {"a": {"L": [{"M": {"b": NB}}]}}}, NUMERIC + "bob", id="M-L-M-N-bob"), + pytest.param({"N": "1e200"}, OVERFLOW, id="overflow"), + pytest.param({"N": "1" * 39}, TOO_MANY_DIGITS, id="39-digits"), + pytest.param({"N": ""}, NUMERIC, id="empty"), + ]) + def test_value_nothing_reads(self, dynamodb_client, table, value, expected): + """The filter reads :p; :n is checked all the same, ahead of the unused value check.""" + assert _scan_error( + dynamodb_client, TableName=table, + FilterExpression="a = :p", ExpressionAttributeValues={":p": SX, ":n": value}, + ) == ("ValidationException", expected) + + def test_no_expression_at_all(self, dynamodb_client, table): + assert _scan_error( + dynamodb_client, TableName=table, ExpressionAttributeValues={":n": NB}, + ) == ("ValidationException", NUMERIC + "bob") + + def test_with_scan_filter_only(self, dynamodb_client, table): + assert _scan_error( + dynamodb_client, TableName=table, ScanFilter=SCAN_FILTER, + ExpressionAttributeValues={":n": NB}, + ) == ("ValidationException", NUMERIC + "bob") + + def test_with_projection_expression_only(self, dynamodb_client, table): + assert _scan_error( + dynamodb_client, TableName=table, ProjectionExpression="a", + ExpressionAttributeValues={":n": NB}, + ) == ("ValidationException", NUMERIC + "bob") + + def test_with_conditional_operator_and_no_filter(self, dynamodb_client, table): + """ConditionalOperator alone does not join the parameter mix; the number is reported.""" + assert _scan_error( + dynamodb_client, TableName=table, ConditionalOperator="AND", + ExpressionAttributeValues={":n": NB}, + ) == ("ValidationException", NUMERIC + "bob") + + def test_two_bad_numbers_report_one_of_them(self, dynamodb_client, table): + """The service's choice between two bad values varied between two runs; either is accepted.""" + code, msg = _scan_error( + dynamodb_client, TableName=table, FilterExpression="a = :a", + ExpressionAttributeValues={":a": {"N": "one"}, ":b": {"N": "two"}}, + ) + assert code == "ValidationException" + assert msg in (NUMERIC + "one", NUMERIC + "two") + + def test_well_formed_numbers_pass(self, dynamodb_client, table): + for value in ("1", "1.0e1"): + response = dynamodb_client.scan( + TableName=table, FilterExpression="a = :n", + ExpressionAttributeValues={":n": {"N": value}}, + ) + assert "Count" in response, value + + +class TestChecksBeforeTheNumbers: + """Range constraints, the parameter mix and ReturnConsumedCapacity win over a bad number.""" + + @pytest.mark.parametrize("limit", [0, -1]) + def test_limit_range(self, dynamodb_client_no_validation, table, limit): + assert _scan_error( + dynamodb_client_no_validation, TableName=table, Limit=limit, **NB_FILTER, + ) == ("ValidationException", "1 validation error detected: " + LIMIT_RANGE) + + @pytest.mark.parametrize("kwargs, text", [ + pytest.param({"Segment": 0, "TotalSegments": 0}, + "Value at 'TotalSegments' failed to satisfy constraint: " + "Member must have value greater than or equal to 1", id="TotalSegments-0"), + pytest.param({"Segment": 0, "TotalSegments": 1_000_001}, + "Value at 'TotalSegments' failed to satisfy constraint: " + "Member must have value less than or equal to 1000000", id="TotalSegments-1000001"), + pytest.param({"Segment": -1, "TotalSegments": 2}, + "Value at 'Segment' failed to satisfy constraint: " + "Member must have value greater than or equal to 0", id="Segment-minus-1"), + pytest.param({"Segment": 1_000_000, "TotalSegments": 1_000_000}, + "Value at 'Segment' failed to satisfy constraint: " + "Member must have value less than or equal to 999999", id="Segment-1000000"), + pytest.param({"Segment": -1}, + "Value at 'Segment' failed to satisfy constraint: " + "Member must have value greater than or equal to 0", id="Segment-minus-1-alone"), + pytest.param({"TotalSegments": 0}, + "Value at 'TotalSegments' failed to satisfy constraint: " + "Member must have value greater than or equal to 1", id="TotalSegments-0-alone"), + ]) + def test_segment_ranges(self, dynamodb_client_no_validation, table, kwargs, text): + assert _scan_error( + dynamodb_client_no_validation, TableName=table, **kwargs, **NB_FILTER, + ) == ("ValidationException", "1 validation error detected: " + text) + + def test_ranges_aggregate_limit_then_segment_then_total_segments( + self, dynamodb_client_no_validation, table, + ): + assert _scan_error( + dynamodb_client_no_validation, TableName=table, + Limit=0, Segment=-1, TotalSegments=1_000_001, + ) == ("ValidationException", ( + "3 validation errors detected: " + LIMIT_RANGE + "; " + "Value at 'Segment' failed to satisfy constraint: " + "Member must have value greater than or equal to 0; " + "Value at 'TotalSegments' failed to satisfy constraint: " + "Member must have value less than or equal to 1000000" + )) + + def test_limit_range_beats_the_missing_table(self, dynamodb_client_no_validation): + assert _scan_error( + dynamodb_client_no_validation, TableName="extenddb-test-no-such-table", Limit=0, + ) == ("ValidationException", "1 validation error detected: " + LIMIT_RANGE) + + @pytest.mark.parametrize("extra, non_expression, expression", [ + pytest.param({"ScanFilter": SCAN_FILTER}, "ScanFilter", "FilterExpression", id="ScanFilter"), + pytest.param({"AttributesToGet": ["a"], "ProjectionExpression": "a"}, "AttributesToGet", + "ProjectionExpression, FilterExpression", id="AttributesToGet"), + pytest.param({"ConditionalOperator": "AND"}, "ConditionalOperator", "FilterExpression", + id="ConditionalOperator"), + ]) + def test_parameter_mix(self, dynamodb_client, table, extra, non_expression, expression): + assert _scan_error(dynamodb_client, TableName=table, **extra, **NB_FILTER) == ( + "ValidationException", + "Can not use both expression and non-expression parameters in the same request: " + f"Non-expression parameters: {{{non_expression}}} Expression parameters: {{{expression}}}", + ) + + def test_parameter_mix_beats_return_consumed_capacity(self, dynamodb_client_no_validation, table): + assert _scan_error( + dynamodb_client_no_validation, TableName=table, ScanFilter=SCAN_FILTER, + ReturnConsumedCapacity="NOPE", **OK_FILTER, + ) == ("ValidationException", ( + "Can not use both expression and non-expression parameters in the same request: " + "Non-expression parameters: {ScanFilter} Expression parameters: {FilterExpression}" + )) + + def test_limit_range_beats_parameter_mix(self, dynamodb_client_no_validation, table): + assert _scan_error( + dynamodb_client_no_validation, TableName=table, ScanFilter=SCAN_FILTER, Limit=0, **OK_FILTER, + ) == ("ValidationException", "1 validation error detected: " + LIMIT_RANGE) + + def test_return_consumed_capacity_enum(self, dynamodb_client_no_validation, table): + assert _scan_error( + dynamodb_client_no_validation, TableName=table, ReturnConsumedCapacity="NOPE", **NB_FILTER, + ) == ("ValidationException", RCC_ENUM) + + def test_both_enums_invalid_report_return_consumed_capacity_alone( + self, dynamodb_client_no_validation, table, + ): + for extra in ({}, NB_FILTER): + assert _scan_error( + dynamodb_client_no_validation, TableName=table, + Select="NOPE", ReturnConsumedCapacity="NOPE", **extra, + ) == ("ValidationException", RCC_ENUM) + + def test_limit_range_beats_both_enums(self, dynamodb_client_no_validation, table): + assert _scan_error( + dynamodb_client_no_validation, TableName=table, + Limit=0, Select="NOPE", ReturnConsumedCapacity="NOPE", + ) == ("ValidationException", "1 validation error detected: " + LIMIT_RANGE) + + +class TestChecksAfterTheNumbers: + """A bad number wins over every check the handler makes later.""" + + def test_select_enum(self, dynamodb_client_no_validation, table): + assert _scan_error( + dynamodb_client_no_validation, TableName=table, Select="NOPE", **NB_FILTER, + ) == ("ValidationException", NUMERIC + "bob") + assert _scan_error( + dynamodb_client_no_validation, TableName=table, Select="NOPE", **OK_FILTER, + ) == ("ValidationException", SELECT_ENUM) + + @pytest.mark.parametrize("kwargs", [ + pytest.param({"Segment": 0}, id="Segment-without-TotalSegments"), + pytest.param({"TotalSegments": 2}, id="TotalSegments-without-Segment"), + pytest.param({"Segment": 5, "TotalSegments": 2}, id="Segment-not-below-TotalSegments"), + pytest.param({"IndexName": "nope"}, id="unknown-IndexName"), + pytest.param({"IndexName": "gsi1", "ConsistentRead": True}, id="ConsistentRead-on-GSI"), + pytest.param({"Select": "COUNT", "ProjectionExpression": "a"}, id="COUNT-with-ProjectionExpression"), + pytest.param({"ExclusiveStartKey": {"wrong": SX}}, id="ExclusiveStartKey-off-schema"), + ]) + def test_handler_checks(self, dynamodb_client, table, kwargs): + assert _scan_error( + dynamodb_client, TableName=table, **kwargs, **NB_FILTER, + ) == ("ValidationException", NUMERIC + "bob") + + def test_missing_table(self, dynamodb_client): + assert _scan_error( + dynamodb_client, TableName="extenddb-test-no-such-table", **NB_FILTER, + ) == ("ValidationException", NUMERIC + "bob") + + def test_undefined_placeholder(self, dynamodb_client, table): + assert _scan_error( + dynamodb_client, TableName=table, FilterExpression="a = :zz", + ExpressionAttributeValues={":n": NB}, + ) == ("ValidationException", NUMERIC + "bob") + + def test_filter_syntax_error(self, dynamodb_client, table): + assert _scan_error( + dynamodb_client, TableName=table, FilterExpression="a = = :n", + ExpressionAttributeValues={":n": NB}, + ) == ("ValidationException", NUMERIC + "bob") From 3a633fd13a637f796f8bf27667ea83c58dca2bef Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sun, 25 Oct 2026 16:01:04 +0000 Subject: [PATCH 09/30] test(query): say which Limit text the service uses beside an unknown type descriptor --- crates/engine/src/query_key_values/tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/query_key_values/tests.rs b/crates/engine/src/query_key_values/tests.rs index e9958fe59..f1ba2d3e6 100644 --- a/crates/engine/src/query_key_values/tests.rs +++ b/crates/engine/src/query_key_values/tests.rs @@ -563,8 +563,9 @@ fn a_shape_fault_in_another_field_is_reported_ahead_of_the_checks() { ); // Neither does an unknown type descriptor, which the deserializer reports - // as a SerializationException: the service answers the Limit text - // (measured 2026-10-25). + // as a SerializationException: the service answers the Limit + // ValidationException (measured 2026-10-25), in its older + // `Value '0' at 'limit'` form; ExtendDB answers its usual Limit text. let unknown_type = serde_json::json!({ "TableName": "t", "KeyConditionExpression": "pk = :p", "Limit": 0, "ExpressionAttributeValues": {":p": {"S": "x"}, ":a": {"X": "1"}}, From d676c6ea43b9ea4cbf1521aef1f9db259d746051 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sun, 25 Oct 2026 12:20:49 +0000 Subject: [PATCH 10/30] fix(scan): report range faults one at a time, shape faults first, and accept Unicode decimal digits The range checks on Limit, Segment and TotalSegments reported every fault in one aggregated message with a capitalised field name and no value for all three fields. The service uses that form for a Limit inside the int32 range and saturates the value into the older form below it (Limit -2147483649 answers Value '-2147483648' at 'limit'); the Segment and TotalSegments texts and the aggregation are a separate question. The checks now report the first fault in the order Limit, Segment, TotalSegments; Limit follows the measured int32 rule and the two segment fields keep the texts of the previous release. The two assertions in tests/test_query_scan.py go back to the previous text. A field of the wrong JSON type in another field (a string ExpressionAttributeValues beside Limit 0, a string TotalSegments beside Segment -1, a string ExpressionAttributeNames beside a malformed N, an object AttributesToGet beside ProjectionExpression) answered the check's ValidationException where the service and the previous release answer SerializationException. When a check fails the body is deserialized as the typed input and a SerializationException from that is returned instead, with the helper the Query path uses. A Unicode decimal digit in an N value passes the request-time check shared with Query, as it does on the service. The filter compares the value as the request wrote it, as on the previous release. The unit test for the parameter mix no longer asserts that an empty ScanFilter beside a FilterExpression passes, which the service refuses as a parameter mix; the engine's handling of an empty ScanFilter and an empty AttributesToGet is unchanged and covered by a separate issue. Measured against the service on 2026-10-25 (10:38, 10:55 and 11:31 UTC), each request twice. --- crates/engine/src/scan.rs | 3 +- crates/engine/src/scan_request.rs | 115 ++++++++++------ crates/engine/src/scan_request/tests.rs | 159 ++++++++++++++++++---- tests/test_query_scan.py | 20 +-- tests/test_scan_number_values.py | 174 +++++++++++++++++++----- 5 files changed, 361 insertions(+), 110 deletions(-) diff --git a/crates/engine/src/scan.rs b/crates/engine/src/scan.rs index 2a2214d84..9a8e15296 100755 --- a/crates/engine/src/scan.rs +++ b/crates/engine/src/scan.rs @@ -46,7 +46,8 @@ pub async fn handle_scan( // parameter mix, the ReturnConsumedCapacity enum, every number in // ExpressionAttributeValues, the Select enum. They run before typed // deserialization so a field that does not deserialize does not stop the - // ones before it; see `scan_request`. + // ones before it; a field of the wrong JSON type anywhere in the body is + // reported ahead of them; see `scan_request`. crate::scan_request::validate_scan_request_body(&body)?; let input: ScanInput = serde_json::from_value(body).map_err(crate::deserialize_error)?; diff --git a/crates/engine/src/scan_request.rs b/crates/engine/src/scan_request.rs index e1f89f410..2214d0058 100644 --- a/crates/engine/src/scan_request.rs +++ b/crates/engine/src/scan_request.rs @@ -7,16 +7,21 @@ //! Measured 2026-10-25 (us-east-1, each request twice): //! //! 1. the range constraints on `Limit` (at least 1), `Segment` (0 to 999999) -//! and `TotalSegments` (1 to 1000000), aggregated into one message in that -//! order with no value echoed: `2 validation errors detected: Value at -//! 'Limit' failed to satisfy constraint: Member must have value greater than -//! or equal to 1; Value at 'Segment' ...`. Each field is checked when -//! present, whether or not the other segment field is; +//! and `TotalSegments` (1 to 1000000), each checked when present, whether or +//! not the other segment field is. A `Limit` below 1 inside the int32 range +//! answers `1 validation error detected: Value at 'Limit' failed to satisfy +//! constraint: Member must have value greater than or equal to 1`; below +//! int32 the service saturates the value and answers the older form +//! `Value '-2147483648' at 'limit' ...`. The service aggregates several +//! range faults into one message; this module reports the first in the +//! order `Limit`, `Segment`, `TotalSegments`, with the `Segment` and +//! `TotalSegments` texts the previous release used; //! 2. the expression and non-expression parameter mix; //! 3. the `ReturnConsumedCapacity` enum; //! 4. every number in `ExpressionAttributeValues`, `NS` members and values //! nested in `L` and `M` included, whether a `FilterExpression` reads the -//! value, nothing reads it, or the request carries no expression at all; +//! value, nothing reads it, or the request carries no expression at all; a +//! Unicode decimal digit counts as the digit it stands for; //! 5. the `Select` enum. Both enums invalid answers the `ReturnConsumedCapacity` //! error alone, so the two are not aggregated. //! @@ -25,15 +30,18 @@ //! (Segment without TotalSegments and the reverse, Segment not below //! TotalSegments, the undefined placeholder, unused value, filter syntax, //! IndexName, ConsistentRead, Select with ProjectionExpression and -//! ExclusiveStartKey checks). +//! ExclusiveStartKey checks). A field of the wrong JSON type anywhere in the +//! body is reported ahead of all of them, as a `SerializationException`. use std::collections::HashMap; use extenddb_core::error::DynamoDbError; -use extenddb_core::types::AttributeValue; +use extenddb_core::types::{AttributeValue, ScanInput}; use serde_json::Value; -use crate::query_key_values::{non_empty, present, validate_expression_attribute_value_numbers}; +use crate::query_key_values::{ + non_empty, present, shape_fault_first, validate_expression_attribute_value_numbers, +}; /// The `Scan` checks that run on the raw request body, in the service's order: /// the `Limit`, `Segment` and `TotalSegments` ranges, the expression and @@ -41,13 +49,24 @@ use crate::query_key_values::{non_empty, present, validate_expression_attribute_ /// number in `ExpressionAttributeValues`, then the `Select` enum. /// /// The checks read the raw body, so a field that does not deserialize (an -/// invalid `Select`, for one) does not stop the ones before it. A field of the -/// wrong JSON shape is left to the deserializer, which runs next. +/// invalid `Select`, for one) does not stop the ones before it. When a check +/// fails, the body is deserialized as a [`ScanInput`] and a +/// `SerializationException` from that (a field of the wrong JSON shape +/// anywhere in the body) is the answer instead, as the service reports a shape +/// fault ahead of every validation; see [`shape_fault_first`]. A body that +/// passes every check is not deserialized here. /// /// # Errors /// -/// Returns `DynamoDbError::ValidationException` with the service's text. +/// Returns `DynamoDbError::ValidationException` with the service's text, or +/// `DynamoDbError::SerializationException` for a body of the wrong shape. pub fn validate_scan_request_body(body: &Value) -> Result<(), DynamoDbError> { + scan_request_checks(body).map_err(|check| shape_fault_first::(body, check)) +} + +/// The `Scan` checks in the service's order; see +/// [`validate_scan_request_body`]. +fn scan_request_checks(body: &Value) -> Result<(), DynamoDbError> { validate_ranges(body)?; extenddb_core::validation::validate_no_expression_param_mixing( @@ -95,38 +114,56 @@ pub fn validate_scan_request_body(body: &Value) -> Result<(), DynamoDbError> { ) } -/// The range constraints on `Limit`, `Segment` and `TotalSegments`, aggregated -/// in that order as the service reports them. The field name is capitalised -/// and the value is not echoed, unlike the `select` and `segment` style the -/// other `1 validation error detected` messages use. +/// The range constraints on `Limit`, `Segment` and `TotalSegments`, the first +/// fault in that order. +/// +/// `Limit` answers the service's text: inside the int32 range the field is +/// capitalised and the value is not echoed; below int32 the service saturates +/// the value and uses the older `Value '' at 'limit'` form (measured +/// 2026-10-25, `Limit: -2147483649`). `Segment` and `TotalSegments` keep the +/// texts of the previous release. fn validate_ranges(body: &Value) -> Result<(), DynamoDbError> { - let mut errors: Vec = Vec::new(); - let mut check = |field: &str, below: i64, above: i64| { - let Some(value) = body.get(field).and_then(Value::as_i64) else { - return; + let get = |field: &str| body.get(field).and_then(Value::as_i64); + if let Some(limit) = get("Limit") + && limit < 1 + { + let text = if limit >= i64::from(i32::MIN) { + "Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1".to_owned() + } else { + format!( + "Value '{}' at 'limit' failed to satisfy constraint: Member must have value greater than or equal to 1", + i32::MIN + ) }; - if value < below { - errors.push(format!( - "Value at '{field}' failed to satisfy constraint: Member must have value greater than or equal to {below}" - )); - } else if value > above { - errors.push(format!( - "Value at '{field}' failed to satisfy constraint: Member must have value less than or equal to {above}" + return Err(DynamoDbError::ValidationException(format!( + "1 validation error detected: {text}" + ))); + } + if let Some(segment) = get("Segment") { + if segment < 0 { + return Err(DynamoDbError::ValidationException(format!( + "1 validation error detected: Value '{segment}' at 'segment' failed to satisfy constraint: Member must have value greater than or equal to 0" + ))); + } + if segment > 999_999 { + return Err(DynamoDbError::ValidationException(format!( + "1 validation error detected: Value '{segment}' at 'segment' failed to satisfy constraint: Member must have value less than or equal to 999999" + ))); + } + } + if let Some(total) = get("TotalSegments") { + if total < 1 { + return Err(DynamoDbError::ValidationException( + "The parameter TotalSegments should be greater than or equal to 1".to_owned(), )); } - }; - check("Limit", 1, i64::MAX); - check("Segment", 0, 999_999); - check("TotalSegments", 1, 1_000_000); - if errors.is_empty() { - return Ok(()); + if total > 1_000_000 { + return Err(DynamoDbError::ValidationException(format!( + "1 validation error detected: Value '{total}' at 'totalSegments' failed to satisfy constraint: Member must have value less than or equal to 1000000" + ))); + } } - let count = errors.len(); - Err(DynamoDbError::ValidationException(format!( - "{count} validation error{} detected: {}", - if count == 1 { "" } else { "s" }, - errors.join("; ") - ))) + Ok(()) } #[cfg(test)] diff --git a/crates/engine/src/scan_request/tests.rs b/crates/engine/src/scan_request/tests.rs index 80af8ae17..2ae845559 100644 --- a/crates/engine/src/scan_request/tests.rs +++ b/crates/engine/src/scan_request/tests.rs @@ -1,8 +1,12 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! Every expected text below was measured against the service on 2026-10-25 -//! (us-east-1, each request twice). +//! The expected texts below were measured against the service on 2026-10-25 +//! (us-east-1, each request twice), except where a test says otherwise: the +//! `Segment` and `TotalSegments` range texts are the previous release's (the +//! service aggregates range faults into one message with a different form, a +//! separate issue), and the deserializer test pins this module's hand-off, not +//! a service text. use extenddb_core::error::DynamoDbError; use serde_json::{Value, json}; @@ -122,7 +126,7 @@ fn nested_numbers_and_the_other_number_faults_are_reported_with_the_service_text } #[test] -fn limit_segment_and_total_segments_ranges_come_first_and_aggregate() { +fn limit_segment_and_total_segments_ranges_come_first() { let base = bad_number(); assert_eq!( check(&with(base.clone(), "Limit", json!(0))).as_deref(), @@ -132,33 +136,45 @@ fn limit_segment_and_total_segments_ranges_come_first_and_aggregate() { check(&with(base.clone(), "Limit", json!(-1))).as_deref(), Some(&*format!("1 validation error detected: {LIMIT_RANGE}")) ); + // The int32 minimum itself gets the capitalised form; below it the service + // saturates the value and uses the older form (measured 2026-10-25). + assert_eq!( + check(&with(base.clone(), "Limit", json!(-2_147_483_648_i64))).as_deref(), + Some(&*format!("1 validation error detected: {LIMIT_RANGE}")) + ); + assert_eq!( + check(&with(base.clone(), "Limit", json!(-2_147_483_649_i64))).as_deref(), + Some( + "1 validation error detected: Value '-2147483648' at 'limit' failed to satisfy constraint: Member must have value greater than or equal to 1" + ) + ); // Each segment field is range checked when present, with or without the - // other one. + // other one (the service's position; the texts are the previous release's). for (field, value, text) in [ ( "Segment", -1, - "Value at 'Segment' failed to satisfy constraint: Member must have value greater than or equal to 0", + "1 validation error detected: Value '-1' at 'segment' failed to satisfy constraint: Member must have value greater than or equal to 0", ), ( "Segment", 1_000_000, - "Value at 'Segment' failed to satisfy constraint: Member must have value less than or equal to 999999", + "1 validation error detected: Value '1000000' at 'segment' failed to satisfy constraint: Member must have value less than or equal to 999999", ), ( "TotalSegments", 0, - "Value at 'TotalSegments' failed to satisfy constraint: Member must have value greater than or equal to 1", + "The parameter TotalSegments should be greater than or equal to 1", ), ( "TotalSegments", 1_000_001, - "Value at 'TotalSegments' failed to satisfy constraint: Member must have value less than or equal to 1000000", + "1 validation error detected: Value '1000001' at 'totalSegments' failed to satisfy constraint: Member must have value less than or equal to 1000000", ), ] { assert_eq!( check(&with(base.clone(), field, json!(value))).as_deref(), - Some(&*format!("1 validation error detected: {text}")), + Some(text), "{field} {value}" ); let partner = if field == "Segment" { @@ -173,12 +189,13 @@ fn limit_segment_and_total_segments_ranges_come_first_and_aggregate() { ); assert_eq!( check(&paired).as_deref(), - Some(&*format!("1 validation error detected: {text}")), + Some(text), "{field} {value} with {}", partner.0 ); } - // Limit, Segment, TotalSegments, in that order, one message. + // Several range faults: the first in the order Limit, Segment, + // TotalSegments is reported. let three = with( with( with(json!({"TableName": "t"}), "Limit", json!(0)), @@ -190,10 +207,14 @@ fn limit_segment_and_total_segments_ranges_come_first_and_aggregate() { ); assert_eq!( check(&three).as_deref(), - Some( - "3 validation errors detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1; Value at 'Segment' failed to satisfy constraint: Member must have value greater than or equal to 0; Value at 'TotalSegments' failed to satisfy constraint: Member must have value less than or equal to 1000000" - ) + Some(&*format!("1 validation error detected: {LIMIT_RANGE}")) + ); + let two = with( + with(json!({"TableName": "t"}), "Segment", json!(-1)), + "TotalSegments", + json!(1_000_001), ); + assert!(check(&two).is_some_and(|m| m.contains("at 'segment'"))); // Values at the bounds pass. assert!( check( @@ -207,7 +228,7 @@ fn limit_segment_and_total_segments_ranges_come_first_and_aggregate() { "ScanFilter", json!({"a": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]}}), ); - assert!(check(&mix).is_some_and(|m| m.contains("Value at 'Segment'"))); + assert!(check(&mix).is_some_and(|m| m.contains("at 'segment'"))); let rcc = with( with(base, "Limit", json!(0)), "ReturnConsumedCapacity", @@ -268,16 +289,17 @@ fn parameter_mix_beats_the_enum_and_the_numbers() { .as_deref(), Some(NUMERIC_BOB) ); - // An empty ScanFilter or AttributesToGet does not join the mix. - assert!( + // An empty ScanFilter alone is accepted, and an unused N bob beside it + // answers the number (measured 2026-10-25). + assert!(check(&json!({"TableName": "t", "ScanFilter": {}})).is_none()); + assert_eq!( check(&json!({ "TableName": "t", "ScanFilter": {}, - "AttributesToGet": [], - "FilterExpression": "a = :n", - "ExpressionAttributeValues": {":n": {"N": "1"}}, + "ExpressionAttributeValues": {":n": {"N": "bob"}}, })) - .is_none() + .as_deref(), + Some(NUMERIC_BOB) ); } @@ -318,12 +340,101 @@ fn enum_checks_sit_on_either_side_of_the_numbers() { } #[test] -fn values_that_do_not_deserialize_are_left_to_the_deserializer() { - // A string Limit and a malformed ExpressionAttributeValues are not range - // or number faults here; the typed deserializer reports them next. +fn a_shape_fault_anywhere_in_the_body_is_reported_first() { + // Measured 2026-10-25: a field of the wrong + // JSON type in another field answers SerializationException ahead of the + // range, mix and number checks. + let shape_faults = [ + json!({"TableName": "t", "Limit": 0, "ExpressionAttributeValues": "x"}), + json!({"TableName": "t", "Segment": -1, "TotalSegments": "2"}), + with(bad_number(), "ExpressionAttributeNames", json!("x")), + json!({"TableName": "t", "AttributesToGet": {"a": 1}, "ProjectionExpression": "a"}), + json!({"TableName": "t", "ScanFilter": [1], "FilterExpression": "a = :n", + "ExpressionAttributeValues": {":n": {"N": "1"}}}), + json!({"TableName": "t", "Limit": 0, "Select": 5}), + ]; + for body in shape_faults { + assert!( + matches!( + validate_scan_request_body(&body), + Err(DynamoDbError::SerializationException(_)) + ), + "{body}" + ); + } + // A string enum that is not a member is the checks' answer (not a shape + // fault), and a ValidationException the deserializer raises (an empty NS) + // does not preempt a check. + assert_eq!( + check(&with( + with(bad_number(), "Limit", json!(0)), + "Select", + json!("NOPE") + )) + .as_deref(), + Some(&*format!("1 validation error detected: {LIMIT_RANGE}")) + ); + assert_eq!( + check(&json!({ + "TableName": "t", "Limit": 0, + "ExpressionAttributeValues": {":s": {"NS": []}}, + })) + .as_deref(), + Some(&*format!("1 validation error detected: {LIMIT_RANGE}")) + ); + // A body that passes every check is left to the handler's deserializer: a + // string Limit and a malformed AttributeValue are not range or number + // faults here. assert!(check(&json!({"TableName": "t", "Limit": "0"})).is_none()); assert!( check(&json!({"TableName": "t", "ExpressionAttributeValues": {":n": {"X": "bob"}}})) .is_none() ); } + +#[test] +fn unicode_decimal_digits_pass_the_number_check() { + // Measured 2026-10-25: fullwidth and Arabic-Indic digits are read as digits, thirty nine + // Devanagari ones answer the 38 digit message, a superscript, a fraction, a + // fullwidth minus and a fullwidth full stop are refused with the value as + // sent. + for raw in ["\u{ff11}", "\u{661}", "\u{ff17}", "\u{ff11}e2"] { + assert!( + check(&with( + bad_number(), + "ExpressionAttributeValues", + json!({":n": {"N": raw}}) + )) + .is_none(), + "{raw:?}" + ); + } + assert!( + check(&json!({ + "TableName": "t", "FilterExpression": "a = :p", + "ExpressionAttributeValues": {":p": {"S": "x"}, ":s": {"NS": ["1", "\u{ff12}"]}}, + })) + .is_none() + ); + assert_eq!( + check(&with( + bad_number(), + "ExpressionAttributeValues", + json!({":n": {"N": "\u{967}".repeat(39)}}) + )) + .as_deref(), + Some("Attempting to store more than 38 significant digits in a Number") + ); + for raw in ["\u{b2}", "\u{bd}", "\u{ff0d}1", "1\u{ff0e}5"] { + assert_eq!( + check(&with( + bad_number(), + "ExpressionAttributeValues", + json!({":n": {"N": raw}}) + )) + .as_deref(), + Some(format!("The parameter cannot be converted to a numeric value: {raw}").as_str()), + "{raw:?}" + ); + } +} diff --git a/tests/test_query_scan.py b/tests/test_query_scan.py index 04019c990..44a82f4a2 100755 --- a/tests/test_query_scan.py +++ b/tests/test_query_scan.py @@ -614,17 +614,17 @@ def test_scan_segment_at_max_accepted(self, dynamodb_client, scan_table): def test_scan_segment_one_over_max_rejected( self, dynamodb_client_no_validation, scan_table ): - """Segment > 999999 returns the range ValidationException (measured 2026-10-25).""" + """Segment > 999999 returns the Coral-format ValidationException.""" with pytest.raises(ClientError) as exc_info: dynamodb_client_no_validation.scan( TableName=scan_table, Segment=1_000_000, TotalSegments=1_000_000 ) err = exc_info.value.response["Error"] assert err["Code"] == "ValidationException" - assert err["Message"] == ( - "1 validation error detected: Value at 'Segment' failed to satisfy " - "constraint: Member must have value less than or equal to 999999" - ) + msg = err["Message"] + assert "1 validation error detected" in msg + assert "'1000000' at 'segment'" in msg + assert "Member must have value less than or equal to 999999" in msg def test_scan_total_segments_at_max_accepted(self, dynamodb_client, scan_table): """TotalSegments=1000000 with Segment=0 is at the documented bound.""" @@ -635,17 +635,17 @@ def test_scan_total_segments_at_max_accepted(self, dynamodb_client, scan_table): def test_scan_total_segments_one_over_max_rejected( self, dynamodb_client_no_validation, scan_table ): - """TotalSegments > 1000000 returns the range ValidationException (measured 2026-10-25).""" + """TotalSegments > 1000000 returns the Coral-format ValidationException.""" with pytest.raises(ClientError) as exc_info: dynamodb_client_no_validation.scan( TableName=scan_table, Segment=0, TotalSegments=1_000_001 ) err = exc_info.value.response["Error"] assert err["Code"] == "ValidationException" - assert err["Message"] == ( - "1 validation error detected: Value at 'TotalSegments' failed to satisfy " - "constraint: Member must have value less than or equal to 1000000" - ) + msg = err["Message"] + assert "1 validation error detected" in msg + assert "'1000001' at 'totalSegments'" in msg + assert "Member must have value less than or equal to 1000000" in msg def test_scan_all_projected_attributes_without_index_rejected( self, dynamodb_client, scan_table diff --git a/tests/test_scan_number_values.py b/tests/test_scan_number_values.py index df354ef4d..89ab066aa 100644 --- a/tests/test_scan_number_values.py +++ b/tests/test_scan_number_values.py @@ -8,13 +8,18 @@ significant digits or an empty ``N`` is refused with ``ValidationException`` before any row is read, whether a ``FilterExpression`` reads the value, nothing reads it, or the request carries no expression at all. Every expected -answer below was measured against the service on 2026-10-25 (09:23 to 09:28 -UTC) with each request sent twice. +answer below was measured against the service on 2026-10-25 (09:23 to 09:28, +10:38, 10:55 and 11:31 UTC) with each request sent twice. A Unicode decimal +digit in an ``N`` value counts as the digit it stands for; a field of the +wrong JSON type anywhere in the body answers ``SerializationException`` ahead +of every check. The rows also pin where the check falls against the other early Scan checks: -after the ``Limit``, ``Segment`` and ``TotalSegments`` range constraints (one -aggregated message, ``Value at 'Limit'`` with no value echoed), the expression -and non-expression parameter mix and the ``ReturnConsumedCapacity`` enum; and +after the ``Limit``, ``Segment`` and ``TotalSegments`` range constraints +(``Value at 'Limit'`` with no value echoed for a ``Limit`` inside the int32 +range; the ``Segment`` and ``TotalSegments`` rows assert the position of the +check, not its text), the expression and non-expression parameter mix and the +``ReturnConsumedCapacity`` enum; and before the ``Select`` enum, the Segment pairing checks, the table lookup, the IndexName, ConsistentRead, Select with ProjectionExpression, ExclusiveStartKey, undefined placeholder, unused value and filter syntax @@ -194,44 +199,45 @@ def test_limit_range(self, dynamodb_client_no_validation, table, limit): dynamodb_client_no_validation, TableName=table, Limit=limit, **NB_FILTER, ) == ("ValidationException", "1 validation error detected: " + LIMIT_RANGE) - @pytest.mark.parametrize("kwargs, text", [ - pytest.param({"Segment": 0, "TotalSegments": 0}, - "Value at 'TotalSegments' failed to satisfy constraint: " - "Member must have value greater than or equal to 1", id="TotalSegments-0"), - pytest.param({"Segment": 0, "TotalSegments": 1_000_001}, - "Value at 'TotalSegments' failed to satisfy constraint: " - "Member must have value less than or equal to 1000000", id="TotalSegments-1000001"), - pytest.param({"Segment": -1, "TotalSegments": 2}, - "Value at 'Segment' failed to satisfy constraint: " - "Member must have value greater than or equal to 0", id="Segment-minus-1"), - pytest.param({"Segment": 1_000_000, "TotalSegments": 1_000_000}, - "Value at 'Segment' failed to satisfy constraint: " - "Member must have value less than or equal to 999999", id="Segment-1000000"), - pytest.param({"Segment": -1}, - "Value at 'Segment' failed to satisfy constraint: " - "Member must have value greater than or equal to 0", id="Segment-minus-1-alone"), - pytest.param({"TotalSegments": 0}, - "Value at 'TotalSegments' failed to satisfy constraint: " - "Member must have value greater than or equal to 1", id="TotalSegments-0-alone"), + @pytest.mark.parametrize("kwargs, field", [ + pytest.param({"Segment": 0, "TotalSegments": 0}, "totalsegments", id="TotalSegments-0"), + pytest.param({"Segment": 0, "TotalSegments": 1_000_001}, "totalsegments", id="TotalSegments-1000001"), + pytest.param({"Segment": -1, "TotalSegments": 2}, "segment", id="Segment-minus-1"), + pytest.param({"Segment": 1_000_000, "TotalSegments": 1_000_000}, "segment", id="Segment-1000000"), + pytest.param({"Segment": -1}, "segment", id="Segment-minus-1-alone"), + pytest.param({"TotalSegments": 0}, "totalsegments", id="TotalSegments-0-alone"), ]) - def test_segment_ranges(self, dynamodb_client_no_validation, table, kwargs, text): - assert _scan_error( - dynamodb_client_no_validation, TableName=table, **kwargs, **NB_FILTER, - ) == ("ValidationException", "1 validation error detected: " + text) + def test_segment_ranges(self, dynamodb_client_no_validation, table, kwargs, field): + # The range fault names the field and is reported ahead of the number; + # the text itself differs between the service and extenddb. + code, msg = _scan_error(dynamodb_client_no_validation, TableName=table, **kwargs, **NB_FILTER) + assert code == "ValidationException" + assert field in msg.lower().replace("'", "") + assert "bob" not in msg - def test_ranges_aggregate_limit_then_segment_then_total_segments( + def test_limit_range_is_reported_ahead_of_the_segment_ranges_and_the_number( self, dynamodb_client_no_validation, table, ): - assert _scan_error( + code, msg = _scan_error( dynamodb_client_no_validation, TableName=table, - Limit=0, Segment=-1, TotalSegments=1_000_001, + Limit=0, Segment=-1, TotalSegments=1_000_001, **NB_FILTER, + ) + assert code == "ValidationException" + assert msg.endswith(LIMIT_RANGE) or msg.startswith("3 validation errors detected: " + LIMIT_RANGE) + assert "bob" not in msg + + def test_limit_below_int32_answers_the_saturated_value(self, dynamodb_client_no_validation, table): + # Measured 2026-10-25 10:38 and 10:55 UTC: outside int32 the service + # echoes the saturated value in the older form, and beats the number. + assert _scan_error( + dynamodb_client_no_validation, TableName=table, Limit=-2_147_483_649, **NB_FILTER, ) == ("ValidationException", ( - "3 validation errors detected: " + LIMIT_RANGE + "; " - "Value at 'Segment' failed to satisfy constraint: " - "Member must have value greater than or equal to 0; " - "Value at 'TotalSegments' failed to satisfy constraint: " - "Member must have value less than or equal to 1000000" + "1 validation error detected: Value '-2147483648' at 'limit' failed to " + "satisfy constraint: Member must have value greater than or equal to 1" )) + assert _scan_error( + dynamodb_client_no_validation, TableName=table, Limit=-2_147_483_648, **NB_FILTER, + ) == ("ValidationException", "1 validation error detected: " + LIMIT_RANGE) def test_limit_range_beats_the_missing_table(self, dynamodb_client_no_validation): assert _scan_error( @@ -328,3 +334,99 @@ def test_filter_syntax_error(self, dynamodb_client, table): dynamodb_client, TableName=table, FilterExpression="a = = :n", ExpressionAttributeValues={":n": NB}, ) == ("ValidationException", NUMERIC + "bob") + + +FW_ONE = "\uff11" # fullwidth digit one +FW_SEVEN = "\uff17" # fullwidth digit seven +AR_ONE = "\u0661" # Arabic-Indic digit one +DEVA_ONE = "\u0967" # Devanagari digit one +# Superscript two, vulgar half, fullwidth minus then 1, 1 fullwidth full stop 5. +NOT_DIGITS = ["\u00b2", "\u00bd", "\uff0d1", "1\uff0e5"] + + +class TestUnicodeDecimalDigits: + """A Unicode decimal digit (general category Nd) in an N value passes the + number check as the digit it stands for; other characters are refused with + the value echoed as sent (measured 2026-10-25 10:38 and 10:55 UTC). The + service also reads such a value as the digit when it compares; this change + does not, so only the acceptance is asserted.""" + + @pytest.mark.parametrize("raw", [FW_ONE, AR_ONE], ids=["fullwidth-1", "arabic-indic-1"]) + def test_digit_in_the_filter_is_accepted(self, dynamodb_client, table, raw): + # The request is accepted and every row is scanned. + resp = dynamodb_client.scan( + TableName=table, FilterExpression="a = :n", + ExpressionAttributeValues={":n": {"N": raw}}) + assert resp["ScannedCount"] == 2 + + @pytest.mark.parametrize("raw", [FW_SEVEN, FW_ONE + "e2"], ids=["fullwidth-7", "fullwidth-1e2"]) + def test_digit_that_matches_no_row(self, dynamodb_client, table, raw): + # Accepted; no stored item has a equal to 7 or 100. + resp = dynamodb_client.scan( + TableName=table, FilterExpression="a = :n", + ExpressionAttributeValues={":n": {"N": raw}}) + assert (resp["Count"], resp["ScannedCount"]) == (0, 2) + + def test_digit_in_a_number_set_passes_the_check(self, dynamodb_client, table): + assert _scan_error( + dynamodb_client, TableName=table, FilterExpression="a = :p", + ExpressionAttributeValues={":p": SX, ":s": {"NS": ["1", "\uff12"]}}, + ) == ("ValidationException", + "Value provided in ExpressionAttributeValues unused in expressions: keys: {:s}") + + def test_39_devanagari_digits_are_39_digits(self, dynamodb_client, table): + assert _scan_error( + dynamodb_client, TableName=table, FilterExpression="a = :n", + ExpressionAttributeValues={":n": {"N": DEVA_ONE * 39}}, + ) == ("ValidationException", TOO_MANY_DIGITS) + + @pytest.mark.parametrize("raw", NOT_DIGITS, ids=["superscript", "fraction", "fullwidth-minus", "fullwidth-point"]) + def test_characters_that_are_not_digits_are_refused(self, dynamodb_client, table, raw): + assert _scan_error( + dynamodb_client, TableName=table, FilterExpression="a = :n", + ExpressionAttributeValues={":n": {"N": raw}}, + ) == ("ValidationException", NUMERIC + raw) + + +def _raw_scan(client, body: dict): + """POST ``body`` as the Scan JSON exactly as written, signed with the + client's credentials, so a field of the wrong JSON type reaches the server + (boto3 would refuse or reshape it).""" + import json + + from botocore.awsrequest import AWSRequest + + req = AWSRequest(method="POST", url=client.meta.endpoint_url, data=json.dumps(body), + headers={"Content-Type": "application/x-amz-json-1.0", + "X-Amz-Target": "DynamoDB_20120810.Scan"}) + client._request_signer.sign("Scan", req) + resp = client._endpoint.http_session.send(req.prepare()) + return resp.status_code, json.loads(resp.content.decode("utf-8", "replace") or "{}") + + +SHAPE_FAULTS = [ + ("Limit 0 with ExpressionAttributeValues string", {"Limit": 0, "ExpressionAttributeValues": "x"}), + ("Segment -1 with TotalSegments string", {"Segment": -1, "TotalSegments": "2"}), + ("ExpressionAttributeNames string with N bob", {"ExpressionAttributeNames": "x", **NB_FILTER}), + ("AttributesToGet object with ProjectionExpression", + {"AttributesToGet": {"a": 1}, "ProjectionExpression": "a"}), +] + + +class TestShapeFaultsAreReportedFirst: + """A field of the wrong JSON type anywhere in the body answers + SerializationException ahead of the range, parameter mix and number checks + (measured 2026-10-25 10:38 UTC). The message texts differ between the + service and extenddb, so only the error type is asserted.""" + + @pytest.mark.parametrize("row,body", SHAPE_FAULTS, ids=[r[0] for r in SHAPE_FAULTS]) + def test_rows(self, dynamodb_client, table, row, body): + status, payload = _raw_scan(dynamodb_client, {"TableName": table, **body}) + assert status == 400 + assert payload.get("__type", "").endswith("SerializationException"), payload + + def test_control_without_a_shape_fault_answers_the_check(self, dynamodb_client, table): + status, payload = _raw_scan(dynamodb_client, {"TableName": table, "Limit": 0, **NB_FILTER}) + assert status == 400 + assert payload.get("__type", "").endswith("ValidationException") + assert payload.get("message", payload.get("Message")) == "1 validation error detected: " + LIMIT_RANGE From 44b7b18028b250d27169d4395200de64d5006b2b Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:29:33 +0000 Subject: [PATCH 11/30] test(query): pass the RANGE attributes to resolve_multipart Main changes resolve_multipart to take the HASH and the RANGE attribute names (#429). The multi-attribute HASH test now gives r as the RANGE attribute, as its attribute definitions do. --- crates/engine/src/query_key_values/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/query_key_values/tests.rs b/crates/engine/src/query_key_values/tests.rs index f1ba2d3e6..68c353943 100644 --- a/crates/engine/src/query_key_values/tests.rs +++ b/crates/engine/src/query_key_values/tests.rs @@ -198,7 +198,7 @@ fn multipart_hash_conditions_are_checked() { ]); let mut kc = parse("g1 = :a AND g2 = :b AND r > :c"); let names = HashMap::new(); - kc.resolve_multipart(&["g1", "g2"], &names) + kc.resolve_multipart(&["g1", "g2"], &["r"], &names) .expect("resolve"); assert_eq!(kc.extra_pk_conditions.len(), 1); let m = maps(&[], &[("a", s("x")), ("b", s("1")), ("c", s("r"))]); From 0b8e97dbc94459d5e142dfc5b1a20f25b965fa01 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:56:16 +0000 Subject: [PATCH 12/30] fix(query): order the key value type check and the begins_with refusal as the service does On a single-attribute key schema, the later check of this branch now reports a wrong type in a key condition expression, as the service does. The early check from main still runs there for legacy KeyConditions, which the later check skips. The begins_with refusal now reads the type of the value instead of the type of the sort key. --- crates/engine/src/query.rs | 86 +++++++++------ crates/engine/src/query_begins_with_tests.rs | 107 +++++++++++++++++++ tests/test_query_key_value_types.py | 35 +++++- 3 files changed, 189 insertions(+), 39 deletions(-) create mode 100644 crates/engine/src/query_begins_with_tests.rs diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 503c8e993..a67ed5f13 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -226,11 +226,9 @@ pub async fn handle_query( // HASH or several RANGE attributes) every clause is assigned by name, every // HASH attribute needs an equality and the RANGE conditions must cover a // leading run of the RANGE attributes with equalities before the last one. - // A wrong-typed value is reported where the service reports it: after those - // structural rules and before the non-key rule on a multi-attribute key - // schema, and ahead of the missing-key check on a single-attribute one - // (measured 2026-10-21: `pk = :n` on an S key with a second clause on a - // non-key attribute reports the type, not the missing key). + // On a multi-attribute key schema the service reports a wrong-typed value + // after those structural rules and before the non-key rule, so the + // classifier runs the type check there. // // On a multi-attribute key schema the classifier refuses a clause on an // attribute outside the key schema (`Query condition missed key schema @@ -240,11 +238,17 @@ pub async fn handle_query( // 2026-10-30 on a GSI with HASH `GSI2PK` and RANGE `GSI2SK`: `GSI2PK = :h // AND PK = :k` answers `Query condition missed key schema element: GSI2SK` // whether `:k` has the table's type for `PK` or not, so the service's type - // check does not see an attribute outside the queried key schema. The - // single-attribute path has no non-key rule yet: a clause on another - // attribute reaches storage, which applies it to the first RANGE - // attribute, so it keeps checking against the table's definitions, which - // refuse a value of the wrong type before storage does. + // check does not see an attribute outside the queried key schema. + // + // On a single-attribute key schema the service reports a wrong-typed value + // after the missing-key, filter, projection, unused-value and Select + // checks (measured 2026-11-06). The classifier does not run the type check + // there, and `validate_key_condition_types` reports the value below. `pk = + // :n` on an S key with a second clause on a non-key attribute reports the + // type, not a missing key schema element (measured 2026-10-21). This path + // has no non-key rule, so that query also reaches the check below. + // Legacy `KeyConditions` do not go through the check below, so the + // classifier still checks their values, against the table's definitions. let multipart = extenddb_core::types::is_multipart_key_schema(&query_key_info.key_schema); let key_schema_definitions: Vec = query_key_info .attribute_definitions @@ -262,16 +266,19 @@ pub async fn handle_query( } else { &query_key_info.attribute_definitions }; + let check_types_here = multipart || legacy_kc_maps.is_some(); key_condition.resolve_key_schema_with( &query_key_info.key_schema, &effective_maps.names, - |path, value| check_key_value_type(path, value, type_definitions, effective_maps), - )?; - refuse_begins_with_on_number( - &key_condition, - &query_key_info.attribute_definitions, - effective_maps, + |path, value| { + if check_types_here { + check_key_value_type(path, value, type_definitions, effective_maps) + } else { + Ok(()) + } + }, )?; + refuse_begins_with_on_number(&key_condition, effective_maps)?; // On a single-attribute key schema, validate that the partition key is // actually referenced in the condition. The classifier has already required // an equality on every HASH attribute of a multi-attribute one. @@ -633,30 +640,35 @@ fn check_key_value_type( } } -/// Refuse `begins_with` on a number key attribute (measured 2026-10-21: -/// `Invalid KeyConditionExpression: Incorrect operand type for operator or -/// function; operator or function: begins_with, operand type: N`). +/// Refuse a `begins_with` key condition whose value is not an S or a B, with +/// the value's type in the text: `Invalid KeyConditionExpression: Incorrect +/// operand type for operator or function; operator or function: begins_with, +/// operand type: N`. +/// +/// Measured on the service 2026-11-06: the value's type decides the refusal, +/// not the sort key's type. An N or a BOOL value is refused on an S, an N and +/// a B sort key alike. An S or a B value on a sort key of another type gets +/// the type mismatch from the type check instead. The refusal comes before the +/// unused-value, projection overlap and Select checks and before a wrong-typed +/// partition key value. A placeholder that has no value passes here, and the +/// existing checks report it. fn refuse_begins_with_on_number( key_condition: &extenddb_core::expression::KeyCondition, - attribute_definitions: &[extenddb_core::types::AttributeDefinition], maps: &ExpressionMaps, ) -> Result<(), DynamoDbError> { - use extenddb_core::expression::SortKeyCondition; - use extenddb_core::types::ScalarAttributeType; + use extenddb_core::expression::{Expr, SortKeyCondition}; - if let Some(SortKeyCondition::BeginsWith { path, .. }) = &key_condition.sk_condition - && let Some(attr) = resolve_path_attr_name(path, &maps.names) - && attribute_definitions - .iter() - .any(|d| d.attribute_name == attr && d.attribute_type == ScalarAttributeType::N) - { - return Err(DynamoDbError::ValidationException( - "Invalid KeyConditionExpression: Incorrect operand type for operator or function; \ - operator or function: begins_with, operand type: N" - .to_owned(), - )); - } - Ok(()) + let Some(SortKeyCondition::BeginsWith { path, prefix }) = &key_condition.sk_condition else { + return Ok(()); + }; + // The operand check of the filter, applied to the key condition's call. + let call = Expr::Function { + name: "begins_with".to_owned(), + args: vec![Expr::Path(path.clone()), prefix.clone()], + }; + extenddb_core::expression::validate_begins_with_operands(&call, maps).map_err(|e| { + crate::expression_helpers::prefix_expression_error(e, ExpressionKind::KeyCondition) + }) } /// Validate that all `#name` references in an expression AST are defined. @@ -760,3 +772,7 @@ mod empty_key_condition_tests { assert!(reject_empty_key_condition_expression(Some("pk = :v")).is_ok()); } } + +#[cfg(test)] +#[path = "query_begins_with_tests.rs"] +mod begins_with_tests; diff --git a/crates/engine/src/query_begins_with_tests.rs b/crates/engine/src/query_begins_with_tests.rs new file mode 100644 index 000000000..0a97577bd --- /dev/null +++ b/crates/engine/src/query_begins_with_tests.rs @@ -0,0 +1,107 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Tests for [`refuse_begins_with_on_number`]: the type of the `begins_with` +//! value decides the refusal, not the sort key's type (measured 2026-11-06). + +use std::collections::HashMap; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::expression::{ + ExpressionMaps, KeyCondition, parse_key_condition, tokenize_with_limit, +}; +use extenddb_core::types::{AttributeDefinition, AttributeValue, ScalarAttributeType}; + +use super::refuse_begins_with_on_number; +use crate::query_key_values::{KEY_CONDITION_TYPE_MISMATCH, validate_key_condition_types}; + +const OPERAND_TYPE: &str = "Invalid KeyConditionExpression: Incorrect operand type for operator or \ + function; operator or function: begins_with, operand type: "; + +const SORT_KEY_TYPES: [ScalarAttributeType; 3] = [ + ScalarAttributeType::S, + ScalarAttributeType::N, + ScalarAttributeType::B, +]; + +fn parse(kce: &str) -> KeyCondition { + let tokens = tokenize_with_limit(kce, 1000).expect("tokenize"); + parse_key_condition(&tokens).expect("parse") +} + +fn values(pairs: Vec<(&str, AttributeValue)>) -> ExpressionMaps { + ExpressionMaps::new( + HashMap::new(), + pairs.into_iter().map(|(k, v)| (k.to_owned(), v)).collect(), + ) +} + +fn message(result: Result<(), DynamoDbError>) -> Option { + match result { + Ok(()) => None, + Err(DynamoDbError::ValidationException(msg)) => Some(msg), + Err(other) => panic!("unexpected error {other:?}"), + } +} + +/// The answer to `pk = :u AND begins_with(sk, :b)` with an S partition key and +/// a sort key of `sk_type`: the refusal, then the type check that +/// `handle_query` runs later. `None` when both pass. +fn answer(sk_type: ScalarAttributeType, value: AttributeValue) -> Option { + let key_condition = parse("pk = :u AND begins_with(sk, :b)"); + let maps = values(vec![("u", AttributeValue::S("x".to_owned())), ("b", value)]); + let definitions = [ + AttributeDefinition { + attribute_name: "pk".to_owned(), + attribute_type: ScalarAttributeType::S, + }, + AttributeDefinition { + attribute_name: "sk".to_owned(), + attribute_type: sk_type, + }, + ]; + message( + refuse_begins_with_on_number(&key_condition, &maps) + .and_then(|()| validate_key_condition_types(&key_condition, &maps, &definitions)), + ) +} + +#[test] +fn number_and_bool_values_are_refused_with_their_type_on_every_sort_key_type() { + for sk_type in SORT_KEY_TYPES { + for (value, type_code) in [ + (AttributeValue::N("1".to_owned()), "N"), + (AttributeValue::Bool(true), "BOOL"), + ] { + assert_eq!( + answer(sk_type, value), + Some(format!("{OPERAND_TYPE}{type_code}")), + "{sk_type:?} sort key" + ); + } + } +} + +#[test] +fn string_and_binary_values_pass_to_the_type_check_on_every_sort_key_type() { + for sk_type in SORT_KEY_TYPES { + for (value, value_type) in [ + (AttributeValue::S("1".to_owned()), ScalarAttributeType::S), + (AttributeValue::B(vec![1]), ScalarAttributeType::B), + ] { + let expected = (value_type != sk_type).then(|| KEY_CONDITION_TYPE_MISMATCH.to_owned()); + assert_eq!( + answer(sk_type, value), + expected, + "{value_type:?} value on {sk_type:?} sort key" + ); + } + } +} + +#[test] +fn a_placeholder_without_a_value_passes() { + let key_condition = parse("pk = :u AND begins_with(sk, :zz)"); + let maps = values(vec![("u", AttributeValue::S("x".to_owned()))]); + assert!(refuse_begins_with_on_number(&key_condition, &maps).is_ok()); +} diff --git a/tests/test_query_key_value_types.py b/tests/test_query_key_value_types.py index c336b6acc..16f2d1546 100644 --- a/tests/test_query_key_value_types.py +++ b/tests/test_query_key_value_types.py @@ -9,10 +9,11 @@ attribute's ``AttributeDefinitions`` type (``One or more parameter values were invalid: Condition parameter type does not match schema type``). Every expected answer below was measured against the service on 2026-10-24 (15:10, 21:00, -21:06 and 23:42 UTC) and 2026-10-25 (11:31 UTC) on tables with S/S, S/N and -B/B keys, a GSI and an LSI. A Unicode decimal digit in an N value counts as -the digit it stands for; a field of the wrong JSON type anywhere in the body -answers SerializationException ahead of every check. +21:06 and 23:42 UTC), 2026-10-25 (11:31 UTC) and 2026-11-06 (the begins_with +rows after b20) on tables with S/S, S/N and B/B keys, a GSI and an LSI. A +Unicode decimal digit in an N value counts as the digit it stands for; a field +of the wrong JSON type anywhere in the body answers SerializationException +ahead of every check. The rows also pin where the two checks fall against the other Query checks: the numeric check after Limit, the expression parameter mix check and the ReturnConsumedCapacity enum, and before the Select enum and the table lookup; @@ -185,6 +186,10 @@ def bb_table(dynamodb_client): "Invalid FilterExpression: Incorrect operand type for operator or function; " "operator or function: begins_with, operand type: N" ) +BEGINS_WITH_KCE = ( + "Invalid KeyConditionExpression: Incorrect operand type for operator or function; " + "operator or function: begins_with, operand type: " +) PROJECTION_OVERLAP = ( "Invalid ProjectionExpression: Two document paths overlap with each other; " "must remove or rewrite one of these paths; path one: [a], path two: [a, b]" @@ -284,6 +289,28 @@ def kce(expr, values, **extra): V, TYPE_MISMATCH), ("b20 N sk begins_with S", "ns", kce("pk = :u AND begins_with(sk, :b)", {":u": SX, ":b": {"S": "1"}}), V, TYPE_MISMATCH), + # begins_with is refused by the type of its value, on every sort key type, + # ahead of the unused value check; an S or B value on a sort key of another + # type gets the type mismatch (measured on Amazon DynamoDB in us-east-1 on + # 6 Nov 2026). + ("q1 S sk begins_with N", "ss", + kce("pk = :u AND begins_with(sk, :n)", {":u": SX, ":n": {"N": "1"}}), V, BEGINS_WITH_KCE + "N"), + ("q2 N sk begins_with B", "ns", + kce("pk = :u AND begins_with(sk, :b)", {":u": SX, ":b": B_BOB}), V, TYPE_MISMATCH), + ("q3 B sk begins_with N", "bb", + kce("bpk = :u AND begins_with(bsk, :n)", {":u": B_BOB, ":n": {"N": "1"}}), + V, BEGINS_WITH_KCE + "N"), + ("q4 N sk begins_with BOOL", "ns", + kce("pk = :u AND begins_with(sk, :t)", {":u": SX, ":t": {"BOOL": True}}), + V, BEGINS_WITH_KCE + "BOOL"), + ("q5 S sk begins_with N with unused value", "ss", + kce("pk = :u AND begins_with(sk, :n)", {":u": SX, ":n": {"N": "1"}, ":x": SX}), + V, BEGINS_WITH_KCE + "N"), + ("p2 N sk begins_with N", "ns", + kce("pk = :u AND begins_with(sk, :n)", {":u": SX, ":n": {"N": "1"}}), V, BEGINS_WITH_KCE + "N"), + ("p4 N sk begins_with N with unused value", "ns", + kce("pk = :u AND begins_with(sk, :n)", {":u": SX, ":n": {"N": "1"}, ":x": SX}), + V, BEGINS_WITH_KCE + "N"), ("b22 pk = N 5 AND N sk = S 5", "ns", kce("pk = :u AND sk = :s", {":u": N5, ":s": {"S": "5"}}), V, TYPE_MISMATCH), ("b23 N sk = N bob", "ns", kce("pk = :u AND sk = :s", {":u": SX, ":s": NB}), V, NUMERIC + "bob"), From 7b0924f5369dd816215358a5626a5aebd35ed797 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:54:23 +0000 Subject: [PATCH 13/30] test(query): pin begins_with on a non-key attribute and correct the order comments Two new rows send begins_with with an N value on an attribute that is not in the key schema. One row uses a table with an S sort key and the other uses a table with an N sort key. The service refuses both requests with the begins_with operand type message. The comments in handle_query now say that the classifier checks the values of legacy KeyConditions. They also say which attribute definitions it uses for each kind of key schema. The doc of resolve_key_schema_with now says where the service reports a wrong type on a single-attribute key schema (measured 2026-11-06). --- crates/core/src/expression/key_condition.rs | 9 ++++++--- crates/engine/src/query.rs | 8 +++++--- tests/test_query_key_value_types.py | 12 ++++++++---- 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index edaa1f8e5..4d461356e 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -381,9 +381,12 @@ impl KeyCondition { /// [`Self::resolve_multipart_with`], which classifies every clause by name, /// applies the service's rules for such a schema and calls `value_check` /// where the service reports a value of the wrong type. On any other key - /// schema `value_check` runs on every clause first, which is where the - /// service reports it for such a schema (measured 2026-10-21), and then - /// [`Self::resolve_pk_sk`] picks the partition key clause. + /// schema `value_check` runs on every clause first, and then + /// [`Self::resolve_pk_sk`] picks the partition key clause. On a + /// single-attribute key schema the service reports a value of the wrong + /// type after the missing-key, filter, projection, unused-value and Select + /// checks (measured 2026-11-06), so the engine passes a `value_check` that + /// checks nothing there unless the request uses legacy `KeyConditions`. /// /// The engine reads a `Query` key condition through this, and so does /// authorization when it finds the partition key value for diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index a67ed5f13..5dd85edfe 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -248,7 +248,9 @@ pub async fn handle_query( // type, not a missing key schema element (measured 2026-10-21). This path // has no non-key rule, so that query also reaches the check below. // Legacy `KeyConditions` do not go through the check below, so the - // classifier still checks their values, against the table's definitions. + // classifier still checks their values: against the key schema's + // definitions on a multi-attribute key schema and against the table's on a + // single-attribute one. let multipart = extenddb_core::types::is_multipart_key_schema(&query_key_info.key_schema); let key_schema_definitions: Vec = query_key_info .attribute_definitions @@ -447,8 +449,8 @@ pub async fn handle_query( // A key condition value whose type is not the key attribute's type is // refused after the key schema, filter, projection, unused value and // Select checks and before the ExclusiveStartKey check (measured - // 2026-10-24). The legacy KeyConditions path makes its own checks when it - // desugars. + // 2026-10-24). The classifier above checked the values of legacy + // `KeyConditions`. if legacy_kc_maps.is_none() { crate::query_key_values::validate_key_condition_types( &key_condition, diff --git a/tests/test_query_key_value_types.py b/tests/test_query_key_value_types.py index 16f2d1546..6db90cbd3 100644 --- a/tests/test_query_key_value_types.py +++ b/tests/test_query_key_value_types.py @@ -289,10 +289,10 @@ def kce(expr, values, **extra): V, TYPE_MISMATCH), ("b20 N sk begins_with S", "ns", kce("pk = :u AND begins_with(sk, :b)", {":u": SX, ":b": {"S": "1"}}), V, TYPE_MISMATCH), - # begins_with is refused by the type of its value, on every sort key type, - # ahead of the unused value check; an S or B value on a sort key of another - # type gets the type mismatch (measured on Amazon DynamoDB in us-east-1 on - # 6 Nov 2026). + # begins_with is refused by the type of its value, on every sort key type + # and on an attribute outside the key schema, ahead of the unused value + # check; an S or B value on a sort key of another type gets the type + # mismatch (measured on Amazon DynamoDB in us-east-1 on 6 Nov 2026). ("q1 S sk begins_with N", "ss", kce("pk = :u AND begins_with(sk, :n)", {":u": SX, ":n": {"N": "1"}}), V, BEGINS_WITH_KCE + "N"), ("q2 N sk begins_with B", "ns", @@ -311,6 +311,10 @@ def kce(expr, values, **extra): ("p4 N sk begins_with N with unused value", "ns", kce("pk = :u AND begins_with(sk, :n)", {":u": SX, ":n": {"N": "1"}, ":x": SX}), V, BEGINS_WITH_KCE + "N"), + ("m2 non-key begins_with N, S sk", "ss", + kce("pk = :u AND begins_with(zz, :n)", {":u": SX, ":n": {"N": "1"}}), V, BEGINS_WITH_KCE + "N"), + ("m3 non-key begins_with N, N sk", "ns", + kce("pk = :u AND begins_with(zz, :n)", {":u": SX, ":n": {"N": "1"}}), V, BEGINS_WITH_KCE + "N"), ("b22 pk = N 5 AND N sk = S 5", "ns", kce("pk = :u AND sk = :s", {":u": N5, ":s": {"S": "5"}}), V, TYPE_MISMATCH), ("b23 N sk = N bob", "ns", kce("pk = :u AND sk = :s", {":u": SX, ":s": NB}), V, NUMERIC + "bob"), From cb2df0b1ee41bfd8bc00453f44ed35fdcad35905 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:00:29 +0000 Subject: [PATCH 14/30] fix(query): check each value on its own and answer in the service's order - Report an invalid ReturnConsumedCapacity ahead of the expression and non-expression parameter mix. - Check the numbers in each ExpressionAttributeValues entry on its own. A value that does not deserialize no longer turns the check off for the others, in the handler and before authorization. - Beside a value the service cannot read as one type, answer in the service's order. Such a value is a null, or holds no known type descriptor, more than one, or an unknown one beside a known one. Select, ReturnConsumedCapacity and Limit come together, with the Limit text that names the value. The parameter mix comes next, then the first value with a fault and its placeholder. A value the service cannot read comes ahead of a number fault in another value. - In the shape fault check, replace only the parts of such a value that the service cannot read. A field of the wrong JSON type in the rest of the value still answers SerializationException. - Count a decimal digit only below U+10000, as the service does. The check refuses a digit from U+104A0 up. - Echo a refused number with each decimal digit folded to ASCII. - Add rows for legacy KeyConditions and for a multi-attribute key schema beside a non-key clause. Skip the second type check where the classifier checked the values. - Delete the LeadingKeys test tables when a call raises. - Give the checks for values the service cannot read their own module and tests. Move the request order unit tests and the shape fault and LeadingKeys Python tests to files of their own. --- crates/engine/src/decimal_digits.rs | 59 +-- crates/engine/src/query.rs | 20 +- crates/engine/src/query_gate_tests.rs | 145 ++++++++ crates/engine/src/query_key_values.rs | 301 +++++++++++----- .../query_key_values/request_order_tests.rs | 279 +++++++++++++++ crates/engine/src/query_key_values/tests.rs | 303 +++++----------- .../engine/src/query_key_values/unreadable.rs | 208 +++++++++++ .../src/query_key_values/unreadable_tests.rs | 301 ++++++++++++++++ tests/test_query_key_value_types.py | 337 ++++++------------ tests/test_query_leading_keys_values.py | 182 ++++++++++ tests/test_query_value_shapes.py | 174 +++++++++ 11 files changed, 1757 insertions(+), 552 deletions(-) create mode 100644 crates/engine/src/query_gate_tests.rs create mode 100644 crates/engine/src/query_key_values/request_order_tests.rs create mode 100644 crates/engine/src/query_key_values/unreadable.rs create mode 100644 crates/engine/src/query_key_values/unreadable_tests.rs create mode 100644 tests/test_query_leading_keys_values.py create mode 100644 tests/test_query_value_shapes.py diff --git a/crates/engine/src/decimal_digits.rs b/crates/engine/src/decimal_digits.rs index 8aeb24130..60e86a4ee 100644 --- a/crates/engine/src/decimal_digits.rs +++ b/crates/engine/src/decimal_digits.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 -//! Unicode decimal digits (general category `Nd`) folded to ASCII for the -//! request-time number check. +//! Unicode decimal digits (general category `Nd`) in the Basic Multilingual +//! Plane, folded to ASCII for the request-time number check. //! //! Measured 2026-10-25 (us-east-1, each request twice): the service reads a //! fullwidth, Arabic-Indic or Devanagari digit in an `N` value as the digit it @@ -10,34 +10,37 @@ //! digits in a Number`), and refuses a superscript (`\u{b2}`), a vulgar //! fraction (`\u{bd}`), a fullwidth minus (`\u{ff0d}`) and a fullwidth full //! stop (`\u{ff0e}`) with `The parameter cannot be converted to a numeric -//! value: `. The accepted characters are exactly those of category `Nd`; -//! the refused ones are `No` or `Pd` and `Po`. +//! value: `. The refused ones are `No` or `Pd` and `Po`. +//! +//! The service accepts a category `Nd` digit only below U+10000 (measured +//! 2026-11-11, each request twice): digit one of each of the 37 `Nd` runs up +//! to U+FF10 is accepted as a `FilterExpression` value, and digit one of each +//! of the 31 runs from U+104A0 up answers `The parameter cannot be converted to +//! a numeric value: `. //! //! Every `Nd` run in Unicode 15.0 is ten consecutive code points starting at -//! its zero, so the table below holds the 68 zeros (generated with Python's -//! `unicodedata`, Unicode 15.0.0) and a digit's value is its offset from the -//! run's zero. +//! its zero, so the table below holds the 37 zeros below U+10000 (generated +//! with Python's `unicodedata`, Unicode 15.0.0) and a digit's value is its +//! offset from the run's zero. //! -//! The fold applies to the check only. The handler and the server's -//! `dynamodb:LeadingKeys` binding read the value as the request wrote it, so -//! both see the same text; reading a Unicode digit as the digit has to change -//! both together. +//! The fold applies to the check and the text of its refusal only. The handler +//! and the server's `dynamodb:LeadingKeys` binding read the value as the +//! request wrote it, so both see the same text; reading a Unicode digit as the +//! digit has to change both together. use std::borrow::Cow; -/// The zero of every `Nd` run in Unicode 15.0, ascending. -const ND_ZEROS: [u32; 68] = [ +/// The zero of every `Nd` run in Unicode 15.0 below U+10000, ascending. +const ND_ZEROS: [u32; 37] = [ 0x0030, 0x0660, 0x06F0, 0x07C0, 0x0966, 0x09E6, 0x0A66, 0x0AE6, 0x0B66, 0x0BE6, 0x0C66, 0x0CE6, 0x0D66, 0x0DE6, 0x0E50, 0x0ED0, 0x0F20, 0x1040, 0x1090, 0x17E0, 0x1810, 0x1946, 0x19D0, 0x1A80, 0x1A90, 0x1B50, 0x1BB0, 0x1C40, 0x1C50, 0xA620, 0xA8D0, 0xA900, 0xA9D0, 0xA9F0, 0xAA50, 0xABF0, - 0xFF10, 0x104A0, 0x10D30, 0x11066, 0x110F0, 0x11136, 0x111D0, 0x112F0, 0x11450, 0x114D0, - 0x11650, 0x116C0, 0x11730, 0x118E0, 0x11950, 0x11C50, 0x11D50, 0x11DA0, 0x11F50, 0x16A60, - 0x16AC0, 0x16B50, 0x1D7CE, 0x1D7D8, 0x1D7E2, 0x1D7EC, 0x1D7F6, 0x1E140, 0x1E2F0, 0x1E4F0, - 0x1E950, 0x1FBF0, + 0xFF10, ]; /// The ASCII digit `c` stands for when `c` is a Unicode decimal digit -/// (general category `Nd`), or `None` for every other character. +/// (general category `Nd`) below U+10000, or `None` for every other +/// character. pub(crate) fn ascii_digit(c: char) -> Option { let cp = u32::from(c); // The zero of the run that could hold `cp`: the last zero at or below it. @@ -91,12 +94,28 @@ mod tests { assert_eq!(ascii_digit('a'), None); assert_eq!(ascii_digit('.'), None); assert_eq!(ascii_digit('e'), None); - assert_eq!(ascii_digit('\u{1FBF9}'), Some('9')); - assert_eq!(ascii_digit('\u{1FBFA}'), None); assert_eq!(ascii_digit(char::MAX), None); assert_eq!(ascii_digit('\u{0}'), None); } + #[test] + fn digits_from_u_104a0_up_are_not_folded() { + // Measured 2026-11-11: digit one of each run from U+104A0 up is refused, + // and digit one of the last run below U+10000 is accepted. + for c in [ + '\u{104A1}', + '\u{11067}', + '\u{1D7CF}', + '\u{1D7F7}', + '\u{1E951}', + '\u{1FBF1}', + ] { + assert_eq!(ascii_digit(c), None, "{c:?}"); + } + assert_eq!(ascii_digit('\u{ABF1}'), Some('1')); + assert_eq!(fold_decimal_digits("\u{ff11}\u{1D7CF}"), "1\u{1D7CF}"); + } + #[test] fn zeros_are_ascending_and_distinct_runs() { for pair in ND_ZEROS.windows(2) { diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 5dd85edfe..76fedd5ea 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -48,8 +48,8 @@ pub async fn handle_query( ctx: &OperationContext, ) -> Result { // Request-time checks on the raw body, in the service's order: Limit, the - // expression and non-expression parameter mix, the ReturnConsumedCapacity - // enum, every number in ExpressionAttributeValues, the Select enum. They + // ReturnConsumedCapacity enum, the expression and non-expression parameter + // mix, every number in ExpressionAttributeValues, the Select enum. They // run before typed deserialization so a field that does not deserialize // does not stop the ones before it. The server runs the same function // ahead of the IAM decision; see `query_key_values`. @@ -247,10 +247,10 @@ pub async fn handle_query( // :n` on an S key with a second clause on a non-key attribute reports the // type, not a missing key schema element (measured 2026-10-21). This path // has no non-key rule, so that query also reaches the check below. - // Legacy `KeyConditions` do not go through the check below, so the - // classifier still checks their values: against the key schema's - // definitions on a multi-attribute key schema and against the table's on a - // single-attribute one. + // Legacy `KeyConditions` are checked by the classifier: against the key + // schema's definitions on a multi-attribute key schema and against the + // table's on a single-attribute one. The check below runs only where the + // classifier did not check (`!check_types_here`). let multipart = extenddb_core::types::is_multipart_key_schema(&query_key_info.key_schema); let key_schema_definitions: Vec = query_key_info .attribute_definitions @@ -450,8 +450,8 @@ pub async fn handle_query( // refused after the key schema, filter, projection, unused value and // Select checks and before the ExclusiveStartKey check (measured // 2026-10-24). The classifier above checked the values of legacy - // `KeyConditions`. - if legacy_kc_maps.is_none() { + // `KeyConditions` and of every multi-attribute key schema. + if !check_types_here { crate::query_key_values::validate_key_condition_types( &key_condition, effective_maps, @@ -778,3 +778,7 @@ mod empty_key_condition_tests { #[cfg(test)] #[path = "query_begins_with_tests.rs"] mod begins_with_tests; + +#[cfg(test)] +#[path = "query_gate_tests.rs"] +mod gate_tests; diff --git a/crates/engine/src/query_gate_tests.rs b/crates/engine/src/query_gate_tests.rs new file mode 100644 index 000000000..c39f5c1b0 --- /dev/null +++ b/crates/engine/src/query_gate_tests.rs @@ -0,0 +1,145 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Tests for the split of the key condition type check in [`handle_query`]: +//! the classifier checks the values of legacy `KeyConditions` and of a +//! multi-attribute key schema, and `validate_key_condition_types` checks the +//! others after the Select check. The multi-attribute row fails when the +//! classifier stops checking a multi-attribute key schema. The legacy row pins +//! only that legacy values are type-checked: with the legacy term of the split +//! dropped, `validate_key_condition_types` answers the same text. The expected +//! answers were measured on the service in us-east-1 on 2026-11-11, the +//! multi-attribute ones on a GSI. + +use std::sync::Arc; + +use serde_json::{Value, json}; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::limits::LimitsConfig; +use extenddb_core::types::{ + AttributeDefinition, KeySchemaElement, KeyType, ScalarAttributeType, TableKeyInfo, +}; +use extenddb_storage_sqlite::SqliteEngine; + +use super::handle_query; +use crate::query_key_values::KEY_CONDITION_TYPE_MISMATCH; +use crate::{AuthorizedKeyInfo, BackupRuntime, OperationContext}; + +/// A context whose authorization snapshot holds table `kvt` with `key_schema` +/// and `definitions`, so the request reads no catalog. Every request here is +/// refused before a row is read, so the store stays empty. The key schema is +/// the one the query reads, so a multi-attribute one stands for a GSI's. +async fn context( + key_schema: &[(&str, KeyType)], + definitions: &[(&str, ScalarAttributeType)], +) -> OperationContext { + let storage = SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) + .await + .expect("an in-memory database opens"); + let key_schema: Vec = key_schema + .iter() + .map(|(name, key_type)| KeySchemaElement { + attribute_name: (*name).to_owned(), + key_type: *key_type, + }) + .collect(); + let info = TableKeyInfo { + table_name: "kvt".to_owned(), + account_id: "000000000000".to_owned(), + table_id: "kvt-id".to_owned(), + key_schema: key_schema.clone(), + base_key_schema: key_schema, + attribute_definitions: definitions + .iter() + .map(|(name, attribute_type)| AttributeDefinition { + attribute_name: (*name).to_owned(), + attribute_type: *attribute_type, + }) + .collect(), + has_lsi: false, + global_secondary_indexes: Vec::new(), + local_secondary_indexes: Vec::new(), + stream_specification: None, + vector_indexes: Vec::new(), + }; + let mut authorized_key_info = AuthorizedKeyInfo::new(); + authorized_key_info.insert("kvt".to_owned(), Some(info)); + OperationContext { + storage: Arc::new(storage), + backup: Arc::new(BackupRuntime::new(1)), + limits: Arc::new(LimitsConfig::default()), + region: Arc::from("us-east-1"), + account_id: Arc::from("000000000000"), + import_paths: Arc::from(Vec::new()), + export_paths: Arc::from(Vec::new()), + authorized_key_info, + auth_cache: extenddb_auth::AuthCacheRegistry::default(), + table_key_info_lookup: None, + item_authorizer: None, + } +} + +/// The `ValidationException` text `body` answers. +async fn refusal(ctx: &OperationContext, body: Value) -> String { + match handle_query(body, ctx).await { + Err(DynamoDbError::ValidationException(msg)) => msg, + Err(other) => panic!("unexpected error {other:?}"), + Ok(_) => panic!("the request was accepted"), + } +} + +#[tokio::test] +async fn legacy_key_conditions_value_of_another_type_is_refused() { + // `KeyConditions` with `{"N": "5"}` for the S partition key. + let ctx = context( + &[("pk", KeyType::Hash), ("sk", KeyType::Range)], + &[ + ("pk", ScalarAttributeType::S), + ("sk", ScalarAttributeType::S), + ], + ) + .await; + let body = json!({ + "TableName": "kvt", + "KeyConditions": { + "pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"N": "5"}]}, + }, + }); + assert_eq!(refusal(&ctx, body).await, KEY_CONDITION_TYPE_MISMATCH); +} + +#[tokio::test] +async fn multi_attribute_value_of_another_type_is_refused_before_the_non_key_rule() { + // HASH `h1` (S) and `h2` (N), RANGE `r` (S): an S value for `h2` beside a + // clause on the non-key attribute `z` answers the type, and with an N + // value the clause on `z` answers the missing RANGE attribute. + let ctx = context( + &[ + ("h1", KeyType::Hash), + ("h2", KeyType::Hash), + ("r", KeyType::Range), + ], + &[ + ("h1", ScalarAttributeType::S), + ("h2", ScalarAttributeType::N), + ("r", ScalarAttributeType::S), + ], + ) + .await; + let query = |h2: Value| { + json!({ + "TableName": "kvt", + "KeyConditionExpression": "h1 = :a AND h2 = :b AND z = :c", + "ExpressionAttributeValues": {":a": {"S": "x"}, ":b": h2, ":c": {"S": "x"}}, + }) + }; + assert_eq!( + refusal(&ctx, query(json!({"S": "1"}))).await, + KEY_CONDITION_TYPE_MISMATCH + ); + assert_eq!( + refusal(&ctx, query(json!({"N": "1"}))).await, + "Query condition missed key schema element: r" + ); +} diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index 54886bf96..69fbb6ce1 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -4,15 +4,16 @@ //! any row is read. //! //! Measured on 2026-10-24 (tables with S/S, S/N and B/B keys, a GSI and an -//! LSI): +//! LSI) and on 2026-11-11: //! //! 1. an `N` value in `ExpressionAttributeValues` that is not a number answers //! `The parameter cannot be converted to a numeric value: ` (or the //! overflow, underflow and 38-digit messages). Every value in the map is //! checked, whether the key condition, the filter or nothing reads it. The -//! check runs at request time, after the `Limit` check and the expression -//! and non-expression parameter mix check, and before the table is looked -//! up; see [`validate_query_request_body`]; +//! check runs at request time, after the `Limit` check, the +//! `ReturnConsumedCapacity` enum check and the expression and +//! non-expression parameter mix check, and before the table is looked up; +//! see [`validate_query_request_body`]; //! 2. a key condition value whose type is not the key attribute's //! `AttributeDefinitions` type answers `One or more parameter values were //! invalid: Condition parameter type does not match schema type`, on the @@ -35,7 +36,11 @@ use extenddb_core::expression::{ }; use extenddb_core::types::{AttributeDefinition, AttributeValue, QueryInput, ScalarAttributeType}; use serde::de::DeserializeOwned; -use serde_json::Value; +use serde_json::{Map, Value}; + +mod unreadable; + +use unreadable::{readable_for_shape_check, unreadable, unreadable_value_checks}; /// The service's text for a key condition value of the wrong type. pub const KEY_CONDITION_TYPE_MISMATCH: &str = "One or more parameter values were invalid: Condition parameter type does not match schema type"; @@ -46,14 +51,38 @@ pub const LIMIT_BELOW_ONE: &str = "1 validation error detected: Value at 'Limit' /// The bare numeric message the number validator uses for an empty `N`. const EMPTY_NUMBER: &str = "The parameter cannot be converted to a numeric value"; +/// The service's texts for a value it cannot read as one type. +const NULL_VALUE: &str = "The supplied Item contains a null AttributeValue"; +const EMPTY_VALUE: &str = + "Supplied AttributeValue is empty, must contain exactly one of the supported datatypes"; +const SEVERAL_TYPES: &str = "Supplied AttributeValue has more than one datatypes set, must contain exactly one of the supported datatypes"; + +/// The type descriptors of an AttributeValue. +const TYPE_DESCRIPTORS: [&str; 10] = ["S", "N", "B", "SS", "NS", "BS", "M", "L", "NULL", "BOOL"]; + +/// The members of the two enums the request-time checks read. +const RETURN_CONSUMED_CAPACITY: &[&str] = &["INDEXES", "TOTAL", "NONE"]; +const SELECT: &[&str] = &[ + "SPECIFIC_ATTRIBUTES", + "COUNT", + "ALL_ATTRIBUTES", + "ALL_PROJECTED_ATTRIBUTES", +]; + /// The `Query` checks that run on the request body alone, before the body is /// deserialized and before the table is looked up, in the service's order: -/// `Limit`, the expression and non-expression parameter mix, the -/// `ReturnConsumedCapacity` enum, every number in `ExpressionAttributeValues`, -/// then the `Select` enum (measured 2026-10-24: a `Limit` of 0 and a parameter -/// mix are reported ahead of an invalid enum value of either field, an invalid -/// `ReturnConsumedCapacity` ahead of an `N` value that is not a number, and -/// that value ahead of an invalid `Select`). +/// `Limit`, the `ReturnConsumedCapacity` enum, the expression and +/// non-expression parameter mix, every number in `ExpressionAttributeValues`, +/// then the `Select` enum (measured 2026-10-24 and 2026-11-11: a `Limit` of 0 +/// is reported ahead of an invalid enum value of either field and of a +/// parameter mix, an invalid `ReturnConsumedCapacity` ahead of a mix with +/// `AttributesToGet`, `QueryFilter`, `ConditionalOperator` or `KeyConditions` +/// and ahead of an `N` value that is not a number, a mix ahead of that value, +/// and that value ahead of an invalid `Select`). +/// +/// A request whose `ExpressionAttributeValues` holds a value the service +/// cannot read as one type takes another order; see +/// `unreadable_value_checks`. /// /// The checks read the raw body, so a field that does not deserialize (an /// invalid `Select`, for one) does not stop the ones before it. When a check @@ -65,7 +94,11 @@ const EMPTY_NUMBER: &str = "The parameter cannot be converted to a numeric value /// an `N` value that is not a number, and a `Limit` of 0 with `Select: 5` all /// answer `SerializationException`). A `ValidationException` the deserializer /// raises (an empty set, a duplicate, an invalid `AttributeValue`) does not -/// preempt the check. A body that passes every check is not deserialized here. +/// preempt the check. In a value the service cannot read as one type, only the +/// parts it cannot read are replaced for that deserialization, so a JSON-type +/// fault in the rest of the value is still a shape fault; see +/// `readable_for_shape_check`. A body that passes every check is not +/// deserialized here. /// /// The server runs the same function ahead of the IAM decision, so a principal /// whose `dynamodb:LeadingKeys` fence cannot bind a number that does not parse @@ -78,7 +111,8 @@ const EMPTY_NUMBER: &str = "The parameter cannot be converted to a numeric value /// Returns `DynamoDbError::ValidationException` with the service's text, or /// `DynamoDbError::SerializationException` for a body of the wrong shape. pub fn validate_query_request_body(body: &Value) -> Result<(), DynamoDbError> { - query_request_checks(body).map_err(|check| shape_fault_first::(body, check)) + query_request_checks(body) + .map_err(|check| shape_fault_first::(&readable_for_shape_check(body), check)) } /// When a request-time check has failed with `check`, the deserializer's @@ -116,6 +150,15 @@ const UNKNOWN_TYPE_DESCRIPTOR: &str = "unknown AttributeValue type descriptor"; /// The `Query` checks in the service's order; see /// [`validate_query_request_body`]. fn query_request_checks(body: &Value) -> Result<(), DynamoDbError> { + let values = body + .get("ExpressionAttributeValues") + .and_then(Value::as_object); + if let Some(values) = values + && values.values().any(unreadable) + { + return unreadable_value_checks(body, values); + } + if let Some(limit) = body.get("Limit").and_then(Value::as_i64) && limit < 1 { @@ -124,6 +167,36 @@ fn query_request_checks(body: &Value) -> Result<(), DynamoDbError> { )); } + // Query stops at the first invalid enum: ReturnConsumedCapacity ahead of + // the parameter mix, Select after the numbers (measured 2026-08-24 and + // 2026-11-11). + crate::validate_enum_fields( + body, + &[crate::EnumField { + json_name: "ReturnConsumedCapacity", + valid: RETURN_CONSUMED_CAPACITY, + clause: crate::EnumClause::Named("returnConsumedCapacity"), + }], + )?; + + validate_no_parameter_mix(body)?; + + if let Some(values) = values { + validate_expression_attribute_value_numbers(values)?; + } + + crate::validate_enum_fields( + body, + &[crate::EnumField { + json_name: "Select", + valid: SELECT, + clause: crate::EnumClause::Named("select"), + }], + ) +} + +/// The expression and non-expression parameter mix check. +fn validate_no_parameter_mix(body: &Value) -> Result<(), DynamoDbError> { let kce_present = present(body, "KeyConditionExpression"); // KeyConditions combines with FilterExpression and ProjectionExpression, so // it joins the mix check only when KeyConditionExpression is also present. @@ -145,37 +218,6 @@ fn query_request_checks(body: &Value) -> Result<(), DynamoDbError> { ("FilterExpression", present(body, "FilterExpression")), ("KeyConditionExpression", kce_present), ], - )?; - - // Query stops at the first invalid enum, ReturnConsumedCapacity ahead of - // Select (measured 2026-08-24); the numbers sit between the two. - crate::validate_enum_fields( - body, - &[crate::EnumField { - json_name: "ReturnConsumedCapacity", - valid: &["INDEXES", "TOTAL", "NONE"], - clause: crate::EnumClause::Named("returnConsumedCapacity"), - }], - )?; - - if let Some(raw) = body.get("ExpressionAttributeValues") - && let Ok(values) = serde_json::from_value::>(raw.clone()) - { - validate_expression_attribute_value_numbers(&values)?; - } - - crate::validate_enum_fields( - body, - &[crate::EnumField { - json_name: "Select", - valid: &[ - "SPECIFIC_ATTRIBUTES", - "COUNT", - "ALL_ATTRIBUTES", - "ALL_PROJECTED_ATTRIBUTES", - ], - clause: crate::EnumClause::Named("select"), - }], ) } @@ -194,56 +236,139 @@ fn non_empty(body: &Value, field: &str) -> bool { } } +/// The entries of `values` by placeholder, so the reported value is +/// deterministic when several are invalid. +fn sorted_entries(values: &Map) -> Vec<(&String, &Value)> { + let mut entries: Vec<(&String, &Value)> = values.iter().collect(); + entries.sort_by_key(|(key, _)| *key); + entries +} + +/// The first fault inside one value, in document order for `L` items and in +/// key order for `M` members. +enum Fault<'a> { + /// A null, with the member name when it is the value of an `M` member. + Null(Option<&'a str>), + /// No type descriptor the service knows. + Empty, + /// More than one type descriptor. + SeveralTypes, + /// An `N` text or `NS` member that is not a number, as the request wrote it. + NotANumber(&'a str), + /// A number the number rules refuse for its magnitude or precision, with + /// their text. + Refused(String), +} + +impl Fault<'_> { + /// The request-time number check's text: the value echoed with each + /// decimal digit folded to ASCII (measured 2026-11-11: `{"N": "\u{ff11}bob"}` + /// answers `The parameter cannot be converted to a numeric value: 1bob`, + /// `\u{661}\u{662}x` answers `12x`), and the colon kept after an empty one. + fn request_time_text(self) -> String { + match self { + Fault::NotANumber(text) => format!( + "{EMPTY_NUMBER}: {}", + crate::decimal_digits::fold_decimal_digits(text) + ), + other => other.reason(), + } + } + + /// The text [`unreadable_value_checks`] wraps: a number echoed as written + /// and no colon after an empty one (measured 2026-11-11). + fn reason(self) -> String { + match self { + Fault::Null(None) => NULL_VALUE.to_owned(), + Fault::Null(Some(member)) => format!("{NULL_VALUE}: {member} is null"), + Fault::Empty => EMPTY_VALUE.to_owned(), + Fault::SeveralTypes => SEVERAL_TYPES.to_owned(), + Fault::NotANumber("") => EMPTY_NUMBER.to_owned(), + Fault::NotANumber(text) => format!("{EMPTY_NUMBER}: {text}"), + Fault::Refused(msg) => msg, + } + } +} + +/// The first fault in `value` (`member` is its name when it is the value of an +/// `M` member): a null, no type descriptor or more than one, then the numbers +/// in `N`, `NS` and every value an `L` or `M` holds. `L` items are visited in +/// document order and `M` members in key order: this build of `serde_json` +/// keeps an object's members sorted by key. A value of another JSON type, and +/// an `N` or `NS` payload of the wrong JSON type, are shape faults the +/// deserializer reports. +fn first_fault<'a>(value: &'a Value, member: Option<&'a str>) -> Option> { + let Value::Object(map) = value else { + return value.is_null().then_some(Fault::Null(member)); + }; + let mut known = map + .iter() + .filter(|(key, _)| TYPE_DESCRIPTORS.contains(&key.as_str())); + let (descriptor, payload) = match (known.next(), known.next()) { + (None, _) => return Some(Fault::Empty), + (Some(_), Some(_)) => return Some(Fault::SeveralTypes), + (Some(entry), None) => entry, + }; + match (descriptor.as_str(), payload) { + ("N", Value::String(text)) => number_fault(text), + ("NS", Value::Array(members)) => members + .iter() + .filter_map(Value::as_str) + .find_map(number_fault), + ("L", Value::Array(items)) => items.iter().find_map(|item| first_fault(item, None)), + ("M", Value::Object(members)) => members + .iter() + .find_map(|(name, inner)| first_fault(inner, Some(name))), + _ => None, + } +} + +/// `text` against the number rules, with Unicode decimal digits folded for the +/// check; see [`crate::decimal_digits`]. +fn number_fault(text: &str) -> Option> { + let folded = crate::decimal_digits::fold_decimal_digits(text); + match extenddb_core::validation::number::validate_and_normalize_number(&folded) { + Ok(_) => None, + Err(DynamoDbError::ValidationException(msg)) if msg.starts_with(EMPTY_NUMBER) => { + Some(Fault::NotANumber(text)) + } + Err(DynamoDbError::ValidationException(msg)) => Some(Fault::Refused(msg)), + Err(other) => Some(Fault::Refused(other.to_string())), + } +} + /// Refuse the first `N` value in `ExpressionAttributeValues` (including `NS` /// members and values nested in `L` and `M`) that is not a number, with the /// bare numeric message: no `ExpressionAttributeValues contains invalid value` -/// wrapper, which the service uses on `UpdateItem` and not on `Query`. The -/// placeholders are visited in sorted order so the reported value is -/// deterministic when several are invalid. An empty `N` answers the message -/// with the colon and nothing after it, as the service does on `Query`. +/// wrapper, which the service uses on `UpdateItem` and on `Query` only for a +/// value it cannot read as one type. The placeholders are visited in sorted +/// order and each value on its own, so a value of the wrong JSON shape does +/// not stop the check of another (the service picks among several invalid +/// values by an order of its own: measured 2026-11-11, `:a` and `:b` with +/// numbers that are not numbers named either over ten requests). An empty `N` +/// answers the message with the colon and nothing after it, as the service +/// does on `Query`. /// -/// A Unicode decimal digit (general category `Nd`) counts as the digit it -/// stands for, as the service reads it (measured 2026-10-25: a fullwidth or -/// Arabic-Indic digit is accepted, thirty nine Devanagari ones answer the 38 -/// digit message); see [`crate::decimal_digits`]. The message echoes the value -/// as the request wrote it. +/// A Unicode decimal digit in the Basic Multilingual Plane counts as the +/// digit it stands for, as the service reads it (measured 2026-10-25: a +/// fullwidth or Arabic-Indic digit is accepted, thirty nine Devanagari ones +/// answer the 38 digit message); see [`crate::decimal_digits`]. The message +/// echoes the value with each such digit folded to ASCII. /// /// # Errors /// /// Returns `DynamoDbError::ValidationException` with the service's text. -pub fn validate_expression_attribute_value_numbers( - values: &HashMap, +fn validate_expression_attribute_value_numbers( + values: &Map, ) -> Result<(), DynamoDbError> { - let mut keys: Vec<&String> = values.keys().collect(); - keys.sort(); - for key in keys { - validate_value_numbers(&values[key])?; - } - Ok(()) -} - -/// Every number inside one attribute value (`N`, `NS` members, and the values -/// nested in `L` and `M`), with Unicode decimal digits folded for the check. -fn validate_value_numbers(value: &AttributeValue) -> Result<(), DynamoDbError> { - match value { - AttributeValue::N(n) => validate_number_text(n), - AttributeValue::NS(set) => set.iter().try_for_each(|n| validate_number_text(n)), - AttributeValue::L(list) => list.iter().try_for_each(validate_value_numbers), - AttributeValue::M(map) => map.values().try_for_each(validate_value_numbers), - _ => Ok(()), - } -} - -/// One number text against the number rules, with the service's `Query` -/// message for an empty value and the original text echoed for a malformed one. -fn validate_number_text(text: &str) -> Result<(), DynamoDbError> { - let folded = crate::decimal_digits::fold_decimal_digits(text); - match extenddb_core::validation::number::validate_and_normalize_number(&folded) { - Ok(_) => Ok(()), - Err(DynamoDbError::ValidationException(msg)) if msg.starts_with(EMPTY_NUMBER) => Err( - DynamoDbError::ValidationException(format!("{EMPTY_NUMBER}: {text}")), - ), - Err(other) => Err(other), + match sorted_entries(values) + .into_iter() + .find_map(|(_, value)| first_fault(value, None)) + { + Some(fault) => Err(DynamoDbError::ValidationException( + fault.request_time_text(), + )), + None => Ok(()), } } @@ -341,3 +466,9 @@ fn resolve_attr_name(path: &[PathElement], names: &HashMap) -> O #[cfg(test)] mod tests; + +#[cfg(test)] +mod request_order_tests; + +#[cfg(test)] +mod unreadable_tests; diff --git a/crates/engine/src/query_key_values/request_order_tests.rs b/crates/engine/src/query_key_values/request_order_tests.rs new file mode 100644 index 000000000..c83d769ae --- /dev/null +++ b/crates/engine/src/query_key_values/request_order_tests.rs @@ -0,0 +1,279 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Tests for the order of the request-time `Query` checks, and for a shape +//! fault reported ahead of them. + +use extenddb_core::error::DynamoDbError; +use serde_json::json; + +use super::tests::message; +use super::{LIMIT_BELOW_ONE, validate_query_request_body}; + +#[test] +fn request_time_checks_run_limit_then_mix_then_numbers() { + let bad_number = serde_json::json!({ + "TableName": "t", + "KeyConditionExpression": "pk = :u", + "ExpressionAttributeValues": {":u": {"N": "bob"}}, + }); + + let mut with_limit = bad_number.clone(); + with_limit["Limit"] = serde_json::json!(0); + assert_eq!( + message(validate_query_request_body(&with_limit)).as_deref(), + Some(LIMIT_BELOW_ONE) + ); + + let mut with_mix = bad_number.clone(); + with_mix["KeyConditions"] = serde_json::json!({ + "pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]} + }); + assert_eq!( + message(validate_query_request_body(&with_mix)).as_deref(), + Some( + "Can not use both expression and non-expression parameters in the same request: \ + Non-expression parameters: {KeyConditions} Expression parameters: {KeyConditionExpression}" + ) + ); + + assert_eq!( + message(validate_query_request_body(&bad_number)).as_deref(), + Some("The parameter cannot be converted to a numeric value: bob") + ); + + // A number only a FilterExpression reads, and one nothing reads. + for body in [ + serde_json::json!({ + "TableName": "t", + "KeyConditionExpression": "pk = :p", + "FilterExpression": "a = :n", + "ExpressionAttributeValues": {":p": {"S": "x"}, ":n": {"N": "bob"}}, + }), + serde_json::json!({ + "TableName": "t", + "KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": {":p": {"S": "x"}, ":n": {"N": "bob"}}, + }), + ] { + assert_eq!( + message(validate_query_request_body(&body)).as_deref(), + Some("The parameter cannot be converted to a numeric value: bob") + ); + } + + // Legacy KeyConditions alone does not join the mix check; a well-formed + // request passes. + let legacy = serde_json::json!({ + "TableName": "t", + "KeyConditions": { + "pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]} + }, + "FilterExpression": "a = :n", + "ExpressionAttributeValues": {":n": {"N": "5"}}, + "Limit": 1, + }); + assert!(validate_query_request_body(&legacy).is_ok()); +} + +#[test] +fn enum_checks_sit_on_either_side_of_the_numbers() { + // Measured 2026-10-24 and 2026-11-11: an invalid ReturnConsumedCapacity is + // reported ahead of an N value that is not a number, and that value ahead + // of an invalid Select; a Limit of 0 ahead of either enum. + let bad_number = serde_json::json!({ + "TableName": "t", + "KeyConditionExpression": "pk = :u", + "ExpressionAttributeValues": {":u": {"N": "bob"}}, + }); + let mut rcc = bad_number.clone(); + rcc["ReturnConsumedCapacity"] = serde_json::json!("bad"); + assert_eq!( + message(validate_query_request_body(&rcc)).as_deref(), + Some( + "1 validation error detected: Value 'bad' at 'returnConsumedCapacity' failed to \ + satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]" + ) + ); + let mut select = bad_number.clone(); + select["Select"] = serde_json::json!("bad"); + assert_eq!( + message(validate_query_request_body(&select)).as_deref(), + Some("The parameter cannot be converted to a numeric value: bob") + ); + for field in ["ReturnConsumedCapacity", "Select"] { + let mut limit = bad_number.clone(); + limit[field] = serde_json::json!("bad"); + limit["Limit"] = serde_json::json!(0); + assert_eq!( + message(validate_query_request_body(&limit)).as_deref(), + Some(LIMIT_BELOW_ONE), + "{field}" + ); + } + // With the numbers valid, an invalid Select is still reported. + let mut only_select = serde_json::json!({ + "TableName": "t", + "KeyConditionExpression": "pk = :u", + "ExpressionAttributeValues": {":u": {"S": "bob"}}, + }); + only_select["Select"] = serde_json::json!("bad"); + assert!( + message(validate_query_request_body(&only_select)) + .is_some_and(|m| m.contains("at 'select' failed to satisfy constraint")) + ); +} + +const RCC_MSG: &str = "1 validation error detected: Value 'bad' at 'returnConsumedCapacity' \ + failed to satisfy constraint: Member must satisfy enum value set: \ + [INDEXES, TOTAL, NONE]"; + +#[test] +fn return_consumed_capacity_is_reported_ahead_of_the_parameter_mix() { + // Measured 2026-11-11 with each non-expression parameter beside + // KeyConditionExpression: an invalid ReturnConsumedCapacity is reported + // ahead of the mix, and the mix ahead of an N value that is not a number + // and of an invalid Select. + for (name, value) in [ + ("AttributesToGet", json!(["a"])), + ( + "QueryFilter", + json!({"a": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]}}), + ), + ("ConditionalOperator", json!("AND")), + ( + "KeyConditions", + json!({"pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]}}), + ), + ] { + let mut body = json!({ + "TableName": "t", + "KeyConditionExpression": "pk = :u", + "ExpressionAttributeValues": {":u": {"N": "bob"}}, + "Select": "bad", + }); + body[name] = value; + let mix = format!( + "Can not use both expression and non-expression parameters in the same request: \ + Non-expression parameters: {{{name}}} Expression parameters: \ + {{KeyConditionExpression}}" + ); + assert_eq!( + message(validate_query_request_body(&body)).as_deref(), + Some(mix.as_str()), + "{name}" + ); + body["ReturnConsumedCapacity"] = json!("bad"); + assert_eq!( + message(validate_query_request_body(&body)).as_deref(), + Some(RCC_MSG), + "{name}" + ); + body["Limit"] = json!(0); + assert_eq!( + message(validate_query_request_body(&body)).as_deref(), + Some(LIMIT_BELOW_ONE), + "{name}" + ); + } +} + +#[test] +fn a_shape_fault_in_another_field_is_reported_ahead_of_the_checks() { + // Measured 2026-10-25: a field of the wrong JSON type + // anywhere in the body answers SerializationException even when a Limit, + // mix, enum or number check would fail. + let shape_faults = [ + serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "Limit": 0, "ExpressionAttributeValues": "x", + }), + serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "ExpressionAttributeNames": "x", + "ExpressionAttributeValues": {":p": {"N": "bob"}}, + }), + serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "Limit": "1", "ExpressionAttributeValues": {":p": {"N": "bob"}}, + }), + serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "AttributesToGet": {"a": 1}, "ProjectionExpression": "a", + "ExpressionAttributeValues": {":p": {"S": "x"}}, + }), + serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "QueryFilter": [1], "FilterExpression": "a = :p", + "ExpressionAttributeValues": {":p": {"S": "x"}}, + }), + serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "Select": 5, "ExpressionAttributeValues": {":p": {"N": "bob"}}, + }), + serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "Limit": 0, "Select": 5, "ExpressionAttributeValues": {":p": {"S": "x"}}, + }), + ]; + for body in shape_faults { + assert!( + matches!( + validate_query_request_body(&body), + Err(DynamoDbError::SerializationException(_)) + ), + "{body}" + ); + } + + // A string enum value that is not a member is the checks' own answer, not a + // shape fault. + let mut select = serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "Limit": 0, "ExpressionAttributeValues": {":p": {"S": "x"}}, + }); + select["Select"] = serde_json::json!("bad"); + assert_eq!( + message(validate_query_request_body(&select)).as_deref(), + Some(LIMIT_BELOW_ONE) + ); + select["ReturnConsumedCapacity"] = serde_json::json!("bad"); + select["Limit"] = serde_json::json!(1); + assert!( + message(validate_query_request_body(&select)) + .is_some_and(|m| m.contains("at 'returnConsumedCapacity' failed to satisfy constraint")) + ); + + // A ValidationException the deserializer raises does not preempt a check: + // an empty NS beside a Limit of 0 answers the Limit text. + let empty_set = serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "Limit": 0, "ExpressionAttributeValues": {":p": {"S": "x"}, ":s": {"NS": []}}, + }); + assert_eq!( + message(validate_query_request_body(&empty_set)).as_deref(), + Some(LIMIT_BELOW_ONE) + ); + + // Neither does an unknown type descriptor, which the deserializer reports + // as a SerializationException: the service answers the Limit + // ValidationException in the form that names the value (measured + // 2026-10-25 and 2026-11-11). + let unknown_type = serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "Limit": 0, "ExpressionAttributeValues": {":p": {"S": "x"}, ":a": {"X": "1"}}, + }); + assert_eq!( + message(validate_query_request_body(&unknown_type)).as_deref(), + Some( + "1 validation error detected: Value '0' at 'limit' failed to satisfy constraint: \ + Member must have value greater than or equal to 1" + ) + ); + + // A body that passes every check is left to the handler's deserializer. + let shape_fault_only = serde_json::json!({ + "TableName": "t", "KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": "x", + }); + assert!(validate_query_request_body(&shape_fault_only).is_ok()); +} diff --git a/crates/engine/src/query_key_values/tests.rs b/crates/engine/src/query_key_values/tests.rs index 68c353943..2a2bce4b4 100644 --- a/crates/engine/src/query_key_values/tests.rs +++ b/crates/engine/src/query_key_values/tests.rs @@ -7,12 +7,23 @@ use extenddb_core::expression::{ ExpressionMaps, KeyCondition, parse_key_condition, tokenize_with_limit, }; use extenddb_core::types::{AttributeDefinition, AttributeValue, ScalarAttributeType}; +use serde_json::{Value, json}; use super::{ - KEY_CONDITION_TYPE_MISMATCH, LIMIT_BELOW_ONE, validate_expression_attribute_value_numbers, - validate_key_condition_types, validate_query_request_body, + KEY_CONDITION_TYPE_MISMATCH, validate_key_condition_types, validate_query_request_body, }; +/// The request-time number check on typed values, serialized as a request +/// carries them. +fn validate_expression_attribute_value_numbers( + values: &HashMap, +) -> Result<(), DynamoDbError> { + let Value::Object(raw) = serde_json::to_value(values).expect("the values serialize") else { + panic!("a map serializes to an object"); + }; + super::validate_expression_attribute_value_numbers(&raw) +} + fn defs(pairs: &[(&str, ScalarAttributeType)]) -> Vec { pairs .iter() @@ -49,7 +60,7 @@ fn n(v: &str) -> AttributeValue { AttributeValue::N(v.to_owned()) } -fn message(result: Result<(), DynamoDbError>) -> Option { +pub(super) fn message(result: Result<(), DynamoDbError>) -> Option { match result { Ok(()) => None, Err(DynamoDbError::ValidationException(msg)) => Some(msg), @@ -324,120 +335,6 @@ fn first_invalid_number_in_placeholder_order_is_reported() { ); } -#[test] -fn request_time_checks_run_limit_then_mix_then_numbers() { - let bad_number = serde_json::json!({ - "TableName": "t", - "KeyConditionExpression": "pk = :u", - "ExpressionAttributeValues": {":u": {"N": "bob"}}, - }); - - let mut with_limit = bad_number.clone(); - with_limit["Limit"] = serde_json::json!(0); - assert_eq!( - message(validate_query_request_body(&with_limit)).as_deref(), - Some(LIMIT_BELOW_ONE) - ); - - let mut with_mix = bad_number.clone(); - with_mix["KeyConditions"] = serde_json::json!({ - "pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]} - }); - assert_eq!( - message(validate_query_request_body(&with_mix)).as_deref(), - Some( - "Can not use both expression and non-expression parameters in the same request: \ - Non-expression parameters: {KeyConditions} Expression parameters: {KeyConditionExpression}" - ) - ); - - assert_eq!( - message(validate_query_request_body(&bad_number)).as_deref(), - Some("The parameter cannot be converted to a numeric value: bob") - ); - - // A number only a FilterExpression reads, and one nothing reads. - for body in [ - serde_json::json!({ - "TableName": "t", - "KeyConditionExpression": "pk = :p", - "FilterExpression": "a = :n", - "ExpressionAttributeValues": {":p": {"S": "x"}, ":n": {"N": "bob"}}, - }), - serde_json::json!({ - "TableName": "t", - "KeyConditionExpression": "pk = :p", - "ExpressionAttributeValues": {":p": {"S": "x"}, ":n": {"N": "bob"}}, - }), - ] { - assert_eq!( - message(validate_query_request_body(&body)).as_deref(), - Some("The parameter cannot be converted to a numeric value: bob") - ); - } - - // Legacy KeyConditions alone does not join the mix check; a well-formed - // request passes. - let legacy = serde_json::json!({ - "TableName": "t", - "KeyConditions": { - "pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]} - }, - "FilterExpression": "a = :n", - "ExpressionAttributeValues": {":n": {"N": "5"}}, - "Limit": 1, - }); - assert!(validate_query_request_body(&legacy).is_ok()); -} - -#[test] -fn enum_checks_sit_on_either_side_of_the_numbers() { - // Measured 2026-10-24: an invalid ReturnConsumedCapacity is reported ahead - // of an N value that is not a number, and that value ahead of an invalid - // Select; a Limit of 0 and a parameter mix ahead of either enum. - let bad_number = serde_json::json!({ - "TableName": "t", - "KeyConditionExpression": "pk = :u", - "ExpressionAttributeValues": {":u": {"N": "bob"}}, - }); - let mut rcc = bad_number.clone(); - rcc["ReturnConsumedCapacity"] = serde_json::json!("bad"); - assert_eq!( - message(validate_query_request_body(&rcc)).as_deref(), - Some( - "1 validation error detected: Value 'bad' at 'returnConsumedCapacity' failed to \ - satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]" - ) - ); - let mut select = bad_number.clone(); - select["Select"] = serde_json::json!("bad"); - assert_eq!( - message(validate_query_request_body(&select)).as_deref(), - Some("The parameter cannot be converted to a numeric value: bob") - ); - for field in ["ReturnConsumedCapacity", "Select"] { - let mut limit = bad_number.clone(); - limit[field] = serde_json::json!("bad"); - limit["Limit"] = serde_json::json!(0); - assert_eq!( - message(validate_query_request_body(&limit)).as_deref(), - Some(LIMIT_BELOW_ONE), - "{field}" - ); - } - // With the numbers valid, an invalid Select is still reported. - let mut only_select = serde_json::json!({ - "TableName": "t", - "KeyConditionExpression": "pk = :u", - "ExpressionAttributeValues": {":u": {"S": "bob"}}, - }); - only_select["Select"] = serde_json::json!("bad"); - assert!( - message(validate_query_request_body(&only_select)) - .is_some_and(|m| m.contains("at 'select' failed to satisfy constraint")) - ); -} - #[test] fn unicode_decimal_digits_count_as_the_digits_they_stand_for() { // Measured 2026-10-25: a fullwidth, Arabic-Indic or Devanagari digit is accepted as a @@ -475,7 +372,7 @@ fn characters_that_are_not_decimal_digits_are_refused_with_the_text_as_sent() { // Measured 2026-10-25: a superscript, // a vulgar fraction, a fullwidth minus and a fullwidth full stop are refused // and the message echoes the value as the request wrote it. - for raw in ["\u{b2}", "\u{bd}", "\u{ff0d}1", "1\u{ff0e}5", "\u{ff11}bob"] { + for raw in ["\u{b2}", "\u{bd}", "\u{ff0d}1", "1\u{ff0e}5"] { let values = HashMap::from([(":u".to_owned(), n(raw))]); assert_eq!( message(validate_expression_attribute_value_numbers(&values)).as_deref(), @@ -486,99 +383,93 @@ fn characters_that_are_not_decimal_digits_are_refused_with_the_text_as_sent() { } #[test] -fn a_shape_fault_in_another_field_is_reported_ahead_of_the_checks() { - // Measured 2026-10-25: a field of the wrong JSON type - // anywhere in the body answers SerializationException even when a Limit, - // mix, enum or number check would fail. - let shape_faults = [ - serde_json::json!({ - "TableName": "t", "KeyConditionExpression": "pk = :p", - "Limit": 0, "ExpressionAttributeValues": "x", - }), - serde_json::json!({ - "TableName": "t", "KeyConditionExpression": "pk = :p", - "ExpressionAttributeNames": "x", - "ExpressionAttributeValues": {":p": {"N": "bob"}}, - }), - serde_json::json!({ - "TableName": "t", "KeyConditionExpression": "pk = :p", - "Limit": "1", "ExpressionAttributeValues": {":p": {"N": "bob"}}, - }), - serde_json::json!({ - "TableName": "t", "KeyConditionExpression": "pk = :p", - "AttributesToGet": {"a": 1}, "ProjectionExpression": "a", - "ExpressionAttributeValues": {":p": {"S": "x"}}, - }), - serde_json::json!({ - "TableName": "t", "KeyConditionExpression": "pk = :p", - "QueryFilter": [1], "FilterExpression": "a = :p", - "ExpressionAttributeValues": {":p": {"S": "x"}}, - }), - serde_json::json!({ - "TableName": "t", "KeyConditionExpression": "pk = :p", - "Select": 5, "ExpressionAttributeValues": {":p": {"N": "bob"}}, - }), - serde_json::json!({ - "TableName": "t", "KeyConditionExpression": "pk = :p", - "Limit": 0, "Select": 5, "ExpressionAttributeValues": {":p": {"S": "x"}}, - }), - ]; - for body in shape_faults { - assert!( - matches!( - validate_query_request_body(&body), - Err(DynamoDbError::SerializationException(_)) - ), - "{body}" +fn a_refused_value_is_echoed_with_each_decimal_digit_folded_to_ascii() { + // Measured 2026-11-11: the service folds every decimal digit below U+10000 + // in the echoed value, and a digit from U+104A0 up is refused and echoed + // as sent. + for (raw, echo) in [ + ("\u{ff11}bob", "1bob"), + ("\u{661}\u{662}x", "12x"), + ("bob\u{ff11}", "bob1"), + ("\u{967}\u{968}a\u{969}", "12a3"), + ("\u{ff11}\u{1d7cf}", "1\u{1d7cf}"), + ("\u{1d7cf}", "\u{1d7cf}"), + ("\u{104a1}", "\u{104a1}"), + ] { + let values = HashMap::from([(":u".to_owned(), n(raw))]); + assert_eq!( + message(validate_expression_attribute_value_numbers(&values)).as_deref(), + Some(format!("The parameter cannot be converted to a numeric value: {echo}").as_str()), + "{raw:?}" ); } +} - // A string enum value that is not a member is the checks' own answer, not a - // shape fault. - let mut select = serde_json::json!({ - "TableName": "t", "KeyConditionExpression": "pk = :p", - "Limit": 0, "ExpressionAttributeValues": {":p": {"S": "x"}}, - }); - select["Select"] = serde_json::json!("bad"); - assert_eq!( - message(validate_query_request_body(&select)).as_deref(), - Some(LIMIT_BELOW_ONE) - ); - select["ReturnConsumedCapacity"] = serde_json::json!("bad"); - select["Limit"] = serde_json::json!(1); - assert!( - message(validate_query_request_body(&select)) - .is_some_and(|m| m.contains("at 'returnConsumedCapacity' failed to satisfy constraint")) - ); +#[test] +fn decimal_digits_from_u_104a0_up_are_not_numbers() { + // Measured 2026-11-11: digit one of each of the 31 decimal digit runs from + // U+104A0 up is refused as a filter value, and digit one of the last run + // below U+10000 is accepted. + for raw in [ + "\u{104a1}", + "\u{11067}", + "\u{1d7cf}", + "\u{1e951}", + "\u{1fbf1}", + ] { + let values = HashMap::from([(":u".to_owned(), n(raw))]); + assert_eq!( + message(validate_expression_attribute_value_numbers(&values)).as_deref(), + Some(format!("The parameter cannot be converted to a numeric value: {raw}").as_str()), + "{raw:?}" + ); + } + let values = HashMap::from([(":u".to_owned(), n("\u{abf1}"))]); + assert!(validate_expression_attribute_value_numbers(&values).is_ok()); +} - // A ValidationException the deserializer raises does not preempt a check: - // an empty NS beside a Limit of 0 answers the Limit text. - let empty_set = serde_json::json!({ - "TableName": "t", "KeyConditionExpression": "pk = :p", - "Limit": 0, "ExpressionAttributeValues": {":p": {"S": "x"}, ":s": {"NS": []}}, +/// A Query body with `values` as its `ExpressionAttributeValues` and `extra` +/// beside them. +pub(super) fn body_with(values: Value, extra: Value) -> Value { + let mut body = json!({ + "TableName": "t", + "KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": values, }); - assert_eq!( - message(validate_query_request_body(&empty_set)).as_deref(), - Some(LIMIT_BELOW_ONE) - ); + if let (Value::Object(body), Value::Object(extra)) = (&mut body, extra) { + body.extend(extra); + } + body +} - // Neither does an unknown type descriptor, which the deserializer reports - // as a SerializationException: the service answers the Limit - // ValidationException (measured 2026-10-25), in its older - // `Value '0' at 'limit'` form; ExtendDB answers its usual Limit text. - let unknown_type = serde_json::json!({ - "TableName": "t", "KeyConditionExpression": "pk = :p", - "Limit": 0, "ExpressionAttributeValues": {":p": {"S": "x"}, ":a": {"X": "1"}}, - }); - assert_eq!( - message(validate_query_request_body(&unknown_type)).as_deref(), - Some(LIMIT_BELOW_ONE) +#[test] +fn a_value_that_does_not_deserialize_does_not_stop_the_number_check_of_another() { + // Measured 2026-11-11: beside `:u = {"N": "bob"}`, an empty set, a + // duplicate set member or a NULL of false answered either that value's + // fault or the numeric fault over ten requests each, and a B that is not + // base64 answered SerializationException. + for other in [ + json!({"NS": []}), + json!({"SS": ["a", "a"]}), + json!({"NULL": false}), + json!({"L": [{"NS": []}]}), + ] { + let body = body_with( + json!({":p": {"S": "x"}, ":u": {"N": "bob"}, ":z": other}), + json!({}), + ); + assert_eq!( + message(validate_query_request_body(&body)).as_deref(), + Some("The parameter cannot be converted to a numeric value: bob"), + "{other}" + ); + } + let body = body_with( + json!({":p": {"S": "x"}, ":u": {"N": "bob"}, ":z": {"B": "!!"}}), + json!({}), ); - - // A body that passes every check is left to the handler's deserializer. - let shape_fault_only = serde_json::json!({ - "TableName": "t", "KeyConditionExpression": "pk = :p", - "ExpressionAttributeValues": "x", - }); - assert!(validate_query_request_body(&shape_fault_only).is_ok()); + assert!(matches!( + validate_query_request_body(&body), + Err(DynamoDbError::SerializationException(_)) + )); } diff --git a/crates/engine/src/query_key_values/unreadable.rs b/crates/engine/src/query_key_values/unreadable.rs new file mode 100644 index 000000000..cd6ec2e9c --- /dev/null +++ b/crates/engine/src/query_key_values/unreadable.rs @@ -0,0 +1,208 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `ExpressionAttributeValues` entries the service cannot read as one type: a +//! null, no type descriptor it knows, more than one, or one it does not know +//! beside one it does, in the value or in any value an `L` or `M` holds. A +//! `Query` with such an entry takes its own order of checks (see +//! [`unreadable_value_checks`]), and the shape fault check reads the entry with +//! those parts replaced (see [`readable_for_shape_check`]). + +use std::borrow::Cow; + +use extenddb_core::error::DynamoDbError; +use serde_json::{Map, Value}; + +use super::{ + RETURN_CONSUMED_CAPACITY, SELECT, TYPE_DESCRIPTORS, first_fault, sorted_entries, + validate_no_parameter_mix, +}; + +/// Whether the service cannot read `value` as exactly one AttributeValue type: +/// a null, no type descriptor it knows, more than one, or one it does not know +/// beside one it does, in the value or in any value an `L` or `M` holds. A +/// value of another JSON type is a shape fault instead. +pub(super) fn unreadable(value: &Value) -> bool { + match value { + Value::Null => true, + Value::Object(map) => { + let mut known = map + .iter() + .filter(|(key, _)| TYPE_DESCRIPTORS.contains(&key.as_str())); + match (known.next(), known.next()) { + (Some((key, inner)), None) => { + map.len() > 1 + || match (key.as_str(), inner) { + ("L", Value::Array(items)) => items.iter().any(unreadable), + ("M", Value::Object(members)) => members.values().any(unreadable), + _ => false, + } + } + _ => true, + } + } + _ => false, + } +} + +/// `body` for the shape fault check. When its `ExpressionAttributeValues` +/// holds a value the service cannot read as one type, each part the service +/// cannot read is replaced (see [`make_readable`]) and the rest of the value +/// stays, so the deserializer still reports a JSON-type fault in it. Measured +/// 2026-11-11: `{"L": [null, "x"]}`, `{"L": [{"X": "1"}, {"N": 5}]}` and +/// `{"L": [null, {"B": "!!"}]}`, and `{"S": 5, "X": "1"}` and `{"S": 5, "N": +/// "1"}` beside a `Limit` of 0, all answer `SerializationException`. +pub(super) fn readable_for_shape_check(body: &Value) -> Cow<'_, Value> { + match body + .get("ExpressionAttributeValues") + .and_then(Value::as_object) + { + Some(values) if values.values().any(unreadable) => { + let mut body = body.clone(); + if let Some(Value::Object(values)) = body.get_mut("ExpressionAttributeValues") { + values.values_mut().for_each(make_readable); + } + Cow::Owned(body) + } + _ => Cow::Borrowed(body), + } +} + +/// Replace each part of `value` the service cannot read as one type, in the +/// value and in the values an `L` or `M` holds. A null, or an object with no +/// type descriptor the service knows, becomes `{"NULL": true}`. An unknown +/// descriptor beside a known one is dropped. An object with several known +/// descriptors becomes an `L` of one value per descriptor, so the deserializer +/// still reads each payload (measured 2026-11-11: `{"L": [{"S": "a", "N": +/// "1"}, "x"]}` and `{"S": "a", "N": 1}` answer `SerializationException`). A +/// value of another JSON type is left for the deserializer to report. +fn make_readable(value: &mut Value) { + let replacement = match value { + Value::Null => Some(null_value()), + Value::Object(map) => { + map.retain(|key, _| TYPE_DESCRIPTORS.contains(&key.as_str())); + if map.len() > 1 { + let mut parts: Vec = std::mem::take(map) + .into_iter() + .map(|entry| Value::Object(Map::from_iter([entry]))) + .collect(); + parts.iter_mut().for_each(make_readable); + Some(Value::Object(Map::from_iter([( + "L".to_owned(), + Value::Array(parts), + )]))) + } else if let Some((key, payload)) = map.iter_mut().next() { + match (key.as_str(), payload) { + ("L", Value::Array(items)) => items.iter_mut().for_each(make_readable), + ("M", Value::Object(members)) => members.values_mut().for_each(make_readable), + _ => {} + } + None + } else { + Some(null_value()) + } + } + _ => None, + }; + if let Some(replacement) = replacement { + *value = replacement; + } +} + +/// `{"NULL": true}`, a value the deserializer reads. +fn null_value() -> Value { + Value::Object(Map::from_iter([("NULL".to_owned(), Value::Bool(true))])) +} + +/// The checks for a request whose `ExpressionAttributeValues` holds a value +/// the service cannot read as one type. Measured 2026-11-11, the service then +/// answers in this order: +/// +/// 1. an invalid `Select`, an invalid `ReturnConsumedCapacity` and a `Limit` +/// below 1, reported together in that order, with the `Limit` text naming +/// the value: `2 validation errors detected: Value 'bad' at +/// 'returnConsumedCapacity' failed to satisfy constraint: ...; Value '0' at +/// 'limit' failed to satisfy constraint: Member must have value greater +/// than or equal to 1`; +/// 2. the expression and non-expression parameter mix; +/// 3. the first fault inside a value, in document order for `L` items and in +/// key order for `M` members, as `ExpressionAttributeValues contains +/// invalid value: for key `: a null (`The supplied +/// Item contains a null AttributeValue`, with `: is null` when it +/// is the value of an `M` member), no type descriptor, more than one, or an +/// `N` that is not a number. Such an `N` is echoed as written, and an empty +/// one has no colon after the message. No `M` with more than one member was +/// measured. +/// +/// When several values have a fault, the service names a value it cannot read +/// as one type ahead of a number fault in another value. `:u` with `{"N": +/// "bob"}` beside `:z` with `{"X": "1"}` names `:z` in 28 of 28 requests, and +/// twelve other shapes of `:z` beside that `:u` name `:z` too. Five shapes of +/// `:a` beside that `:u` name `:a`. So the values the service cannot read are +/// visited first, then the others, each group in placeholder order. Three +/// measured requests name another value than this order does. `:a` and `:b` +/// with numbers that are not numbers beside `:z` with `{"X": "1"}` name `:b`. +/// `:a` with `{"X": "1"}` beside `:b` with a null names `:b`, and `:a` with a +/// null beside `:b` with `{"X": "1"}` names `:b`. This order names `:z`, `:a` +/// and `:a` for them. +pub(super) fn unreadable_value_checks( + body: &Value, + values: &Map, +) -> Result<(), DynamoDbError> { + let mut violations: Vec = [ + enum_violation(body, "Select", "select", SELECT), + enum_violation( + body, + "ReturnConsumedCapacity", + "returnConsumedCapacity", + RETURN_CONSUMED_CAPACITY, + ), + ] + .into_iter() + .flatten() + .collect(); + if let Some(limit) = body.get("Limit").and_then(Value::as_i64) + && limit < 1 + { + violations.push(format!( + "Value '{limit}' at 'limit' failed to satisfy constraint: Member must have value \ + greater than or equal to 1" + )); + } + if !violations.is_empty() { + let count = violations.len(); + return Err(DynamoDbError::ValidationException(format!( + "{count} validation error{} detected: {}", + if count == 1 { "" } else { "s" }, + violations.join("; ") + ))); + } + + validate_no_parameter_mix(body)?; + + // The values the service cannot read first; the sort is stable, so each + // group keeps the placeholder order. + let mut entries = sorted_entries(values); + entries.sort_by_key(|(_, value)| !unreadable(value)); + for (key, value) in entries { + if let Some(fault) = first_fault(value, None) { + return Err(DynamoDbError::ValidationException(format!( + "ExpressionAttributeValues contains invalid value: {} for key {key}", + fault.reason() + ))); + } + } + Ok(()) +} + +/// The enum violation clause for `field` when the body holds a string that is +/// not one of `valid`. +fn enum_violation(body: &Value, field: &str, api_name: &str, valid: &[&str]) -> Option { + let value = body.get(field)?.as_str()?; + (!valid.contains(&value)).then(|| { + format!( + "Value '{value}' at '{api_name}' failed to satisfy constraint: Member must satisfy \ + enum value set: [{}]", + valid.join(", ") + ) + }) +} diff --git a/crates/engine/src/query_key_values/unreadable_tests.rs b/crates/engine/src/query_key_values/unreadable_tests.rs new file mode 100644 index 000000000..33f227062 --- /dev/null +++ b/crates/engine/src/query_key_values/unreadable_tests.rs @@ -0,0 +1,301 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Tests for a `Query` whose `ExpressionAttributeValues` holds a value the +//! service cannot read as one type. + +use extenddb_core::error::DynamoDbError; +use serde_json::{Value, json}; + +use super::tests::{body_with, message}; +use super::validate_query_request_body; + +const INVALID_VALUE: &str = "ExpressionAttributeValues contains invalid value: "; +const EMPTY: &str = + "Supplied AttributeValue is empty, must contain exactly one of the supported datatypes"; + +#[test] +fn a_value_the_service_cannot_read_as_one_type_is_named_with_its_placeholder() { + // Measured 2026-11-11, each value alone beside `:p = {"S": "x"}`. + let several = "Supplied AttributeValue has more than one datatypes set, must contain \ + exactly one of the supported datatypes"; + let null = "The supplied Item contains a null AttributeValue"; + for (value, reason) in [ + (json!({"X": "1"}), EMPTY.to_owned()), + (Value::Null, null.to_owned()), + (json!({}), EMPTY.to_owned()), + (json!({"S": "a", "N": "1"}), several.to_owned()), + (json!({"L": [{"X": "1"}]}), EMPTY.to_owned()), + (json!({"L": [null]}), null.to_owned()), + (json!({"L": [{}]}), EMPTY.to_owned()), + (json!({"L": [{"S": "a", "N": "1"}]}), several.to_owned()), + (json!({"L": [{"S": "a"}, {"X": "1"}]}), EMPTY.to_owned()), + (json!({"M": {"k": {"X": "1"}}}), EMPTY.to_owned()), + (json!({"M": {"k": {}}}), EMPTY.to_owned()), + (json!({"M": {"k": null}}), format!("{null}: k is null")), + ( + json!({"M": {"k": {"M": {"j": null}}}}), + format!("{null}: j is null"), + ), + (json!({"M": {"k": {"L": [null]}}}), null.to_owned()), + ( + json!({"L": [{"M": {"k": null}}]}), + format!("{null}: k is null"), + ), + // The first fault in document order. + ( + json!({"L": [{"N": "bob"}, {"X": "1"}]}), + "The parameter cannot be converted to a numeric value: bob".to_owned(), + ), + (json!({"L": [{"X": "1"}, {"N": "bob"}]}), EMPTY.to_owned()), + ] { + let body = body_with(json!({":p": {"S": "x"}, ":z": value}), json!({})); + assert_eq!( + message(validate_query_request_body(&body)), + Some(format!("{INVALID_VALUE}{reason} for key :z")), + "{value}" + ); + } +} + +#[test] +fn numbers_beside_a_value_the_service_cannot_read_are_wrapped_and_echoed_as_sent() { + // Measured 2026-11-11 beside `:a = {"S": "a", "X": "1"}`, which the service + // reads as an S: the numeric texts are wrapped with the placeholder, the + // value is echoed without folding its digits, an empty N has no colon, and + // a decimal digit below U+10000 still counts as a digit. + let numeric = "The parameter cannot be converted to a numeric value"; + for (value, reason) in [ + (json!({"N": "bob"}), format!("{numeric}: bob")), + (json!({"N": ""}), numeric.to_owned()), + (json!({"NS": ["1", "bob"]}), format!("{numeric}: bob")), + (json!({"L": [{"N": "bob"}]}), format!("{numeric}: bob")), + ( + json!({"N": "\u{ff11}bob"}), + format!("{numeric}: \u{ff11}bob"), + ), + (json!({"N": "\u{1d7cf}"}), format!("{numeric}: \u{1d7cf}")), + ( + json!({"N": "1e200"}), + "Number overflow. Attempting to store a number with magnitude larger than \ + supported range" + .to_owned(), + ), + ( + json!({"N": "1".repeat(39)}), + "Attempting to store more than 38 significant digits in a Number".to_owned(), + ), + ] { + let body = body_with( + json!({":p": {"S": "x"}, ":a": {"S": "a", "X": "1"}, ":u": value}), + json!({}), + ); + assert_eq!( + message(validate_query_request_body(&body)), + Some(format!("{INVALID_VALUE}{reason} for key :u")), + "{value}" + ); + } + let body = body_with( + json!({":p": {"S": "x"}, ":a": {"S": "a", "X": "1"}, ":u": {"N": "\u{ff11}"}}), + json!({}), + ); + assert!(validate_query_request_body(&body).is_ok()); +} + +#[test] +fn a_value_the_service_cannot_read_is_named_ahead_of_a_number_fault() { + // Measured 2026-11-11: beside `:u = {"N": "bob"}`, the service names `:z` + // or `:a` when it holds a value it cannot read as one type (28 of 28 + // requests for `:z = {"X": "1"}`), and names `:u` when the other value has + // no fault of its own. + let several = "Supplied AttributeValue has more than one datatypes set, must contain \ + exactly one of the supported datatypes"; + let null = "The supplied Item contains a null AttributeValue"; + let numeric = "The parameter cannot be converted to a numeric value: bob"; + for (value, reason) in [ + (json!({"X": "1"}), EMPTY.to_owned()), + (Value::Null, null.to_owned()), + (json!({}), EMPTY.to_owned()), + (json!({"S": "a", "N": "1"}), several.to_owned()), + (json!({"L": [{"X": "1"}]}), EMPTY.to_owned()), + (json!({"L": [null]}), null.to_owned()), + (json!({"L": [{}]}), EMPTY.to_owned()), + (json!({"L": [{"S": "a", "N": "1"}]}), several.to_owned()), + (json!({"M": {"k": {"X": "1"}}}), EMPTY.to_owned()), + (json!({"M": {"k": null}}), format!("{null}: k is null")), + (json!({"L": [{"S": "a"}, {"X": "1"}]}), EMPTY.to_owned()), + (json!({"L": [{"N": "bob"}, {"X": "1"}]}), numeric.to_owned()), + (json!({"L": [{"X": "1"}, {"N": "bob"}]}), EMPTY.to_owned()), + ] { + let body = body_with( + json!({":p": {"S": "x"}, ":u": {"N": "bob"}, ":z": value}), + json!({}), + ); + assert_eq!( + message(validate_query_request_body(&body)), + Some(format!("{INVALID_VALUE}{reason} for key :z")), + "{value}" + ); + } + for (value, reason) in [ + (json!({"X": "1"}), EMPTY), + (Value::Null, null), + (json!({}), EMPTY), + (json!({"S": "a", "N": "1"}), several), + (json!({"L": [{"X": "1"}]}), EMPTY), + ] { + let body = body_with( + json!({":p": {"S": "x"}, ":a": value, ":u": {"N": "bob"}}), + json!({}), + ); + assert_eq!( + message(validate_query_request_body(&body)), + Some(format!("{INVALID_VALUE}{reason} for key :a")), + "{value}" + ); + } + for values in [ + json!({":p": {"S": "x"}, ":u": {"N": "bob"}, ":z": {"S": "a", "X": "1"}}), + json!({":p": {"S": "x"}, ":a": {"S": "a", "X": "1"}, ":u": {"N": "bob"}}), + ] { + let body = body_with(values.clone(), json!({})); + assert_eq!( + message(validate_query_request_body(&body)), + Some(format!("{INVALID_VALUE}{numeric} for key :u")), + "{values}" + ); + } +} + +#[test] +fn beside_a_value_the_service_cannot_read_the_enums_and_limit_are_reported_together() { + // Measured 2026-11-11 beside `:z = {"X": "1"}`: Select, then + // ReturnConsumedCapacity, then Limit, in one message, ahead of the + // parameter mix; the mix ahead of the values. + let select = "Value 'bad' at 'select' failed to satisfy constraint: Member must satisfy \ + enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, \ + ALL_PROJECTED_ATTRIBUTES]"; + let rcc = "Value 'bad' at 'returnConsumedCapacity' failed to satisfy constraint: Member \ + must satisfy enum value set: [INDEXES, TOTAL, NONE]"; + let limit = |n: i64| { + format!( + "Value '{n}' at 'limit' failed to satisfy constraint: Member must have value \ + greater than or equal to 1" + ) + }; + let mix = "Can not use both expression and non-expression parameters in the same request: \ + Non-expression parameters: {AttributesToGet} Expression parameters: \ + {KeyConditionExpression}"; + let values = json!({":p": {"S": "x"}, ":u": {"N": "bob"}, ":z": {"X": "1"}}); + for (extra, expected) in [ + ( + json!({"Limit": 0}), + format!("1 validation error detected: {}", limit(0)), + ), + ( + json!({"Limit": -1}), + format!("1 validation error detected: {}", limit(-1)), + ), + ( + json!({"Select": "bad"}), + format!("1 validation error detected: {select}"), + ), + ( + json!({"ReturnConsumedCapacity": "bad"}), + format!("1 validation error detected: {rcc}"), + ), + ( + json!({"Limit": 0, "ReturnConsumedCapacity": "bad"}), + format!("2 validation errors detected: {rcc}; {}", limit(0)), + ), + ( + json!({"Limit": 0, "Select": "bad", "AttributesToGet": ["a"]}), + format!("2 validation errors detected: {select}; {}", limit(0)), + ), + ( + json!({"Limit": 0, "ReturnConsumedCapacity": "bad", "Select": "bad"}), + format!( + "3 validation errors detected: {select}; {rcc}; {}", + limit(0) + ), + ), + (json!({"AttributesToGet": ["a"]}), mix.to_owned()), + ] { + let body = body_with(values.clone(), extra.clone()); + assert_eq!( + message(validate_query_request_body(&body)), + Some(expected), + "{extra}" + ); + } + // A null value takes the same path. + let body = body_with( + json!({":p": {"S": "x"}, ":z": null}), + json!({"Limit": 0, "ReturnConsumedCapacity": "bad"}), + ); + assert_eq!( + message(validate_query_request_body(&body)), + Some(format!("2 validation errors detected: {rcc}; {}", limit(0))) + ); +} + +#[test] +fn a_shape_fault_is_still_reported_ahead_of_a_value_the_service_cannot_read() { + for extra in [ + json!({"Select": 5}), + json!({"ExpressionAttributeNames": "x"}), + ] { + for value in [json!({"X": "1"}), Value::Null] { + let body = body_with(json!({":p": {"S": "x"}, ":z": value}), extra.clone()); + assert!( + matches!( + validate_query_request_body(&body), + Err(DynamoDbError::SerializationException(_)) + ), + "{body}" + ); + } + } +} + +#[test] +fn a_json_type_fault_inside_a_value_the_service_cannot_read_is_a_shape_fault() { + // Measured 2026-11-11: each answers SerializationException. + for (values, extra) in [ + (json!({":z": {"L": [null, "x"]}}), json!({})), + (json!({":z": {"L": [{"X": "1"}, {"N": 5}]}}), json!({})), + (json!({":z": {"S": 5, "X": "1"}}), json!({"Limit": 0})), + (json!({":z": {"L": [null, {"B": "!!"}]}}), json!({})), + (json!({":z": {"S": 5, "N": "1"}}), json!({"Limit": 0})), + (json!({":z": {"L": [{"S": "a", "N": "1"}, "x"]}}), json!({})), + ( + json!({":a": {"S": "a", "N": "1"}, ":b": {"N": 5}}), + json!({}), + ), + (json!({":z": {"S": "a", "N": 1}}), json!({})), + ] { + let mut values = values; + values[":p"] = json!({"S": "x"}); + let body = body_with(values, extra); + assert!( + matches!( + validate_query_request_body(&body), + Err(DynamoDbError::SerializationException(_)) + ), + "{body}" + ); + } + // Two known descriptors with no JSON-type fault: the Limit text. + let body = body_with( + json!({":p": {"S": "x"}, ":z": {"S": "a", "N": "1"}}), + json!({"Limit": 0}), + ); + assert_eq!( + message(validate_query_request_body(&body)), + Some( + "1 validation error detected: Value '0' at 'limit' failed to satisfy constraint: \ + Member must have value greater than or equal to 1" + .to_owned() + ) + ); +} diff --git a/tests/test_query_key_value_types.py b/tests/test_query_key_value_types.py index 6db90cbd3..1d7b13a86 100644 --- a/tests/test_query_key_value_types.py +++ b/tests/test_query_key_value_types.py @@ -9,20 +9,22 @@ attribute's ``AttributeDefinitions`` type (``One or more parameter values were invalid: Condition parameter type does not match schema type``). Every expected answer below was measured against the service on 2026-10-24 (15:10, 21:00, -21:06 and 23:42 UTC), 2026-10-25 (11:31 UTC) and 2026-11-06 (the begins_with -rows after b20) on tables with S/S, S/N and B/B keys, a GSI and an LSI. A -Unicode decimal digit in an N value counts as the digit it stands for; a field -of the wrong JSON type anywhere in the body answers SerializationException -ahead of every check. +21:06 and 23:42 UTC), 2026-10-25 (11:31 UTC), 2026-11-06 (the begins_with +rows after b20) and 2026-11-11 (rows b48 to b50, f8, f9, g9 and g10, and the +digit runs) on tables with S/S, S/N and B/B keys, a GSI, an LSI and a GSI with +two HASH attributes. A Unicode decimal digit below U+10000 in an N value counts +as the digit it stands for. The rows also pin where the two checks fall against the other Query checks: -the numeric check after Limit, the expression parameter mix check and the -ReturnConsumedCapacity enum, and before the Select enum and the table lookup; -the type check after the key schema, filter, projection, unused value and -Select checks and before the ExclusiveStartKey check. +the numeric check after Limit, the ReturnConsumedCapacity enum and the +expression parameter mix check, and before the Select enum and the table +lookup; the type check after the key schema, filter, projection, unused value +and Select checks and before the ExclusiveStartKey check. Dual-target: runs against the service and against extenddb with the same -assertions. The LeadingKeys class needs the extenddb management API and is -skipped against the service. +assertions. test_query_value_shapes.py holds the bodies of the wrong JSON +shape and the values the service cannot read as one type, and +test_query_leading_keys_values.py the LeadingKeys fences, which need the +extenddb management API. Run: EXTENDDB_TEST_ENDPOINT=https://localhost:18443 \\ @@ -32,16 +34,10 @@ from __future__ import annotations -import os -import uuid -from typing import Any - -import boto3 import pytest -from botocore.config import Config as BotoConfig from botocore.exceptions import ClientError -from conftest import scoped_table, wait_for_active +from conftest import scoped_table NUMERIC = "The parameter cannot be converted to a numeric value: " TYPE_MISMATCH = ( @@ -144,6 +140,31 @@ def bb_table(dynamodb_client): yield name +@pytest.fixture(scope="module") +def mp_table(dynamodb_client): + """pk S; GSI mpi with HASH h1 S and h2 N, RANGE r S.""" + with scoped_table( + dynamodb_client, + attribute_definitions=[ + {"AttributeName": "pk", **S}, + {"AttributeName": "h1", **S}, + {"AttributeName": "h2", "AttributeType": "N"}, + {"AttributeName": "r", **S}, + ], + key_schema=[{"AttributeName": "pk", "KeyType": "HASH"}], + GlobalSecondaryIndexes=[{ + "IndexName": "mpi", + "KeySchema": [ + {"AttributeName": "h1", "KeyType": "HASH"}, + {"AttributeName": "h2", "KeyType": "HASH"}, + {"AttributeName": "r", "KeyType": "RANGE"}, + ], + "Projection": {"ProjectionType": "ALL"}, + }], + ) as name: + yield name + + NB = {"N": "bob"} N5 = {"N": "5"} SX = {"S": "x"} @@ -207,6 +228,32 @@ def bb_table(dynamodb_client): ) V = "ValidationException" RNF = "ResourceNotFoundException" +LEGACY_PK_N5 = {"pk": {"ComparisonOperator": "EQ", "AttributeValueList": [N5]}} +MISSED_R = "Query condition missed key schema element: r" +# Digit one of every decimal digit (category Nd) run in Unicode 15.0: the +# service accepts the 36 runs below U+10000 outside ASCII and refuses the 31 +# runs from U+104A0 up (measured 2026-11-11, each twice). +BMP_ONES = [chr(zero + 1) for zero in ( + 0x0660, 0x06F0, 0x07C0, 0x0966, 0x09E6, 0x0A66, 0x0AE6, 0x0B66, 0x0BE6, 0x0C66, 0x0CE6, + 0x0D66, 0x0DE6, 0x0E50, 0x0ED0, 0x0F20, 0x1040, 0x1090, 0x17E0, 0x1810, 0x1946, 0x19D0, + 0x1A80, 0x1A90, 0x1B50, 0x1BB0, 0x1C40, 0x1C50, 0xA620, 0xA8D0, 0xA900, 0xA9D0, 0xA9F0, + 0xAA50, 0xABF0, 0xFF10)] +HIGH_ONES = [chr(zero + 1) for zero in ( + 0x104A0, 0x10D30, 0x11066, 0x110F0, 0x11136, 0x111D0, 0x112F0, 0x11450, 0x114D0, 0x11650, + 0x116C0, 0x11730, 0x118E0, 0x11950, 0x11C50, 0x11D50, 0x11DA0, 0x11F50, 0x16A60, 0x16AC0, + 0x16B50, 0x1D7CE, 0x1D7D8, 0x1D7E2, 0x1D7EC, 0x1D7F6, 0x1E140, 0x1E2F0, 0x1E4F0, 0x1E950, + 0x1FBF0)] +# A refused value is echoed with each decimal digit below U+10000 folded. +FOLDED_ECHOES = [ + ("\uff11bob", "1bob"), ("\u0661\u0662x", "12x"), ("bob\uff11", "bob1"), + ("\u0967\u0968a\u0969", "12a3"), ("\uff11\U0001d7cf", "1\U0001d7cf"), +] +MIXES = { + "AttributesToGet": {"AttributesToGet": ["a"]}, + "QueryFilter": {"QueryFilter": {"a": {"ComparisonOperator": "EQ", "AttributeValueList": [SX]}}}, + "ConditionalOperator": {"ConditionalOperator": "AND"}, + "KeyConditions": {"KeyConditions": LEGACY_PK}, +} def kce(expr, values, **extra): @@ -433,6 +480,36 @@ def kce(expr, values, **extra): ("pk = BOOL", "ss", kce("pk = :u", {":u": {"BOOL": True}}), V, TYPE_MISMATCH), ("pk = N bob AND pk > S alice", "ss", kce("pk = :u AND pk > :v", {":u": NB, ":v": {"S": "alice"}}), V, NUMERIC + "bob"), + # An invalid ReturnConsumedCapacity is reported ahead of each + # non-expression parameter beside KeyConditionExpression, and the mix + # ahead of the numbers (measured 2026-11-11). + *[(f"f8 invalid ReturnConsumedCapacity with {name}", "ss", + kce("pk = :u", {":u": NB}, ReturnConsumedCapacity="bad", **extra), V, RCC_MSG) + for name, extra in MIXES.items()], + *[(f"f9 {name} with N bob", "ss", kce("pk = :u", {":u": NB}, **extra), V, + "Can not use both expression and non-expression parameters in the same request: " + f"Non-expression parameters: {{{name}}} Expression parameters: {{KeyConditionExpression}}") + for name, extra in MIXES.items() if name != "KeyConditions"], + # A refused value is echoed with its decimal digits folded to ASCII, and a + # digit from U+104A0 up is not a digit (measured 2026-11-11). + *[(f"g9 {raw!r} echoed with ASCII digits", "ns", + kce("pk = :u AND sk = :s", {":u": CAROL, ":s": {"N": "1"}, ":f": {"N": raw}}), + V, NUMERIC + echo) + for raw, echo in FOLDED_ECHOES], + *[(f"g10 U+{ord(one):X} in filter", "ns", + kce("pk = :u AND sk = :s", {":u": CAROL, ":s": {"N": "1"}, ":f": {"N": one}}, + FilterExpression="a = :f"), V, NUMERIC + one) + for one in HIGH_ONES], + # Legacy KeyConditions, and a key schema with two HASH attributes, where + # the type is reported ahead of the clause on a non-key attribute + # (measured 2026-11-11). + ("b48 legacy KeyConditions pk EQ N 5", "ss", {"KeyConditions": LEGACY_PK_N5}, V, TYPE_MISMATCH), + ("b49 two HASH attributes, h2 = S beside a non-key clause", "mp", + kce("h1 = :a AND h2 = :b AND z = :c", {":a": SX, ":b": {"S": "1"}, ":c": SX}, + IndexName="mpi"), V, TYPE_MISMATCH), + ("b50 two HASH attributes, h2 = N beside a non-key clause", "mp", + kce("h1 = :a AND h2 = :b AND z = :c", {":a": SX, ":b": {"N": "1"}, ":c": SX}, + IndexName="mpi"), V, MISSED_R), ] @@ -440,8 +517,8 @@ class TestKeyConditionValueTypes: """Each row: a Query and the service's answer.""" @pytest.fixture - def tables(self, ss_table, ns_table, bb_table): - return {"ss": ss_table, "ns": ns_table, "bb": bb_table, "missing": MISSING} + def tables(self, ss_table, ns_table, bb_table, mp_table): + return {"ss": ss_table, "ns": ns_table, "bb": bb_table, "mp": mp_table, "missing": MISSING} @pytest.mark.parametrize("row,table,kwargs,code,expected", ROWS, ids=[r[0] for r in ROWS]) def test_rows(self, dynamodb_client_no_validation, tables, row, table, kwargs, code, expected): @@ -500,216 +577,10 @@ def test_fullwidth_digit_in_a_number_set_passes_the_check(self, dynamodb_client, ExpressionAttributeValues={":u": CAROL, ":s": {"N": "1"}, ":f": {"NS": [FW_ONE]}}) assert (resp["Count"], resp["ScannedCount"]) == (0, 1) - -def _raw_query(client, body: dict): - """POST ``body`` as the Query JSON exactly as written, signed with the - client's credentials, so a field of the wrong JSON type reaches the server - (boto3 would refuse or reshape it).""" - import json - - from botocore.awsrequest import AWSRequest - - req = AWSRequest(method="POST", url=client.meta.endpoint_url, data=json.dumps(body), - headers={"Content-Type": "application/x-amz-json-1.0", - "X-Amz-Target": "DynamoDB_20120810.Query"}) - client._request_signer.sign("Query", req) - resp = client._endpoint.http_session.send(req.prepare()) - return resp.status_code, json.loads(resp.content.decode("utf-8", "replace") or "{}") - - -SHAPE_FAULTS = [ - ("Limit 0 with ExpressionAttributeValues string", - {"KeyConditionExpression": "pk = :p", "Limit": 0, "ExpressionAttributeValues": "x"}), - ("ExpressionAttributeNames string with N bob", - {"KeyConditionExpression": "pk = :p", "ExpressionAttributeNames": "x", - "ExpressionAttributeValues": {":p": NB}}), - ("Limit string with N bob", - {"KeyConditionExpression": "pk = :p", "Limit": "1", "ExpressionAttributeValues": {":p": NB}}), - ("AttributesToGet object with ProjectionExpression", - {"KeyConditionExpression": "pk = :p", "AttributesToGet": {"a": 1}, "ProjectionExpression": "a", - "ExpressionAttributeValues": {":p": SX}}), - ("QueryFilter array with FilterExpression", - {"KeyConditionExpression": "pk = :p", "QueryFilter": [1], "FilterExpression": "a = :p", - "ExpressionAttributeValues": {":p": SX}}), - ("Select number with N bob", - {"KeyConditionExpression": "pk = :p", "Select": 5, "ExpressionAttributeValues": {":p": NB}}), - ("Limit 0 with Select number", - {"KeyConditionExpression": "pk = :p", "Limit": 0, "Select": 5, - "ExpressionAttributeValues": {":p": SX}}), -] - - -class TestShapeFaultsAreReportedFirst: - """A field of the wrong JSON type anywhere in the body answers - SerializationException ahead of the Limit, parameter mix, enum and number - checks (measured 2026-10-25 11:31 UTC). The message texts differ between - the service and extenddb, so only the error type is asserted.""" - - @pytest.mark.parametrize("row,body", SHAPE_FAULTS, ids=[r[0] for r in SHAPE_FAULTS]) - def test_rows(self, dynamodb_client, ss_table, row, body): - status, payload = _raw_query(dynamodb_client, {"TableName": ss_table, **body}) - assert status == 400 - assert payload.get("__type", "").endswith("SerializationException"), payload - - def test_control_without_a_shape_fault_answers_the_check(self, dynamodb_client, ss_table): - status, payload = _raw_query(dynamodb_client, { - "TableName": ss_table, "KeyConditionExpression": "pk = :p", "Limit": 0, - "ExpressionAttributeValues": {":p": NB}}) - assert status == 400 - assert payload.get("__type", "").endswith("ValidationException") - assert payload.get("message", payload.get("Message")) == LIMIT_MSG - - -class TestLeadingKeysWithAnInvalidKeyValue: - """A principal under each LeadingKeys fence form gets ValidationException and - no items for a Query whose ExpressionAttributeValues carries an N value that - is not a number, whether the key condition, the filter or nothing reads it. - - extenddb only: the fences need users created through the management API.""" - - @pytest.fixture(autouse=True) - def setup(self): - endpoint = os.environ.get("EXTENDDB_TEST_ENDPOINT", "").strip() - admin_user = os.environ.get("EXTENDDB_ADMIN_USER", "").strip() - admin_pass = os.environ.get("EXTENDDB_ADMIN_PASSWORD", "").strip() - if not endpoint: - pytest.skip("LeadingKeys fences need the extenddb management API") - if not admin_user or not admin_pass: - pytest.fail("MISCONFIGURED: EXTENDDB_ADMIN_USER and EXTENDDB_ADMIN_PASSWORD are required") - from management_helpers import ManagementClient - - self.endpoint = endpoint - self.region = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") - self.mgmt = ManagementClient(endpoint, admin_user, admin_pass) - self.account_id = f"{uuid.uuid4().int % 10**12:012d}" - resp = self.mgmt.create_account(self.account_id, f"kv-test-{self.account_id}") - assert resp.status_code == 201, resp.text - self._users: list[str] = [] - yield - for u in self._users: - try: - self.mgmt.delete_user(self.account_id, u) - except Exception: - pass - self.mgmt.delete_account(self.account_id) - - def _client(self, policy: dict | None) -> Any: - name = f"kv-{uuid.uuid4().hex[:8]}" - resp = self.mgmt.create_user(self.account_id, name, "TestPass123!") - assert resp.status_code == 201, resp.text - self._users.append(name) - resp = self.mgmt.create_access_key(self.account_id, name) - assert resp.status_code == 201, resp.text - creds = resp.json() - if policy is not None: - resp = self.mgmt.put_user_policy(self.account_id, name, "p", policy) - assert resp.status_code == 204, resp.text - return boto3.client( - "dynamodb", endpoint_url=self.endpoint, region_name=self.region, - aws_access_key_id=creds["access_key_id"], - aws_secret_access_key=creds["secret_access_key"], - verify=False, - config=BotoConfig(retries={"max_attempts": 0}, parameter_validation=False)) - - def _fence(self, condition: dict, table: str) -> dict: - arn = f"arn:aws:dynamodb:{self.region}:{self.account_id}:table/{table}" - return { - "Version": "2012-10-17", - "Statement": [{ - "Effect": "Allow", - "Action": "dynamodb:*", - "Resource": [arn, arn + "/index/*"], - "Condition": condition, - }], - } - - def test_every_fence_form_gets_validation_exception_and_no_items(self): - owner = self._client({ - "Version": "2012-10-17", - "Statement": [{"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"}], - }) - table = f"kv-{uuid.uuid4().hex[:8]}" - owner.create_table( - TableName=table, - AttributeDefinitions=[{"AttributeName": "pk", **S}], - KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}], - BillingMode="PAY_PER_REQUEST") - wait_for_active(owner, table) - for pk in ("alice", "bob"): - owner.put_item(TableName=table, Item={"pk": {"S": pk}}) - - fences = { - "ForAllValues": {"ForAllValues:StringEquals": {"dynamodb:LeadingKeys": ["alice"]}}, - "ForAnyValue": {"ForAnyValue:StringEquals": {"dynamodb:LeadingKeys": ["alice"]}}, - "Null false": {"Null": {"dynamodb:LeadingKeys": "false"}, - "ForAllValues:StringEquals": {"dynamodb:LeadingKeys": ["alice"]}}, - "StringEquals": {"StringEquals": {"dynamodb:LeadingKeys": "alice"}}, - "StringLike": {"StringLike": {"dynamodb:LeadingKeys": "ali*"}}, - "StringNotEquals": {"StringNotEquals": {"dynamodb:LeadingKeys": "bob"}}, - } - # The reported shape, and an N value that only the filter reads or - # nothing reads beside a key value the fence would bind. - requests = { - "pk = N bob": {"TableName": table, "KeyConditionExpression": "pk = :u", - "ExpressionAttributeValues": {":u": NB}}, - "pk = S alice, N bob in filter": { - "TableName": table, "KeyConditionExpression": "pk = :u", - "FilterExpression": "a = :n", - "ExpressionAttributeValues": {":u": {"S": "alice"}, ":n": NB}}, - "pk = S bob, N bob unused": { - "TableName": table, "KeyConditionExpression": "pk = :u", - "ExpressionAttributeValues": {":u": {"S": "bob"}, ":n": NB}}, - "pk = N bob, invalid Select": { - "TableName": table, "KeyConditionExpression": "pk = :u", - "ExpressionAttributeValues": {":u": NB}, "Select": "bad"}, - } - failures = [] - clients = {label: self._client(self._fence(condition, table)) - for label, condition in fences.items()} - clients["owner"] = owner - for shape, request in requests.items(): - for label, client in clients.items(): - try: - resp = client.query(**request) - failures.append(f"{shape} / {label}: {resp['Count']} items returned") - except ClientError as exc: - err = exc.response["Error"] - if (err["Code"], err["Message"]) != ("ValidationException", NUMERIC + "bob"): - failures.append(f"{shape} / {label}: {err['Code']} {err['Message']}") - owner.delete_table(TableName=table) - assert not failures, "\n".join(failures) - - def test_a_unicode_digit_key_value_reads_no_fenced_partition(self): - """A partition key value written with Unicode digits is not bound to a - LeadingKeys value, so it must not read a partition the fence keeps the - principal from. The service's answer for a fenced principal cannot be - measured here; the test asserts only that no item of partition 20 is - returned, whatever the answer is.""" - owner = self._client({ - "Version": "2012-10-17", - "Statement": [{"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"}], - }) - table = f"kv-{uuid.uuid4().hex[:8]}" - owner.create_table( - TableName=table, - AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "N"}], - KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}], - BillingMode="PAY_PER_REQUEST") - wait_for_active(owner, table) - for pk in ("10", "20"): - owner.put_item(TableName=table, Item={"pk": {"N": pk}, "v": {"S": "p" + pk}}) - fenced = self._client(self._fence( - {"ForAllValues:StringEquals": {"dynamodb:LeadingKeys": ["10"]}}, table)) - leaks = [] - for label, value in (("fullwidth", "\uff12\uff10"), ("arabic-indic", "\u0662\u0660"), - ("devanagari", "\u0968\u0966")): - try: - resp = fenced.query( - TableName=table, KeyConditionExpression="pk = :p", - ExpressionAttributeValues={":p": {"N": value}}) - except ClientError: - continue - if any(item.get("v") == {"S": "p20"} for item in resp["Items"]): - leaks.append(label) - owner.delete_table(TableName=table) - assert not leaks, leaks + @pytest.mark.parametrize("one", BMP_ONES, ids=[f"U+{ord(one):04X}" for one in BMP_ONES]) + def test_digit_one_of_every_run_below_u_10000_is_accepted(self, dynamodb_client, ns_table, one): + resp = dynamodb_client.query( + TableName=ns_table, KeyConditionExpression="pk = :u AND sk = :s", + FilterExpression="a = :f", + ExpressionAttributeValues={":u": CAROL, ":s": {"N": "1"}, ":f": {"N": one}}) + assert resp["ScannedCount"] == 1 diff --git a/tests/test_query_leading_keys_values.py b/tests/test_query_leading_keys_values.py new file mode 100644 index 000000000..5c0524de2 --- /dev/null +++ b/tests/test_query_leading_keys_values.py @@ -0,0 +1,182 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Query under each dynamodb:LeadingKeys fence form with an N value that is +not a number. The fences need users created through the extenddb management +API, so this file is skipped against the service. + +Run: + EXTENDDB_TEST_ENDPOINT=https://localhost:18443 \\ + EXTENDDB_ADMIN_USER=admin EXTENDDB_ADMIN_PASSWORD= \\ + pytest tests/test_query_leading_keys_values.py -v +""" + +from __future__ import annotations + +import os +import uuid +from typing import Any + +import boto3 +import pytest +from botocore.config import Config as BotoConfig +from botocore.exceptions import ClientError + +from conftest import scoped_table +from test_query_key_value_types import NB, NUMERIC +from test_query_value_shapes import EMPTY_AV, INVALID_VALUE, X1, _raw_query + + +class TestLeadingKeysWithAnInvalidKeyValue: + """A principal under each LeadingKeys fence form gets ValidationException and + no items for a Query whose ExpressionAttributeValues carries an N value that + is not a number, whether the key condition, the filter or nothing reads it. + + extenddb only: the fences need users created through the management API.""" + + @pytest.fixture(autouse=True) + def setup(self): + endpoint = os.environ.get("EXTENDDB_TEST_ENDPOINT", "").strip() + admin_user = os.environ.get("EXTENDDB_ADMIN_USER", "").strip() + admin_pass = os.environ.get("EXTENDDB_ADMIN_PASSWORD", "").strip() + if not endpoint: + pytest.skip("LeadingKeys fences need the extenddb management API") + if not admin_user or not admin_pass: + pytest.fail("MISCONFIGURED: EXTENDDB_ADMIN_USER and EXTENDDB_ADMIN_PASSWORD are required") + from management_helpers import ManagementClient + + self.endpoint = endpoint + self.region = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") + self.mgmt = ManagementClient(endpoint, admin_user, admin_pass) + self.account_id = f"{uuid.uuid4().int % 10**12:012d}" + resp = self.mgmt.create_account(self.account_id, f"kv-test-{self.account_id}") + assert resp.status_code == 201, resp.text + self._users: list[str] = [] + yield + for u in self._users: + try: + self.mgmt.delete_user(self.account_id, u) + except Exception: + pass + self.mgmt.delete_account(self.account_id) + + def _client(self, policy: dict | None) -> Any: + name = f"kv-{uuid.uuid4().hex[:8]}" + resp = self.mgmt.create_user(self.account_id, name, "TestPass123!") + assert resp.status_code == 201, resp.text + self._users.append(name) + resp = self.mgmt.create_access_key(self.account_id, name) + assert resp.status_code == 201, resp.text + creds = resp.json() + if policy is not None: + resp = self.mgmt.put_user_policy(self.account_id, name, "p", policy) + assert resp.status_code == 204, resp.text + return boto3.client( + "dynamodb", endpoint_url=self.endpoint, region_name=self.region, + aws_access_key_id=creds["access_key_id"], + aws_secret_access_key=creds["secret_access_key"], + verify=False, + config=BotoConfig(retries={"max_attempts": 0}, parameter_validation=False)) + + def _fence(self, condition: dict, table: str) -> dict: + arn = f"arn:aws:dynamodb:{self.region}:{self.account_id}:table/{table}" + return { + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Allow", + "Action": "dynamodb:*", + "Resource": [arn, arn + "/index/*"], + "Condition": condition, + }], + } + + def test_every_fence_form_gets_validation_exception_and_no_items(self): + owner = self._client({ + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"}], + }) + failures = [] + with scoped_table(owner) as table: + for pk in ("alice", "bob"): + owner.put_item(TableName=table, Item={"pk": {"S": pk}}) + + fences = { + "ForAllValues": {"ForAllValues:StringEquals": {"dynamodb:LeadingKeys": ["alice"]}}, + "ForAnyValue": {"ForAnyValue:StringEquals": {"dynamodb:LeadingKeys": ["alice"]}}, + "Null false": {"Null": {"dynamodb:LeadingKeys": "false"}, + "ForAllValues:StringEquals": {"dynamodb:LeadingKeys": ["alice"]}}, + "StringEquals": {"StringEquals": {"dynamodb:LeadingKeys": "alice"}}, + "StringLike": {"StringLike": {"dynamodb:LeadingKeys": "ali*"}}, + "StringNotEquals": {"StringNotEquals": {"dynamodb:LeadingKeys": "bob"}}, + } + # The reported shape, and an N value that only the filter reads or + # nothing reads beside a key value the fence would bind. + requests = { + "pk = N bob": {"TableName": table, "KeyConditionExpression": "pk = :u", + "ExpressionAttributeValues": {":u": NB}}, + "pk = S alice, N bob in filter": { + "TableName": table, "KeyConditionExpression": "pk = :u", + "FilterExpression": "a = :n", + "ExpressionAttributeValues": {":u": {"S": "alice"}, ":n": NB}}, + "pk = S bob, N bob unused": { + "TableName": table, "KeyConditionExpression": "pk = :u", + "ExpressionAttributeValues": {":u": {"S": "bob"}, ":n": NB}}, + "pk = N bob, invalid Select": { + "TableName": table, "KeyConditionExpression": "pk = :u", + "ExpressionAttributeValues": {":u": NB}, "Select": "bad"}, + } + clients = {label: self._client(self._fence(condition, table)) + for label, condition in fences.items()} + clients["owner"] = owner + for shape, request in requests.items(): + for label, client in clients.items(): + try: + resp = client.query(**request) + failures.append(f"{shape} / {label}: {resp['Count']} items returned") + except ClientError as exc: + err = exc.response["Error"] + if (err["Code"], err["Message"]) != ("ValidationException", NUMERIC + "bob"): + failures.append(f"{shape} / {label}: {err['Code']} {err['Message']}") + # Beside a value with an unknown type descriptor, which boto3 cannot + # send, every principal gets the ValidationException that names + # :z. The service names :z for the owner (measured 2026-11-11). Its + # answer for a fenced principal was not measured. + body = {"TableName": table, "KeyConditionExpression": "pk = :u", + "ExpressionAttributeValues": {":u": NB, ":z": X1}} + expected = INVALID_VALUE + EMPTY_AV + " for key :z" + for label, client in clients.items(): + status, payload = _raw_query(client, body) + kind = payload.get("__type", "").rsplit("#", 1)[-1] + msg = payload.get("message", payload.get("Message")) + if (status, kind, msg) != (400, "ValidationException", expected): + failures.append(f"N bob beside X / {label}: {status} {kind} {msg}") + assert not failures, "\n".join(failures) + + def test_a_unicode_digit_key_value_reads_no_fenced_partition(self): + """A partition key value written with Unicode digits is not bound to a + LeadingKeys value, so it must not read a partition the fence keeps the + principal from. The service's answer for a fenced principal cannot be + measured here; the test asserts only that no item of partition 20 is + returned, whatever the answer is.""" + owner = self._client({ + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"}], + }) + leaks = [] + with scoped_table(owner, attribute_definitions=[ + {"AttributeName": "pk", "AttributeType": "N"}]) as table: + for pk in ("10", "20"): + owner.put_item(TableName=table, Item={"pk": {"N": pk}, "v": {"S": "p" + pk}}) + fenced = self._client(self._fence( + {"ForAllValues:StringEquals": {"dynamodb:LeadingKeys": ["10"]}}, table)) + for label, value in (("fullwidth", "\uff12\uff10"), ("arabic-indic", "\u0662\u0660"), + ("devanagari", "\u0968\u0966")): + try: + resp = fenced.query( + TableName=table, KeyConditionExpression="pk = :p", + ExpressionAttributeValues={":p": {"N": value}}) + except ClientError: + continue + if any(item.get("v") == {"S": "p20"} for item in resp["Items"]): + leaks.append(label) + assert not leaks, leaks diff --git a/tests/test_query_value_shapes.py b/tests/test_query_value_shapes.py new file mode 100644 index 000000000..ebf71678c --- /dev/null +++ b/tests/test_query_value_shapes.py @@ -0,0 +1,174 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Query request bodies the service does not read as written: a field of the +wrong JSON type, and an ExpressionAttributeValues value the service cannot +read as one type. boto3 refuses or reshapes these bodies, so they go out as +written. Every expected answer below was measured against the service on +2026-10-25 (11:31 UTC) and 2026-11-11. + +Dual-target: runs against the service and against extenddb with the same +assertions. + +Run: + EXTENDDB_TEST_ENDPOINT=https://localhost:18443 \\ + EXTENDDB_ADMIN_USER=admin EXTENDDB_ADMIN_PASSWORD= \\ + pytest tests/test_query_value_shapes.py -v +""" + +from __future__ import annotations + +import pytest + +from test_query_key_value_types import ( # noqa: F401 (ss_table is a fixture) + LIMIT_MSG, + NB, + NUMERIC, + RCC_MSG, + SX, + ss_table, +) + + +def _raw_query(client, body: dict): + """POST ``body`` as the Query JSON exactly as written, signed with the + client's credentials, so a field of the wrong JSON type reaches the server + (boto3 would refuse or reshape it).""" + import json + + from botocore.awsrequest import AWSRequest + + req = AWSRequest(method="POST", url=client.meta.endpoint_url, data=json.dumps(body), + headers={"Content-Type": "application/x-amz-json-1.0", + "X-Amz-Target": "DynamoDB_20120810.Query"}) + client._request_signer.sign("Query", req) + resp = client._endpoint.http_session.send(req.prepare()) + return resp.status_code, json.loads(resp.content.decode("utf-8", "replace") or "{}") + + +SHAPE_FAULTS = [ + ("Limit 0 with ExpressionAttributeValues string", + {"KeyConditionExpression": "pk = :p", "Limit": 0, "ExpressionAttributeValues": "x"}), + ("ExpressionAttributeNames string with N bob", + {"KeyConditionExpression": "pk = :p", "ExpressionAttributeNames": "x", + "ExpressionAttributeValues": {":p": NB}}), + ("Limit string with N bob", + {"KeyConditionExpression": "pk = :p", "Limit": "1", "ExpressionAttributeValues": {":p": NB}}), + ("AttributesToGet object with ProjectionExpression", + {"KeyConditionExpression": "pk = :p", "AttributesToGet": {"a": 1}, "ProjectionExpression": "a", + "ExpressionAttributeValues": {":p": SX}}), + ("QueryFilter array with FilterExpression", + {"KeyConditionExpression": "pk = :p", "QueryFilter": [1], "FilterExpression": "a = :p", + "ExpressionAttributeValues": {":p": SX}}), + ("Select number with N bob", + {"KeyConditionExpression": "pk = :p", "Select": 5, "ExpressionAttributeValues": {":p": NB}}), + ("Limit 0 with Select number", + {"KeyConditionExpression": "pk = :p", "Limit": 0, "Select": 5, + "ExpressionAttributeValues": {":p": SX}}), + # A field of the wrong JSON type inside a value the service cannot read as + # one type (measured 2026-11-11). + ("string beside a null in an L", + {"KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": {":p": SX, ":z": {"L": [None, "x"]}}}), + ("N number beside an unknown descriptor in an L", + {"KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": {":p": SX, ":z": {"L": [{"X": "1"}, {"N": 5}]}}}), + ("S number beside an unknown descriptor with Limit 0", + {"KeyConditionExpression": "pk = :p", "Limit": 0, + "ExpressionAttributeValues": {":p": SX, ":z": {"S": 5, "X": "1"}}}), + ("B not base64 beside a null in an L", + {"KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": {":p": SX, ":z": {"L": [None, {"B": "!!"}]}}}), +] + + +class TestShapeFaultsAreReportedFirst: + """A field of the wrong JSON type anywhere in the body answers + SerializationException ahead of the Limit, parameter mix, enum and number + checks (measured 2026-10-25 11:31 UTC). The message texts differ between + the service and extenddb, so only the error type is asserted.""" + + @pytest.mark.parametrize("row,body", SHAPE_FAULTS, ids=[r[0] for r in SHAPE_FAULTS]) + def test_rows(self, dynamodb_client, ss_table, row, body): + status, payload = _raw_query(dynamodb_client, {"TableName": ss_table, **body}) + assert status == 400 + assert payload.get("__type", "").endswith("SerializationException"), payload + + def test_control_without_a_shape_fault_answers_the_check(self, dynamodb_client, ss_table): + status, payload = _raw_query(dynamodb_client, { + "TableName": ss_table, "KeyConditionExpression": "pk = :p", "Limit": 0, + "ExpressionAttributeValues": {":p": NB}}) + assert status == 400 + assert payload.get("__type", "").endswith("ValidationException") + assert payload.get("message", payload.get("Message")) == LIMIT_MSG + + +INVALID_VALUE = "ExpressionAttributeValues contains invalid value: " +EMPTY_AV = "Supplied AttributeValue is empty, must contain exactly one of the supported datatypes" +NULL_AV = "The supplied Item contains a null AttributeValue" +SEVERAL_AV = ("Supplied AttributeValue has more than one datatypes set, must contain exactly " + "one of the supported datatypes") +X1 = {"X": "1"} +# An S with an unknown descriptor beside it, which the service reads as an S. +S_PLUS_X = {"S": "a", "X": "1"} +LIMIT_0_AT = ("Value '0' at 'limit' failed to satisfy constraint: " + "Member must have value greater than or equal to 1") + +# (row, values beside :p, other fields, the service's message). +UNREADABLE = [ + ("unknown descriptor", {":z": X1}, {}, INVALID_VALUE + EMPTY_AV + " for key :z"), + ("null", {":z": None}, {}, INVALID_VALUE + NULL_AV + " for key :z"), + ("no descriptor", {":z": {}}, {}, INVALID_VALUE + EMPTY_AV + " for key :z"), + ("two descriptors", {":z": {"S": "a", "N": "1"}}, {}, INVALID_VALUE + SEVERAL_AV + " for key :z"), + ("unknown descriptor in an L", {":z": {"L": [X1]}}, {}, INVALID_VALUE + EMPTY_AV + " for key :z"), + ("null M member", {":z": {"M": {"k": None}}}, {}, + INVALID_VALUE + NULL_AV + ": k is null for key :z"), + ("N bob beside S plus X", {":a": S_PLUS_X, ":u": NB}, {}, INVALID_VALUE + NUMERIC + "bob for key :u"), + ("empty N beside S plus X", {":a": S_PLUS_X, ":u": {"N": ""}}, {}, + INVALID_VALUE + "The parameter cannot be converted to a numeric value for key :u"), + ("fullwidth one bob beside S plus X", {":a": S_PLUS_X, ":u": {"N": "\uff11bob"}}, {}, + INVALID_VALUE + NUMERIC + "\uff11bob for key :u"), + ("Limit 0", {":z": X1}, {"Limit": 0}, "1 validation error detected: " + LIMIT_0_AT), + ("Limit 0 beside null", {":z": None}, {"Limit": 0}, "1 validation error detected: " + LIMIT_0_AT), + ("Limit 0 and ReturnConsumedCapacity", {":z": X1}, {"Limit": 0, "ReturnConsumedCapacity": "bad"}, + "2 validation errors detected: " + RCC_MSG.removeprefix("1 validation error detected: ") + + "; " + LIMIT_0_AT), + ("invalid Select", {":z": X1, ":u": NB}, {"Select": "bad"}, + "1 validation error detected: Value 'bad' at 'select' failed to satisfy constraint: Member " + "must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, " + "ALL_PROJECTED_ATTRIBUTES]"), + ("AttributesToGet", {":z": X1, ":u": NB}, {"AttributesToGet": ["a"]}, + "Can not use both expression and non-expression parameters in the same request: " + "Non-expression parameters: {AttributesToGet} Expression parameters: {KeyConditionExpression}"), +] + + +class TestValuesTheServiceCannotReadAsOneType: + """A value in ExpressionAttributeValues that the service cannot read as one + type (a null, no type descriptor it knows, more than one, or an unknown one + beside a known one) is named with its placeholder, and beside such a value + Select, ReturnConsumedCapacity and Limit are reported together, ahead of + the parameter mix (measured 2026-11-11). boto3 cannot send an unknown + descriptor or a null, so the bodies go out as written.""" + + @pytest.mark.parametrize("row,values,extra,expected", UNREADABLE, ids=[r[0] for r in UNREADABLE]) + def test_rows(self, dynamodb_client, ss_table, row, values, extra, expected): + status, payload = _raw_query(dynamodb_client, { + "TableName": ss_table, "KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": {":p": SX, **values}, **extra}) + assert status == 400, payload + assert payload.get("__type", "").endswith("ValidationException"), payload + assert payload.get("message", payload.get("Message")) == expected + + def test_the_value_the_service_cannot_read_is_named_beside_n_bob(self, dynamodb_client, + ss_table): + """A value the service cannot read as one type is named ahead of a + number fault in another value: :z for this body on 28 of 28 requests + (measured 2026-11-11).""" + status, payload = _raw_query(dynamodb_client, { + "TableName": ss_table, "KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": {":p": SX, ":u": NB, ":z": X1}}) + assert status == 400, payload + assert payload.get("__type", "").endswith("ValidationException"), payload + assert payload.get("message", payload.get("Message")) == ( + INVALID_VALUE + EMPTY_AV + " for key :z") From 54150fe9cf086cbeb9a408630495770e15c65e4d Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:40:40 +0000 Subject: [PATCH 15/30] fix(query): share the key value type check and update three comments The comment above the Query request checks in authorize_request said that they run for every principal. They run after the cross-account refusal, so a table ARN in another account gets AccessDeniedException without them. The service runs them first for a body it can read. Main has the same order for every Query check, and the call does not move. The comment now states this. The comment above the key value type gate in handle_query now states the service's order for legacy KeyConditions. For a legacy value of the wrong type on a single-attribute key schema, the service reports the projection, Select, filter, QueryFilter and unused-value checks first. The classifier's check answers ahead of them, as on main. The doc comment of the Query number check is about the ExpressionAttributeValues contains invalid value wrapper. It said that on Query the service adds the wrapper only for a value it cannot read as one type. The service also adds it beside a Limit above 2147483647 (measured 2026-11-12), and the comment now says so. validate_key_condition_types now calls check_key_value_type for each value it compares. This removes type_matches and resolve_attr_name, which repeated check_key_value_type and resolve_path_attr_name. check_key_value_type returns KEY_CONDITION_TYPE_MISMATCH in place of a second copy of the text. No answer changes. validate_attribute_number in the core validation module is private again. An earlier commit of this branch made it public, and nothing outside that file calls it. --- crates/core/src/validation/mod.rs | 10 +---- crates/engine/src/query.rs | 12 ++--- crates/engine/src/query_key_values.rs | 65 ++++++--------------------- crates/server/src/request_helpers.rs | 22 +++++---- 4 files changed, 35 insertions(+), 74 deletions(-) diff --git a/crates/core/src/validation/mod.rs b/crates/core/src/validation/mod.rs index 7d993415e..50fb2a0f3 100755 --- a/crates/core/src/validation/mod.rs +++ b/crates/core/src/validation/mod.rs @@ -2510,15 +2510,7 @@ fn validate_lsi_requires_range_key(input: &CreateTableInput) -> Result<(), Dynam Ok(()) } -/// Validate every number inside one attribute value (`N`, `NS` members, and -/// the values nested in `L` and `M`) against the `DynamoDB` number rules, with -/// the bare numeric message. -/// -/// # Errors -/// -/// Returns `DynamoDbError::ValidationException` for the first number that is -/// not a number, has more than 38 significant digits, or is out of range. -pub fn validate_attribute_number(value: &AttributeValue) -> Result<(), DynamoDbError> { +fn validate_attribute_number(value: &AttributeValue) -> Result<(), DynamoDbError> { match value { AttributeValue::N(n) => { number::validate_and_normalize_number(n)?; diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 76fedd5ea..4efded87d 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -250,7 +250,11 @@ pub async fn handle_query( // Legacy `KeyConditions` are checked by the classifier: against the key // schema's definitions on a multi-attribute key schema and against the // table's on a single-attribute one. The check below runs only where the - // classifier did not check (`!check_types_here`). + // classifier did not check (`!check_types_here`). For a legacy value of + // the wrong type on a single-attribute key schema, the service reports the + // projection, Select, filter, QueryFilter and unused-value checks first + // (measured 2026-11-11 and 2026-11-12), so the classifier's check answers + // ahead of them there, where the service does not. let multipart = extenddb_core::types::is_multipart_key_schema(&query_key_info.key_schema); let key_schema_definitions: Vec = query_key_info .attribute_definitions @@ -601,7 +605,7 @@ fn resolve_path_attr_name( /// `attribute_definitions` is not checked here. On a multi-attribute key /// schema the caller passes the queried key schema's definitions only, and the /// classifier reports a clause on any other attribute. -fn check_key_value_type( +pub(crate) fn check_key_value_type( path: &[PathElement], expr: &extenddb_core::expression::Expr, attribute_definitions: &[extenddb_core::types::AttributeDefinition], @@ -635,9 +639,7 @@ fn check_key_value_type( Ok(()) } else { Err(DynamoDbError::ValidationException( - "One or more parameter values were invalid: Condition parameter type does not match \ - schema type" - .to_owned(), + crate::query_key_values::KEY_CONDITION_TYPE_MISMATCH.to_owned(), )) } } diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index 69fbb6ce1..e134dc252 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -28,13 +28,11 @@ //! `bob` partition, while authorization binds no `dynamodb:LeadingKeys` value //! to a number it cannot parse. -use std::collections::HashMap; - use extenddb_core::error::DynamoDbError; use extenddb_core::expression::{ Expr, ExpressionMaps, KeyCondition, PathElement, SortKeyCondition, }; -use extenddb_core::types::{AttributeDefinition, AttributeValue, QueryInput, ScalarAttributeType}; +use extenddb_core::types::{AttributeDefinition, QueryInput}; use serde::de::DeserializeOwned; use serde_json::{Map, Value}; @@ -340,8 +338,9 @@ fn number_fault(text: &str) -> Option> { /// Refuse the first `N` value in `ExpressionAttributeValues` (including `NS` /// members and values nested in `L` and `M`) that is not a number, with the /// bare numeric message: no `ExpressionAttributeValues contains invalid value` -/// wrapper, which the service uses on `UpdateItem` and on `Query` only for a -/// value it cannot read as one type. The placeholders are visited in sorted +/// wrapper, which the service uses on `UpdateItem`, and on `Query` for a value +/// it cannot read as one type or beside a `Limit` above 2147483647 (measured +/// 2026-11-12). The placeholders are visited in sorted /// order and each value on its own, so a value of the wrong JSON shape does /// not stop the check of another (the service picks among several invalid /// values by an order of its own: measured 2026-11-11, `:a` and `:b` with @@ -377,12 +376,14 @@ fn validate_expression_attribute_value_numbers( /// /// Every value the condition compares is checked: the partition key value(s), /// the sort key value (or both `BETWEEN` bounds, or the `begins_with` prefix) -/// and the extra equality conditions of a multi-attribute key schema. A path -/// that does not resolve to an attribute name, a value that is not a -/// placeholder, and a key attribute with no definition are left to the checks -/// that already refuse them. When any compared placeholder is undefined the -/// whole check is skipped: the service reports the undefined placeholder -/// first, and the storage layer does so here. +/// and the extra equality conditions of a multi-attribute key schema. Each one +/// goes through the check the key schema classifier applies to a clause +/// (`check_key_value_type` in `query.rs`). A path that does not resolve to an +/// attribute name, a value that is not a placeholder, and a key attribute with +/// no definition are left to the checks that already refuse them. When any +/// compared placeholder is undefined the whole check is skipped: the service +/// reports the undefined placeholder first, and the storage layer does so +/// here. /// /// # Errors /// @@ -419,51 +420,11 @@ pub fn validate_key_condition_types( } for (path, value) in pairs { - let Some(attr_name) = resolve_attr_name(path, &maps.names) else { - continue; - }; - let Some(expected) = attribute_definitions - .iter() - .find(|ad| ad.attribute_name == attr_name) - .map(|ad| ad.attribute_type) - else { - continue; - }; - let Expr::Placeholder(name) = value else { - continue; - }; - let Some(av) = maps.values.get(name) else { - continue; - }; - if !type_matches(expected, av) { - return Err(DynamoDbError::ValidationException( - KEY_CONDITION_TYPE_MISMATCH.to_owned(), - )); - } + crate::query::check_key_value_type(path, value, attribute_definitions, maps)?; } Ok(()) } -fn type_matches(expected: ScalarAttributeType, value: &AttributeValue) -> bool { - matches!( - (expected, value), - (ScalarAttributeType::S, AttributeValue::S(_)) - | (ScalarAttributeType::N, AttributeValue::N(_)) - | (ScalarAttributeType::B, AttributeValue::B(_)) - ) -} - -/// The top-level attribute name of a key path, through `#name` references. -fn resolve_attr_name(path: &[PathElement], names: &HashMap) -> Option { - match path.first()? { - PathElement::Attribute(name) => match name.strip_prefix('#') { - Some(reference) => names.get(reference).cloned(), - None => Some(name.clone()), - }, - PathElement::Index(_) => None, - } -} - #[cfg(test)] mod tests; diff --git a/crates/server/src/request_helpers.rs b/crates/server/src/request_helpers.rs index 3d8e36383..a9ae693a1 100755 --- a/crates/server/src/request_helpers.rs +++ b/crates/server/src/request_helpers.rs @@ -174,14 +174,20 @@ pub(crate) async fn authorize_request( // A Query's request-time checks (Limit, the expression and non-expression // parameter mix, the ReturnConsumedCapacity and Select enums, every number - // in ExpressionAttributeValues) run before the IAM decision, for every - // principal. The engine makes the same checks at request time; they run - // here as well because authorization binds no dynamodb:LeadingKeys value - // to a number it cannot parse, and a fence that needs the key present - // (ForAnyValue, a Null guard, the plain operators) would otherwise answer - // AccessDeniedException where ValidationException is the request's error. - // The checks read the raw body, so a field that does not deserialize does - // not skip them. + // in ExpressionAttributeValues) run before the IAM decision, whatever the + // caller's policy. The engine makes the same checks at request time; they + // run here as well because authorization binds no dynamodb:LeadingKeys + // value to a number it cannot parse, and a fence that needs the key + // present (ForAnyValue, a Null guard, the plain operators) would otherwise + // answer AccessDeniedException where ValidationException is the request's + // error. The checks read the raw body, so a field that does not + // deserialize does not skip them. + // + // They run after the cross-account refusal above, so a Query that names a + // table ARN in another account gets AccessDeniedException without them. + // The service runs them first for a body it can read (measured + // 2026-11-12: with a table ARN in another account, `{"N": "bob"}` answers + // the numeric message and a `Limit` of 0 the `Limit` text). if operation == "Query" { extenddb_engine::query_key_values::validate_query_request_body(input)?; } From ba4af88dd6d9c75aedef7086b5bcd5f09c17ba4b Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:00:10 +0000 Subject: [PATCH 16/30] fix(query): read each payload of a value with several types first first_fault returned the more than one datatypes text as soon as a value held two type descriptors. It did not read their payloads. The service reads every payload first. On Query, the service gives one answer for :v set to {"N": "bob", "S": "x"} and for {"S": "x", "N": "bob"}. The answer is "ExpressionAttributeValues contains invalid value: The parameter cannot be converted to a numeric value: bob for key :v". {"N": "1", "S": "x"} answers the more than one datatypes text. The service names a null or an empty value inside an L beside an S in the same way. It reads N ahead of NS, and NS and M ahead of L, in either member order (each request measured twice on 2026-11-19). first_fault now reads the payloads in the order of TYPE_DESCRIPTORS, which agrees with those pairs. It returns the more than one datatypes text only when no payload has a fault. The doc comment of the Query number check said that the service adds the wrapper on UpdateItem. On the service, :v set to {"N": "bob"} in UpdateItem gets no wrapper, in SET a = :v and in a ConditionExpression that reads :v. The answer is "1 validation error detected: The parameter cannot be converted to a numeric value: bob". The comment no longer names UpdateItem. --- crates/engine/src/query_key_values.rs | 65 +++++++++++-------- .../src/query_key_values/unreadable_tests.rs | 64 ++++++++++++++++++ tests/test_query_value_shapes.py | 14 +++- 3 files changed, 115 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index e134dc252..9cc4a3545 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -249,7 +249,7 @@ enum Fault<'a> { Null(Option<&'a str>), /// No type descriptor the service knows. Empty, - /// More than one type descriptor. + /// More than one type descriptor, with no fault in their payloads. SeveralTypes, /// An `N` text or `NS` member that is not a number, as the request wrote it. NotANumber(&'a str), @@ -289,35 +289,46 @@ impl Fault<'_> { } /// The first fault in `value` (`member` is its name when it is the value of an -/// `M` member): a null, no type descriptor or more than one, then the numbers -/// in `N`, `NS` and every value an `L` or `M` holds. `L` items are visited in -/// document order and `M` members in key order: this build of `serde_json` -/// keeps an object's members sorted by key. A value of another JSON type, and -/// an `N` or `NS` payload of the wrong JSON type, are shape faults the -/// deserializer reports. +/// `M` member): a null or no type descriptor, then the numbers in `N`, `NS` +/// and every value an `L` or `M` holds, then more than one type descriptor. +/// `L` items are visited in document order and `M` members in key order: this +/// build of `serde_json` keeps an object's members sorted by key. A value of +/// another JSON type, and an `N` or `NS` payload of the wrong JSON type, are +/// shape faults the deserializer reports. +/// +/// With several type descriptors, the service reads each payload in the order +/// of [`TYPE_DESCRIPTORS`], whatever order the request wrote them in, and +/// answers the more than one datatypes text only when no payload has a fault +/// (measured 2026-11-19: `{"N": "bob", "S": "x"}` and `{"S": "x", "N": "bob"}` +/// answer the numeric text for `bob`, `{"N": "1", "S": "x"}` the more than one +/// datatypes text, `{"S": "x", "L": [null]}` the null text, and `N` is read +/// ahead of `NS`, `NS` and `M` ahead of `L`). fn first_fault<'a>(value: &'a Value, member: Option<&'a str>) -> Option> { let Value::Object(map) = value else { return value.is_null().then_some(Fault::Null(member)); }; - let mut known = map + let payloads: Vec<(&str, &Value)> = TYPE_DESCRIPTORS .iter() - .filter(|(key, _)| TYPE_DESCRIPTORS.contains(&key.as_str())); - let (descriptor, payload) = match (known.next(), known.next()) { - (None, _) => return Some(Fault::Empty), - (Some(_), Some(_)) => return Some(Fault::SeveralTypes), - (Some(entry), None) => entry, - }; - match (descriptor.as_str(), payload) { - ("N", Value::String(text)) => number_fault(text), - ("NS", Value::Array(members)) => members - .iter() - .filter_map(Value::as_str) - .find_map(number_fault), - ("L", Value::Array(items)) => items.iter().find_map(|item| first_fault(item, None)), - ("M", Value::Object(members)) => members - .iter() - .find_map(|(name, inner)| first_fault(inner, Some(name))), - _ => None, + .filter_map(|&descriptor| Some((descriptor, map.get(descriptor)?))) + .collect(); + let fault = payloads + .iter() + .find_map(|&(descriptor, payload)| match (descriptor, payload) { + ("N", Value::String(text)) => number_fault(text), + ("NS", Value::Array(members)) => members + .iter() + .filter_map(Value::as_str) + .find_map(number_fault), + ("L", Value::Array(items)) => items.iter().find_map(|item| first_fault(item, None)), + ("M", Value::Object(members)) => members + .iter() + .find_map(|(name, inner)| first_fault(inner, Some(name))), + _ => None, + }); + match payloads.len() { + 0 => Some(Fault::Empty), + 1 => fault, + _ => fault.or(Some(Fault::SeveralTypes)), } } @@ -337,8 +348,8 @@ fn number_fault(text: &str) -> Option> { /// Refuse the first `N` value in `ExpressionAttributeValues` (including `NS` /// members and values nested in `L` and `M`) that is not a number, with the -/// bare numeric message: no `ExpressionAttributeValues contains invalid value` -/// wrapper, which the service uses on `UpdateItem`, and on `Query` for a value +/// bare numeric message. On `Query` the service adds the +/// `ExpressionAttributeValues contains invalid value` wrapper only for a value /// it cannot read as one type or beside a `Limit` above 2147483647 (measured /// 2026-11-12). The placeholders are visited in sorted /// order and each value on its own, so a value of the wrong JSON shape does diff --git a/crates/engine/src/query_key_values/unreadable_tests.rs b/crates/engine/src/query_key_values/unreadable_tests.rs index 33f227062..9aa20aa89 100644 --- a/crates/engine/src/query_key_values/unreadable_tests.rs +++ b/crates/engine/src/query_key_values/unreadable_tests.rs @@ -57,6 +57,70 @@ fn a_value_the_service_cannot_read_as_one_type_is_named_with_its_placeholder() { } } +#[test] +fn a_number_fault_in_a_value_with_several_types_is_named_ahead_of_the_several_types_text() { + // Measured 2026-11-19, each value beside `:p = {"S": "x"}`: the service + // reads every payload, N ahead of NS, NS and M ahead of L, whatever order + // the request wrote them in, and answers the more than one datatypes text + // only when no payload has a fault. + let numeric = + |text: &str| format!("The parameter cannot be converted to a numeric value: {text}"); + let several = "Supplied AttributeValue has more than one datatypes set, must contain \ + exactly one of the supported datatypes"; + for (value, reason) in [ + (json!({"N": "bob", "S": "x"}), numeric("bob")), + (json!({"N": "1", "S": "x"}), several.to_owned()), + ( + json!({"N": "", "S": "x"}), + "The parameter cannot be converted to a numeric value".to_owned(), + ), + ( + json!({"N": "1e200", "S": "x"}), + "Number overflow. Attempting to store a number with magnitude larger than \ + supported range" + .to_owned(), + ), + (json!({"NS": ["bob"], "S": "x"}), numeric("bob")), + (json!({"BOOL": true, "N": "bob"}), numeric("bob")), + (json!({"S": "x", "N": "bob", "X": "1"}), numeric("bob")), + (json!({"L": [{"N": "bob", "S": "x"}]}), numeric("bob")), + (json!({"S": "x", "L": [{"N": "bob"}]}), numeric("bob")), + (json!({"S": "x", "M": {"a": {"N": "bob"}}}), numeric("bob")), + (json!({"S": "x", "L": [{"X": "1"}]}), EMPTY.to_owned()), + ( + json!({"S": "x", "L": [null]}), + "The supplied Item contains a null AttributeValue".to_owned(), + ), + (json!({"N": "aaa", "NS": ["bbb"]}), numeric("aaa")), + (json!({"N": "bbb", "L": [{"N": "aaa"}]}), numeric("bbb")), + (json!({"NS": ["aaa"], "L": [{"N": "bbb"}]}), numeric("aaa")), + ( + json!({"M": {"k": {"N": "aaa"}}, "L": [{"N": "bbb"}]}), + numeric("aaa"), + ), + ] { + let body = body_with(json!({":p": {"S": "x"}, ":z": value}), json!({})); + assert_eq!( + message(validate_query_request_body(&body)), + Some(format!("{INVALID_VALUE}{reason} for key :z")), + "{value}" + ); + } + // Such a value still takes the order of a value the service cannot read. + let body = body_with( + json!({":p": {"S": "x"}, ":z": {"N": "bob", "S": "x"}}), + json!({"Limit": 0}), + ); + assert_eq!( + message(validate_query_request_body(&body)), + Some( + "1 validation error detected: Value '0' at 'limit' failed to satisfy constraint: \ + Member must have value greater than or equal to 1" + .to_owned() + ) + ); +} + #[test] fn numbers_beside_a_value_the_service_cannot_read_are_wrapped_and_echoed_as_sent() { // Measured 2026-11-11 beside `:a = {"S": "a", "X": "1"}`, which the service diff --git a/tests/test_query_value_shapes.py b/tests/test_query_value_shapes.py index ebf71678c..848a10bf4 100644 --- a/tests/test_query_value_shapes.py +++ b/tests/test_query_value_shapes.py @@ -5,7 +5,7 @@ wrong JSON type, and an ExpressionAttributeValues value the service cannot read as one type. boto3 refuses or reshapes these bodies, so they go out as written. Every expected answer below was measured against the service on -2026-10-25 (11:31 UTC) and 2026-11-11. +2026-10-25 (11:31 UTC), 2026-11-11 and 2026-11-19. Dual-target: runs against the service and against extenddb with the same assertions. @@ -140,6 +140,18 @@ def test_control_without_a_shape_fault_answers_the_check(self, dynamodb_client, ("AttributesToGet", {":z": X1, ":u": NB}, {"AttributesToGet": ["a"]}, "Can not use both expression and non-expression parameters in the same request: " "Non-expression parameters: {AttributesToGet} Expression parameters: {KeyConditionExpression}"), + # Beside a second type descriptor, a payload with a fault is named ahead of + # the more than one datatypes text, whatever order the members are in + # (measured 2026-11-19). + ("N bob then S", {":z": {"N": "bob", "S": "x"}}, {}, INVALID_VALUE + NUMERIC + "bob for key :z"), + ("S then N bob", {":z": {"S": "x", "N": "bob"}}, {}, INVALID_VALUE + NUMERIC + "bob for key :z"), + ("N 1 then S", {":z": {"N": "1", "S": "x"}}, {}, INVALID_VALUE + SEVERAL_AV + " for key :z"), + ("S then NS bob", {":z": {"S": "x", "NS": ["bob"]}}, {}, INVALID_VALUE + NUMERIC + "bob for key :z"), + ("S then L with null", {":z": {"S": "x", "L": [None]}}, {}, INVALID_VALUE + NULL_AV + " for key :z"), + ("L with N bbb then NS aaa", {":z": {"L": [{"N": "bbb"}], "NS": ["aaa"]}}, {}, + INVALID_VALUE + NUMERIC + "aaa for key :z"), + ("N bob then S with Limit 0", {":z": {"N": "bob", "S": "x"}}, {"Limit": 0}, + "1 validation error detected: " + LIMIT_0_AT), ] From 474b23d9071fd9e3daa28f38f5b7fb38b668cb64 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:22:05 +0000 Subject: [PATCH 17/30] fix(query): check ExpressionAttributeNames ahead of the numbers The request-time Query checks had no ExpressionAttributeNames step, so an invalid names key beside {"N": "bob"} answered the numeric text. The service and main answer `ExpressionAttributeNames contains invalid key: Syntax error; key: "a"`. validate_names runs the ExpressionAttributeNames deserializer on the raw body and returns its ValidationException. Both paths of the checks call it after the parameter mix and ahead of the values. The service checks in the same order: it reports a Limit of 0, an invalid ReturnConsumedCapacity and the mix ahead of an invalid key. The key comes ahead of an N value that is not a number and of a duplicate NS. It also comes ahead of an invalid Select and of a value the service cannot read as one type. With KeyConditions and no KeyConditionExpression, the service still reports the key. Each request went to the service twice on 2026-11-19, with the names map first and last in the body. --- crates/engine/src/query.rs | 9 +- crates/engine/src/query_key_values.rs | 44 ++++- .../src/query_key_values/names_tests.rs | 161 ++++++++++++++++++ .../engine/src/query_key_values/unreadable.rs | 10 +- crates/server/src/request_helpers.rs | 18 +- tests/test_query_value_shapes.py | 91 +++++++++- 6 files changed, 308 insertions(+), 25 deletions(-) create mode 100644 crates/engine/src/query_key_values/names_tests.rs diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 4efded87d..4cd0d3567 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -49,10 +49,11 @@ pub async fn handle_query( ) -> Result { // Request-time checks on the raw body, in the service's order: Limit, the // ReturnConsumedCapacity enum, the expression and non-expression parameter - // mix, every number in ExpressionAttributeValues, the Select enum. They - // run before typed deserialization so a field that does not deserialize - // does not stop the ones before it. The server runs the same function - // ahead of the IAM decision; see `query_key_values`. + // mix, the ExpressionAttributeNames map, every number in + // ExpressionAttributeValues, the Select enum. They run before typed + // deserialization so a field that does not deserialize does not stop the + // ones before it. The server runs the same function ahead of the IAM + // decision; see `query_key_values`. crate::query_key_values::validate_query_request_body(&body)?; let input: QueryInput = serde_json::from_value(body).map_err(crate::deserialize_error)?; diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index 9cc4a3545..eb4b2c550 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -11,9 +11,9 @@ //! overflow, underflow and 38-digit messages). Every value in the map is //! checked, whether the key condition, the filter or nothing reads it. The //! check runs at request time, after the `Limit` check, the -//! `ReturnConsumedCapacity` enum check and the expression and -//! non-expression parameter mix check, and before the table is looked up; -//! see [`validate_query_request_body`]; +//! `ReturnConsumedCapacity` enum check, the expression and non-expression +//! parameter mix check and the `ExpressionAttributeNames` check, and before +//! the table is looked up; see [`validate_query_request_body`]; //! 2. a key condition value whose type is not the key attribute's //! `AttributeDefinitions` type answers `One or more parameter values were //! invalid: Condition parameter type does not match schema type`, on the @@ -70,13 +70,17 @@ const SELECT: &[&str] = &[ /// The `Query` checks that run on the request body alone, before the body is /// deserialized and before the table is looked up, in the service's order: /// `Limit`, the `ReturnConsumedCapacity` enum, the expression and -/// non-expression parameter mix, every number in `ExpressionAttributeValues`, -/// then the `Select` enum (measured 2026-10-24 and 2026-11-11: a `Limit` of 0 -/// is reported ahead of an invalid enum value of either field and of a -/// parameter mix, an invalid `ReturnConsumedCapacity` ahead of a mix with +/// non-expression parameter mix, the `ExpressionAttributeNames` map (see +/// `validate_names`), every number in `ExpressionAttributeValues`, then the +/// `Select` enum (measured 2026-10-24 and 2026-11-11: a `Limit` of 0 is +/// reported ahead of an invalid enum value of either field and of a parameter +/// mix, an invalid `ReturnConsumedCapacity` ahead of a mix with /// `AttributesToGet`, `QueryFilter`, `ConditionalOperator` or `KeyConditions` /// and ahead of an `N` value that is not a number, a mix ahead of that value, -/// and that value ahead of an invalid `Select`). +/// and that value ahead of an invalid `Select`. Measured 2026-11-19 in either +/// member order: an invalid names map is reported after a `Limit` of 0, an +/// invalid `ReturnConsumedCapacity` and a mix, and ahead of an `N` value that +/// is not a number, a set with a duplicate member and an invalid `Select`). /// /// A request whose `ExpressionAttributeValues` holds a value the service /// cannot read as one type takes another order; see @@ -178,6 +182,7 @@ fn query_request_checks(body: &Value) -> Result<(), DynamoDbError> { )?; validate_no_parameter_mix(body)?; + validate_names(body)?; if let Some(values) = values { validate_expression_attribute_value_numbers(values)?; @@ -219,6 +224,26 @@ fn validate_no_parameter_mix(body: &Value) -> Result<(), DynamoDbError> { ) } +/// The checks the `ExpressionAttributeNames` deserializer makes, on the raw +/// body: an empty map, a key that is not `#` and a name, and an empty name, +/// with the deserializer's text. A map or name of another JSON type is a shape +/// fault, which this leaves to the shape fault check. +/// +/// # Errors +/// +/// Returns `DynamoDbError::ValidationException` with the deserializer's text. +pub(crate) fn validate_names(body: &Value) -> Result<(), DynamoDbError> { + let Some(names) = body.get("ExpressionAttributeNames") else { + return Ok(()); + }; + match extenddb_core::serde_helpers::deserialize_expression_names(names) + .map_err(crate::deserialize_error) + { + Err(fault @ DynamoDbError::ValidationException(_)) => Err(fault), + _ => Ok(()), + } +} + /// Whether `field` is in the body with a value other than `null`, as a typed /// `Option` field would deserialize to `Some`. fn present(body: &Value, field: &str) -> bool { @@ -444,3 +469,6 @@ mod request_order_tests; #[cfg(test)] mod unreadable_tests; + +#[cfg(test)] +mod names_tests; diff --git a/crates/engine/src/query_key_values/names_tests.rs b/crates/engine/src/query_key_values/names_tests.rs new file mode 100644 index 000000000..a81430bf2 --- /dev/null +++ b/crates/engine/src/query_key_values/names_tests.rs @@ -0,0 +1,161 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Tests for the place of the `ExpressionAttributeNames` check among the +//! request-time `Query` checks. + +use serde_json::{Value, json}; + +use super::tests::{body_with, message}; +use super::{LIMIT_BELOW_ONE, validate_query_request_body}; + +const INVALID_KEY: &str = + r#"ExpressionAttributeNames contains invalid key: Syntax error; key: "a""#; +const NUMERIC_BOB: &str = "The parameter cannot be converted to a numeric value: bob"; +const RCC: &str = "1 validation error detected: Value 'bad' at 'returnConsumedCapacity' \ + failed to satisfy constraint: Member must satisfy enum value set: \ + [INDEXES, TOTAL, NONE]"; +const SELECT: &str = "1 validation error detected: Value 'bad' at 'select' failed to satisfy \ + constraint: Member must satisfy enum value set: [SPECIFIC_ATTRIBUTES, \ + COUNT, ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]"; +const MIX: &str = "Can not use both expression and non-expression parameters in the same \ + request: Non-expression parameters: {AttributesToGet} Expression \ + parameters: {KeyConditionExpression}"; + +/// The answer for a body with `values` in `ExpressionAttributeValues`, `names` +/// in `ExpressionAttributeNames` and the `extra` members. +fn answer(values: Value, names: Value, extra: Value) -> Option { + let mut body = body_with(values, extra); + body["ExpressionAttributeNames"] = names; + message(validate_query_request_body(&body)) +} + +#[test] +fn an_invalid_names_map_is_reported_after_the_mix_and_ahead_of_the_numbers() { + // Measured 2026-11-19, with the names map ahead of the other members and + // after them: each names fault beside `{"N": "bob"}` answers the names + // text, as an invalid key does beside a set with a duplicate member and + // beside an invalid Select. A Limit of 0, an invalid + // ReturnConsumedCapacity and a mix are reported ahead of an invalid key. + let bad_number = json!({":p": {"S": "x"}, ":n": {"N": "bob"}}); + for (names, expected) in [ + (json!({"a": "b"}), INVALID_KEY), + (json!({}), "ExpressionAttributeNames must not be empty"), + ( + json!({"#a": ""}), + "ExpressionAttributeNames contains invalid value: Empty attribute name for key #a", + ), + ] { + assert_eq!( + answer(bad_number.clone(), names.clone(), json!({})).as_deref(), + Some(expected), + "{names}" + ); + } + for (values, extra) in [ + ( + json!({":p": {"S": "x"}, ":d": {"NS": ["1", "1"]}}), + json!({}), + ), + (json!({":p": {"S": "x"}}), json!({"Select": "bad"})), + ] { + assert_eq!( + answer(values, json!({"a": "b"}), extra.clone()).as_deref(), + Some(INVALID_KEY), + "{extra}" + ); + } + for (extra, expected) in [ + (json!({"Limit": 0}), LIMIT_BELOW_ONE), + (json!({"ReturnConsumedCapacity": "bad"}), RCC), + (json!({"AttributesToGet": ["a"]}), MIX), + ] { + assert_eq!( + answer(bad_number.clone(), json!({"a": "b"}), extra.clone()).as_deref(), + Some(expected), + "{extra}" + ); + } + // A names map the deserializer accepts, used or not, leaves the answer to + // the number check. + assert_eq!( + answer(bad_number, json!({"#a": "a"}), json!({})).as_deref(), + Some(NUMERIC_BOB) + ); +} + +#[test] +fn beside_a_value_the_service_cannot_read_the_names_map_follows_the_mix() { + // Measured 2026-11-19, in either member order: an invalid key is reported + // ahead of a value the service cannot read as one type, and the + // reported-together Select, ReturnConsumedCapacity and Limit step and the + // mix are reported ahead of the key. + for value in [json!({"X": "1"}), json!({}), json!({"N": "1", "S": "x"})] { + assert_eq!( + answer( + json!({":p": {"S": "x"}, ":x": value}), + json!({"a": "b"}), + json!({}) + ) + .as_deref(), + Some(INVALID_KEY), + "{value}" + ); + } + let limit = "1 validation error detected: Value '0' at 'limit' failed to satisfy \ + constraint: Member must have value greater than or equal to 1"; + for (extra, expected) in [ + (json!({"Limit": 0}), limit), + (json!({"Select": "bad"}), SELECT), + (json!({"ReturnConsumedCapacity": "bad"}), RCC), + (json!({"AttributesToGet": ["a"]}), MIX), + ] { + assert_eq!( + answer( + json!({":p": {"S": "x"}, ":x": {"X": "1"}}), + json!({"a": "b"}), + extra.clone() + ) + .as_deref(), + Some(expected), + "{extra}" + ); + } +} + +#[test] +fn the_names_map_is_checked_when_no_expression_reads_it() { + // Measured 2026-11-19 with KeyConditions and no KeyConditionExpression: an + // invalid key is reported alone, beside a value nothing reads and beside + // `{"N": "bob"}`. A valid names map leaves the number check to answer. + let key_conditions = + json!({"pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]}}); + for values in [ + None, + Some(json!({":v": {"S": "x"}})), + Some(json!({":v": {"N": "bob"}})), + ] { + let mut body = json!({ + "TableName": "t", + "KeyConditions": key_conditions, + "ExpressionAttributeNames": {"a": "b"}, + }); + if let Some(values) = values { + body["ExpressionAttributeValues"] = values; + } + assert_eq!( + message(validate_query_request_body(&body)).as_deref(), + Some(INVALID_KEY), + "{body}" + ); + } + let body = json!({ + "TableName": "t", + "KeyConditions": key_conditions, + "ExpressionAttributeNames": {"#a": "a"}, + "ExpressionAttributeValues": {":v": {"N": "bob"}}, + }); + assert_eq!( + message(validate_query_request_body(&body)).as_deref(), + Some(NUMERIC_BOB) + ); +} diff --git a/crates/engine/src/query_key_values/unreadable.rs b/crates/engine/src/query_key_values/unreadable.rs index cd6ec2e9c..3a0467776 100644 --- a/crates/engine/src/query_key_values/unreadable.rs +++ b/crates/engine/src/query_key_values/unreadable.rs @@ -14,7 +14,7 @@ use serde_json::{Map, Value}; use super::{ RETURN_CONSUMED_CAPACITY, SELECT, TYPE_DESCRIPTORS, first_fault, sorted_entries, - validate_no_parameter_mix, + validate_names, validate_no_parameter_mix, }; /// Whether the service cannot read `value` as exactly one AttributeValue type: @@ -124,7 +124,12 @@ fn null_value() -> Value { /// 'limit' failed to satisfy constraint: Member must have value greater /// than or equal to 1`; /// 2. the expression and non-expression parameter mix; -/// 3. the first fault inside a value, in document order for `L` items and in +/// 3. the `ExpressionAttributeNames` map (measured 2026-11-19: an invalid +/// names key beside `{"X": "1"}`, `{}` or `{"N": "1", "S": "x"}` answers +/// the names text, in either member order, and beside such a value a +/// `Limit` of 0, an invalid `Select` or `ReturnConsumedCapacity` and a mix +/// are reported ahead of it); see [`validate_names`]; +/// 4. the first fault inside a value, in document order for `L` items and in /// key order for `M` members, as `ExpressionAttributeValues contains /// invalid value: for key `: a null (`The supplied /// Item contains a null AttributeValue`, with `: is null` when it @@ -178,6 +183,7 @@ pub(super) fn unreadable_value_checks( } validate_no_parameter_mix(body)?; + validate_names(body)?; // The values the service cannot read first; the sort is stable, so each // group keeps the placeholder order. diff --git a/crates/server/src/request_helpers.rs b/crates/server/src/request_helpers.rs index 505cc770f..a3fea4349 100755 --- a/crates/server/src/request_helpers.rs +++ b/crates/server/src/request_helpers.rs @@ -246,15 +246,15 @@ pub(crate) async fn authorize_request( } // A Query's request-time checks (Limit, the expression and non-expression - // parameter mix, the ReturnConsumedCapacity and Select enums, every number - // in ExpressionAttributeValues) run before the IAM decision, whatever the - // caller's policy. The engine makes the same checks at request time; they - // run here as well because authorization binds no dynamodb:LeadingKeys - // value to a number it cannot parse, and a fence that needs the key - // present (ForAnyValue, a Null guard, the plain operators) would otherwise - // answer AccessDeniedException where ValidationException is the request's - // error. The checks read the raw body, so a field that does not - // deserialize does not skip them. + // parameter mix, the ReturnConsumedCapacity and Select enums, the + // ExpressionAttributeNames map, every number in ExpressionAttributeValues) + // run before the IAM decision, whatever the caller's policy. The engine + // makes the same checks at request time; they run here as well because + // authorization binds no dynamodb:LeadingKeys value to a number it cannot + // parse, and a fence that needs the key present (ForAnyValue, a Null + // guard, the plain operators) would otherwise answer AccessDeniedException + // where ValidationException is the request's error. The checks read the + // raw body, so a field that does not deserialize does not skip them. // // They run after the cross-account refusal above, so a Query that names a // table ARN in another account gets AccessDeniedException without them. diff --git a/tests/test_query_value_shapes.py b/tests/test_query_value_shapes.py index 848a10bf4..0dfafd527 100644 --- a/tests/test_query_value_shapes.py +++ b/tests/test_query_value_shapes.py @@ -2,8 +2,9 @@ # SPDX-License-Identifier: Apache-2.0 """Query request bodies the service does not read as written: a field of the -wrong JSON type, and an ExpressionAttributeValues value the service cannot -read as one type. boto3 refuses or reshapes these bodies, so they go out as +wrong JSON type, an ExpressionAttributeValues value the service cannot read as +one type, and an ExpressionAttributeNames map the service refuses, in both +member orders. boto3 refuses or reshapes these bodies, so they go out as written. Every expected answer below was measured against the service on 2026-10-25 (11:31 UTC), 2026-11-11 and 2026-11-19. @@ -21,6 +22,7 @@ import pytest from test_query_key_value_types import ( # noqa: F401 (ss_table is a fixture) + LEGACY_PK, LIMIT_MSG, NB, NUMERIC, @@ -184,3 +186,88 @@ def test_the_value_the_service_cannot_read_is_named_beside_n_bob(self, dynamodb_ assert payload.get("__type", "").endswith("ValidationException"), payload assert payload.get("message", payload.get("Message")) == ( INVALID_VALUE + EMPTY_AV + " for key :z") + + +INVALID_KEY = 'ExpressionAttributeNames contains invalid key: Syntax error; key: "a"' +BAD_NAMES = {"a": "b"} +SELECT_MSG = ("1 validation error detected: Value 'bad' at 'select' failed to satisfy constraint: " + "Member must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, " + "ALL_PROJECTED_ATTRIBUTES]") +ATTRIBUTES_TO_GET_MIX = ( + "Can not use both expression and non-expression parameters in the same request: " + "Non-expression parameters: {AttributesToGet} Expression parameters: {KeyConditionExpression}") + +# (row, ExpressionAttributeNames, values beside :p, other members, the +# service's message). +NAMES = [ + ("invalid key beside N bob", BAD_NAMES, {":n": NB}, {}, INVALID_KEY), + ("empty map beside N bob", {}, {":n": NB}, {}, "ExpressionAttributeNames must not be empty"), + ("empty name beside N bob", {"#a": ""}, {":n": NB}, {}, + "ExpressionAttributeNames contains invalid value: Empty attribute name for key #a"), + ("invalid key beside a duplicate NS", BAD_NAMES, {":d": {"NS": ["1", "1"]}}, {}, INVALID_KEY), + ("invalid key beside an invalid Select", BAD_NAMES, {}, {"Select": "bad"}, INVALID_KEY), + ("Limit 0 beside an invalid key", BAD_NAMES, {}, {"Limit": 0}, LIMIT_MSG), + ("ReturnConsumedCapacity beside an invalid key", BAD_NAMES, {}, + {"ReturnConsumedCapacity": "bad"}, RCC_MSG), + ("AttributesToGet beside an invalid key", BAD_NAMES, {}, {"AttributesToGet": ["a"]}, + ATTRIBUTES_TO_GET_MIX), + ("invalid key beside an unknown descriptor", BAD_NAMES, {":x": X1}, {}, INVALID_KEY), + ("invalid key beside no descriptor", BAD_NAMES, {":x": {}}, {}, INVALID_KEY), + ("invalid key beside two descriptors", BAD_NAMES, {":v": {"N": "1", "S": "x"}}, {}, INVALID_KEY), + ("Limit 0 beside an unknown descriptor and an invalid key", BAD_NAMES, {":x": X1}, + {"Limit": 0}, "1 validation error detected: " + LIMIT_0_AT), + ("Select beside an unknown descriptor and an invalid key", BAD_NAMES, {":x": X1}, + {"Select": "bad"}, SELECT_MSG), + ("ReturnConsumedCapacity beside an unknown descriptor and an invalid key", BAD_NAMES, + {":x": X1}, {"ReturnConsumedCapacity": "bad"}, RCC_MSG), + ("AttributesToGet beside an unknown descriptor and an invalid key", BAD_NAMES, {":x": X1}, + {"AttributesToGet": ["a"]}, ATTRIBUTES_TO_GET_MIX), +] + +# (row, ExpressionAttributeNames, ExpressionAttributeValues or None, the +# service's message), with KeyConditions and no KeyConditionExpression. +NAMES_WITHOUT_AN_EXPRESSION = [ + ("invalid key alone", BAD_NAMES, None, INVALID_KEY), + ("invalid key beside S x", BAD_NAMES, {":v": SX}, INVALID_KEY), + ("invalid key beside N bob", BAD_NAMES, {":v": NB}, INVALID_KEY), + ("valid key beside N bob", {"#a": "a"}, {":v": NB}, NUMERIC + "bob"), +] + + +def _assert_validation(status, payload, expected): + assert status == 400, payload + assert payload.get("__type", "").endswith("ValidationException"), payload + assert payload.get("message", payload.get("Message")) == expected + + +class TestExpressionAttributeNamesOrder: + """The ExpressionAttributeNames checks (an empty map, a key that is not + `#` and a name, an empty name) are reported after Limit, + ReturnConsumedCapacity and the parameter mix, and ahead of the number + check, a duplicate set member, Select and a value the service cannot read + as one type, whatever the member order (measured 2026-11-19). Each body is + sent with ExpressionAttributeNames ahead of the other members and after + them.""" + + @pytest.mark.parametrize("names_first", [True, False], ids=["names first", "names last"]) + @pytest.mark.parametrize("row,names,values,extra,expected", NAMES, ids=[r[0] for r in NAMES]) + def test_rows(self, dynamodb_client, ss_table, row, names, values, extra, expected, + names_first): + rest = {"ExpressionAttributeValues": {":p": SX, **values}, **extra} + names_member = {"ExpressionAttributeNames": names} + body = {"TableName": ss_table, "KeyConditionExpression": "pk = :p", + **(names_member | rest if names_first else rest | names_member)} + _assert_validation(*_raw_query(dynamodb_client, body), expected) + + @pytest.mark.parametrize("names_first", [True, False], ids=["names first", "names last"]) + @pytest.mark.parametrize("row,names,values,expected", NAMES_WITHOUT_AN_EXPRESSION, + ids=[r[0] for r in NAMES_WITHOUT_AN_EXPRESSION]) + def test_rows_without_an_expression(self, dynamodb_client, ss_table, row, names, values, + expected, names_first): + rest = {"KeyConditions": LEGACY_PK} + if values is not None: + rest["ExpressionAttributeValues"] = values + names_member = {"ExpressionAttributeNames": names} + body = {"TableName": ss_table, + **(names_member | rest if names_first else rest | names_member)} + _assert_validation(*_raw_query(dynamodb_client, body), expected) From cd7e8e8b6a50a0a9d8b8956cac801631033610f1 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:33:07 +0000 Subject: [PATCH 18/30] fix(query): read a null payload as no payload On Query, {"S": null} beside an invalid Select answered `SerializationException: S value must be a string`. The request checks read {"S": null} as an S, so the Select check failed. The shape fault check then read the S payload as a JSON type fault. Main answers the Select text, as the service does. The service reads a type descriptor with a null payload as absent. To the service, {"S": null} is a value it cannot read as one type, and the request takes that order of checks. Beside an invalid Select it answers the Select text. Beside a Limit of 0 it answers the Limit text that names the value. Alone it answers `ExpressionAttributeValues contains invalid value: Supplied AttributeValue is empty, must contain exactly one of the supported datatypes for key :v`. The service accepts {"S": null, "N": "1"} in a FilterExpression. Each request went to the service twice on 2026-11-19. unreadable counts a type descriptor with a null payload as a part the service cannot read, while first_fault and make_readable skip it. --- crates/engine/src/query_key_values.rs | 7 +- .../engine/src/query_key_values/unreadable.rs | 32 ++++---- .../src/query_key_values/unreadable_tests.rs | 75 +++++++++++++++++++ tests/test_query_value_shapes.py | 29 +++++-- 4 files changed, 123 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index eb4b2c550..da1fa8587 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -319,7 +319,10 @@ impl Fault<'_> { /// `L` items are visited in document order and `M` members in key order: this /// build of `serde_json` keeps an object's members sorted by key. A value of /// another JSON type, and an `N` or `NS` payload of the wrong JSON type, are -/// shape faults the deserializer reports. +/// shape faults the deserializer reports. A type descriptor with a null +/// payload counts as absent, as the service reads it (measured 2026-11-19: +/// `{"S": null}` answers the empty value text, and `{"S": null, "N": "1"}` in +/// a `FilterExpression` is accepted). /// /// With several type descriptors, the service reads each payload in the order /// of [`TYPE_DESCRIPTORS`], whatever order the request wrote them in, and @@ -334,7 +337,7 @@ fn first_fault<'a>(value: &'a Value, member: Option<&'a str>) -> Option = TYPE_DESCRIPTORS .iter() - .filter_map(|&descriptor| Some((descriptor, map.get(descriptor)?))) + .filter_map(|&descriptor| Some((descriptor, map.get(descriptor).filter(|p| !p.is_null())?))) .collect(); let fault = payloads .iter() diff --git a/crates/engine/src/query_key_values/unreadable.rs b/crates/engine/src/query_key_values/unreadable.rs index 3a0467776..68ca5060e 100644 --- a/crates/engine/src/query_key_values/unreadable.rs +++ b/crates/engine/src/query_key_values/unreadable.rs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 //! `ExpressionAttributeValues` entries the service cannot read as one type: a -//! null, no type descriptor it knows, more than one, or one it does not know -//! beside one it does, in the value or in any value an `L` or `M` holds. A -//! `Query` with such an entry takes its own order of checks (see -//! [`unreadable_value_checks`]), and the shape fault check reads the entry with -//! those parts replaced (see [`readable_for_shape_check`]). +//! null, no type descriptor it knows, more than one, one it does not know +//! beside one it does, or one with a null payload, in the value or in any +//! value an `L` or `M` holds. A `Query` with such an entry takes its own order +//! of checks (see [`unreadable_value_checks`]), and the shape fault check reads +//! the entry with those parts replaced (see [`readable_for_shape_check`]). use std::borrow::Cow; @@ -18,9 +18,11 @@ use super::{ }; /// Whether the service cannot read `value` as exactly one AttributeValue type: -/// a null, no type descriptor it knows, more than one, or one it does not know -/// beside one it does, in the value or in any value an `L` or `M` holds. A -/// value of another JSON type is a shape fault instead. +/// a null, no type descriptor it knows, more than one, one it does not know +/// beside one it does, or one with a null payload, in the value or in any +/// value an `L` or `M` holds (measured 2026-11-19: `{"S": null}` beside a +/// `Limit` of 0 answers `Value '0' at 'limit'`, as `{"X": "1"}` does). A value +/// of another JSON type is a shape fault instead. pub(super) fn unreadable(value: &Value) -> bool { match value { Value::Null => true, @@ -31,6 +33,7 @@ pub(super) fn unreadable(value: &Value) -> bool { match (known.next(), known.next()) { (Some((key, inner)), None) => { map.len() > 1 + || inner.is_null() || match (key.as_str(), inner) { ("L", Value::Array(items)) => items.iter().any(unreadable), ("M", Value::Object(members)) => members.values().any(unreadable), @@ -70,16 +73,19 @@ pub(super) fn readable_for_shape_check(body: &Value) -> Cow<'_, Value> { /// Replace each part of `value` the service cannot read as one type, in the /// value and in the values an `L` or `M` holds. A null, or an object with no /// type descriptor the service knows, becomes `{"NULL": true}`. An unknown -/// descriptor beside a known one is dropped. An object with several known -/// descriptors becomes an `L` of one value per descriptor, so the deserializer -/// still reads each payload (measured 2026-11-11: `{"L": [{"S": "a", "N": -/// "1"}, "x"]}` and `{"S": "a", "N": 1}` answer `SerializationException`). A +/// descriptor beside a known one, and a known one with a null payload, are +/// dropped. An object with several known descriptors becomes an `L` of one +/// value per descriptor, so the deserializer still reads each payload +/// (measured 2026-11-11: `{"L": [{"S": "a", "N": "1"}, "x"]}` and `{"S": "a", +/// "N": 1}` answer `SerializationException`). A /// value of another JSON type is left for the deserializer to report. fn make_readable(value: &mut Value) { let replacement = match value { Value::Null => Some(null_value()), Value::Object(map) => { - map.retain(|key, _| TYPE_DESCRIPTORS.contains(&key.as_str())); + map.retain(|key, payload| { + TYPE_DESCRIPTORS.contains(&key.as_str()) && !payload.is_null() + }); if map.len() > 1 { let mut parts: Vec = std::mem::take(map) .into_iter() diff --git a/crates/engine/src/query_key_values/unreadable_tests.rs b/crates/engine/src/query_key_values/unreadable_tests.rs index 9aa20aa89..2864157ee 100644 --- a/crates/engine/src/query_key_values/unreadable_tests.rs +++ b/crates/engine/src/query_key_values/unreadable_tests.rs @@ -363,3 +363,78 @@ fn a_json_type_fault_inside_a_value_the_service_cannot_read_is_a_shape_fault() { ) ); } + +#[test] +fn a_type_descriptor_with_a_null_payload_counts_as_absent() { + // Measured 2026-11-19 on Query, each body twice: the service reads a null + // payload as no payload, so `{"S": null}` is a value it cannot read as one + // type, and the request takes that order of checks. + let select = "Value 'bad' at 'select' failed to satisfy constraint: Member must satisfy \ + enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, \ + ALL_PROJECTED_ATTRIBUTES]"; + let limit = "Value '0' at 'limit' failed to satisfy constraint: Member must have value \ + greater than or equal to 1"; + let empty = format!("{INVALID_VALUE}{EMPTY} for key :v"); + for (value, extra, expected) in [ + (json!({"S": null}), json!({}), empty.clone()), + (json!({"N": null}), json!({}), empty.clone()), + (json!({"L": [{"S": null}]}), json!({}), empty), + ( + json!({"S": null, "N": "bob"}), + json!({}), + format!( + "{INVALID_VALUE}The parameter cannot be converted to a numeric value: bob for \ + key :v" + ), + ), + ( + json!({"S": null}), + json!({"Select": "bad"}), + format!("1 validation error detected: {select}"), + ), + ( + json!({"S": null}), + json!({"Limit": 0}), + format!("1 validation error detected: {limit}"), + ), + ( + json!({"S": null}), + json!({"Select": "bad", "Limit": 0}), + format!("2 validation errors detected: {select}; {limit}"), + ), + ( + json!({"S": null}), + json!({"ReturnConsumedCapacity": "bad"}), + "1 validation error detected: Value 'bad' at 'returnConsumedCapacity' failed to \ + satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]" + .to_owned(), + ), + ( + json!({"S": null}), + json!({"AttributesToGet": ["a"]}), + "Can not use both expression and non-expression parameters in the same request: \ + Non-expression parameters: {AttributesToGet} Expression parameters: \ + {KeyConditionExpression}" + .to_owned(), + ), + ( + json!({"S": null}), + json!({"ExpressionAttributeNames": {"a": "b"}}), + r#"ExpressionAttributeNames contains invalid key: Syntax error; key: "a""#.to_owned(), + ), + ] { + let body = body_with(json!({":p": {"S": "x"}, ":v": value}), extra); + assert_eq!( + message(validate_query_request_body(&body)), + Some(expected), + "{body}" + ); + } + // `{"S": null, "N": "1"}` reads as `{"N": "1"}`: the service accepts it in + // a FilterExpression. + let body = body_with( + json!({":p": {"S": "x"}, ":v": {"S": null, "N": "1"}}), + json!({"FilterExpression": "a = :v"}), + ); + assert!(validate_query_request_body(&body).is_ok()); +} diff --git a/tests/test_query_value_shapes.py b/tests/test_query_value_shapes.py index 0dfafd527..fb67d26fe 100644 --- a/tests/test_query_value_shapes.py +++ b/tests/test_query_value_shapes.py @@ -154,16 +154,35 @@ def test_control_without_a_shape_fault_answers_the_check(self, dynamodb_client, INVALID_VALUE + NUMERIC + "aaa for key :z"), ("N bob then S with Limit 0", {":z": {"N": "bob", "S": "x"}}, {"Limit": 0}, "1 validation error detected: " + LIMIT_0_AT), + # A type descriptor with a null payload reads as no payload (measured + # 2026-11-19). + ("S null", {":z": {"S": None}}, {}, INVALID_VALUE + EMPTY_AV + " for key :z"), + ("N null", {":z": {"N": None}}, {}, INVALID_VALUE + EMPTY_AV + " for key :z"), + ("S null in an L", {":z": {"L": [{"S": None}]}}, {}, INVALID_VALUE + EMPTY_AV + " for key :z"), + ("S null beside N bob", {":z": {"S": None, "N": "bob"}}, {}, + INVALID_VALUE + NUMERIC + "bob for key :z"), + ("S null with an invalid Select", {":z": {"S": None}}, {"Select": "bad"}, + "1 validation error detected: Value 'bad' at 'select' failed to satisfy constraint: Member " + "must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, " + "ALL_PROJECTED_ATTRIBUTES]"), + ("S null with Limit 0", {":z": {"S": None}}, {"Limit": 0}, + "1 validation error detected: " + LIMIT_0_AT), + ("S null with ReturnConsumedCapacity", {":z": {"S": None}}, {"ReturnConsumedCapacity": "bad"}, + RCC_MSG), + ("S null with AttributesToGet", {":z": {"S": None}}, {"AttributesToGet": ["a"]}, + "Can not use both expression and non-expression parameters in the same request: " + "Non-expression parameters: {AttributesToGet} Expression parameters: {KeyConditionExpression}"), ] class TestValuesTheServiceCannotReadAsOneType: """A value in ExpressionAttributeValues that the service cannot read as one - type (a null, no type descriptor it knows, more than one, or an unknown one - beside a known one) is named with its placeholder, and beside such a value - Select, ReturnConsumedCapacity and Limit are reported together, ahead of - the parameter mix (measured 2026-11-11). boto3 cannot send an unknown - descriptor or a null, so the bodies go out as written.""" + type (a null, no type descriptor it knows, more than one, an unknown one + beside a known one, or a known one with a null payload) is named with its + placeholder, and beside such a value Select, ReturnConsumedCapacity and + Limit are reported together, ahead of the parameter mix (measured + 2026-11-11 and 2026-11-19). boto3 cannot send an unknown descriptor or a + null, so the bodies go out as written.""" @pytest.mark.parametrize("row,values,extra,expected", UNREADABLE, ids=[r[0] for r in UNREADABLE]) def test_rows(self, dynamodb_client, ss_table, row, values, extra, expected): From bf3f970bc9d0ee5092c9663ffdb9d84aad004fb4 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:17:38 +0000 Subject: [PATCH 19/30] fix(query): report an empty name after a value the service cannot read On Query, an empty name in ExpressionAttributeNames beside a value the service cannot read as one type answered the empty name text. The service answers the value's text. For {"#a": ""} beside {"X": "1"} it answers `ExpressionAttributeValues contains invalid value: Supplied AttributeValue is empty, must contain exactly one of the supported datatypes for key :x`. Beside {}, {"N": "1", "S": "x"}, a null and {"S": null}, the same names map answers that value's text. Beside {"X": "1"}, {"#a": "", "b": "c"} answers `ExpressionAttributeNames contains invalid key: Syntax error; key: "b"`. Beside {"S": "a", "X": "1"}, which has no fault of its own, {"#a": ""} answers the empty name text. Each body went to the service twice, with the names map first and last, on 2026-11-19. On that path the service checks the keys of the names map ahead of the values. Those checks refuse an invalid key, a key over 255 bytes and an empty map. The service makes the empty name check after the values. unreadable_value_checks now runs the key checks ahead of the values. It runs them through the same deserializer, with each name replaced. The whole names check runs after the values. The unit tests share one set of message texts, and the names tests are one table of rows. The handler and pre-IAM comments point to validate_query_request_body, whose doc lists the order of the checks. --- crates/engine/src/query.rs | 9 +- crates/engine/src/query_key_values.rs | 31 ++- .../src/query_key_values/names_tests.rs | 224 ++++++------------ .../query_key_values/request_order_tests.rs | 24 +- crates/engine/src/query_key_values/tests.rs | 38 ++- .../engine/src/query_key_values/unreadable.rs | 25 +- .../src/query_key_values/unreadable_tests.rs | 149 ++++-------- crates/server/src/request_helpers.rs | 19 +- tests/test_query_value_shapes.py | 42 ++-- 9 files changed, 230 insertions(+), 331 deletions(-) diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 4cd0d3567..ce1cb2cdc 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -47,13 +47,8 @@ pub async fn handle_query( body: Value, ctx: &OperationContext, ) -> Result { - // Request-time checks on the raw body, in the service's order: Limit, the - // ReturnConsumedCapacity enum, the expression and non-expression parameter - // mix, the ExpressionAttributeNames map, every number in - // ExpressionAttributeValues, the Select enum. They run before typed - // deserialization so a field that does not deserialize does not stop the - // ones before it. The server runs the same function ahead of the IAM - // decision; see `query_key_values`. + // The request-time checks on the raw body, before typed deserialization; + // see `query_key_values::validate_query_request_body`. crate::query_key_values::validate_query_request_body(&body)?; let input: QueryInput = serde_json::from_value(body).map_err(crate::deserialize_error)?; diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index da1fa8587..6dbfa5ea8 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -10,10 +10,8 @@ //! `The parameter cannot be converted to a numeric value: ` (or the //! overflow, underflow and 38-digit messages). Every value in the map is //! checked, whether the key condition, the filter or nothing reads it. The -//! check runs at request time, after the `Limit` check, the -//! `ReturnConsumedCapacity` enum check, the expression and non-expression -//! parameter mix check and the `ExpressionAttributeNames` check, and before -//! the table is looked up; see [`validate_query_request_body`]; +//! check runs at request time, before the table is looked up, in the order +//! [`validate_query_request_body`] gives; //! 2. a key condition value whose type is not the key attribute's //! `AttributeDefinitions` type answers `One or more parameter values were //! invalid: Condition parameter type does not match schema type`, on the @@ -106,7 +104,11 @@ const SELECT: &[&str] = &[ /// whose `dynamodb:LeadingKeys` fence cannot bind a number that does not parse /// gets the request's `ValidationException` rather than /// `AccessDeniedException`. That call goes through this function too, so it -/// answers the shape fault first as well. +/// answers the shape fault first as well. It comes after the server's +/// cross-account refusal, so a `Query` that names a table ARN in another +/// account answers `AccessDeniedException` without these checks, where the +/// service makes them first (measured 2026-11-12: with such an ARN, `{"N": +/// "bob"}` answers the numeric message and a `Limit` of 0 the `Limit` text). /// /// # Errors /// @@ -244,6 +246,25 @@ pub(crate) fn validate_names(body: &Value) -> Result<(), DynamoDbError> { } } +/// The key checks of [`validate_names`] alone: an empty map, a key that is not +/// `#` and a name, and a key over 255 bytes. Each name is replaced with a +/// name that is not empty, so an empty name passes here. Beside a value the +/// service cannot read as one type, the service makes the key checks ahead of +/// the values and reports an empty name after them; see +/// `unreadable_value_checks`. +fn validate_name_keys(body: &Value) -> Result<(), DynamoDbError> { + match body.get("ExpressionAttributeNames") { + Some(Value::Object(names)) => { + let keys: Map = names + .keys() + .map(|key| (key.clone(), Value::from("a"))) + .collect(); + validate_names(&serde_json::json!({ "ExpressionAttributeNames": keys })) + } + _ => validate_names(body), + } +} + /// Whether `field` is in the body with a value other than `null`, as a typed /// `Option` field would deserialize to `Some`. fn present(body: &Value, field: &str) -> bool { diff --git a/crates/engine/src/query_key_values/names_tests.rs b/crates/engine/src/query_key_values/names_tests.rs index a81430bf2..bf9549711 100644 --- a/crates/engine/src/query_key_values/names_tests.rs +++ b/crates/engine/src/query_key_values/names_tests.rs @@ -1,161 +1,95 @@ // SPDX-License-Identifier: Apache-2.0 -//! Tests for the place of the `ExpressionAttributeNames` check among the +//! Tests for the place of the `ExpressionAttributeNames` checks among the //! request-time `Query` checks. -use serde_json::{Value, json}; +use serde_json::json; -use super::tests::{body_with, message}; +use super::tests::{ + EMPTY, INVALID_KEY, INVALID_VALUE, LIMIT_ZERO, MIX, NULL, NUMERIC_BOB, RCC_BAD, SELECT_BAD, + SEVERAL, body_with, message, one_error, +}; use super::{LIMIT_BELOW_ONE, validate_query_request_body}; -const INVALID_KEY: &str = - r#"ExpressionAttributeNames contains invalid key: Syntax error; key: "a""#; -const NUMERIC_BOB: &str = "The parameter cannot be converted to a numeric value: bob"; -const RCC: &str = "1 validation error detected: Value 'bad' at 'returnConsumedCapacity' \ - failed to satisfy constraint: Member must satisfy enum value set: \ - [INDEXES, TOTAL, NONE]"; -const SELECT: &str = "1 validation error detected: Value 'bad' at 'select' failed to satisfy \ - constraint: Member must satisfy enum value set: [SPECIFIC_ATTRIBUTES, \ - COUNT, ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]"; -const MIX: &str = "Can not use both expression and non-expression parameters in the same \ - request: Non-expression parameters: {AttributesToGet} Expression \ - parameters: {KeyConditionExpression}"; - -/// The answer for a body with `values` in `ExpressionAttributeValues`, `names` -/// in `ExpressionAttributeNames` and the `extra` members. -fn answer(values: Value, names: Value, extra: Value) -> Option { - let mut body = body_with(values, extra); - body["ExpressionAttributeNames"] = names; - message(validate_query_request_body(&body)) -} - #[test] -fn an_invalid_names_map_is_reported_after_the_mix_and_ahead_of_the_numbers() { - // Measured 2026-11-19, with the names map ahead of the other members and - // after them: each names fault beside `{"N": "bob"}` answers the names - // text, as an invalid key does beside a set with a duplicate member and - // beside an invalid Select. A Limit of 0, an invalid - // ReturnConsumedCapacity and a mix are reported ahead of an invalid key. - let bad_number = json!({":p": {"S": "x"}, ":n": {"N": "bob"}}); - for (names, expected) in [ - (json!({"a": "b"}), INVALID_KEY), - (json!({}), "ExpressionAttributeNames must not be empty"), - ( - json!({"#a": ""}), - "ExpressionAttributeNames contains invalid value: Empty attribute name for key #a", - ), - ] { - assert_eq!( - answer(bad_number.clone(), names.clone(), json!({})).as_deref(), - Some(expected), - "{names}" - ); - } - for (values, extra) in [ - ( - json!({":p": {"S": "x"}, ":d": {"NS": ["1", "1"]}}), - json!({}), - ), - (json!({":p": {"S": "x"}}), json!({"Select": "bad"})), - ] { - assert_eq!( - answer(values, json!({"a": "b"}), extra.clone()).as_deref(), - Some(INVALID_KEY), - "{extra}" - ); - } - for (extra, expected) in [ - (json!({"Limit": 0}), LIMIT_BELOW_ONE), - (json!({"ReturnConsumedCapacity": "bad"}), RCC), - (json!({"AttributesToGet": ["a"]}), MIX), - ] { - assert_eq!( - answer(bad_number.clone(), json!({"a": "b"}), extra.clone()).as_deref(), - Some(expected), - "{extra}" - ); - } - // A names map the deserializer accepts, used or not, leaves the answer to - // the number check. - assert_eq!( - answer(bad_number, json!({"#a": "a"}), json!({})).as_deref(), - Some(NUMERIC_BOB) +fn the_names_checks_take_the_service_order() { + // Measured 2026-11-19, each body with the names map ahead of the other + // members and after them, with the same answer in both orders. With + // readable values, the names checks come after a Limit of 0, an invalid + // ReturnConsumedCapacity and the mix, and ahead of an N value that is not + // a number, a set with a duplicate member and an invalid Select. Beside a + // value the service cannot read as one type, the key checks and the empty + // map come after the reported-together Select, ReturnConsumedCapacity and + // Limit step and the mix, and ahead of the value. An empty name comes + // after the value, and is reported when no value has a fault of its own + // (`{"S": "a", "X": "1"}` reads as an S). With KeyConditions and no + // KeyConditionExpression, the names are checked though no expression + // reads them. + // + // Each row holds: whether the key condition is KeyConditions (else `pk = + // :p` with `:p = {"S": "x"}`), the names map, the members (those that + // start with `:` go into ExpressionAttributeValues), and the answer. + let (rcc, select, limit) = ( + one_error(RCC_BAD), + one_error(SELECT_BAD), + one_error(LIMIT_ZERO), ); -} - -#[test] -fn beside_a_value_the_service_cannot_read_the_names_map_follows_the_mix() { - // Measured 2026-11-19, in either member order: an invalid key is reported - // ahead of a value the service cannot read as one type, and the - // reported-together Select, ReturnConsumedCapacity and Limit step and the - // mix are reported ahead of the key. - for value in [json!({"X": "1"}), json!({}), json!({"N": "1", "S": "x"})] { - assert_eq!( - answer( - json!({":p": {"S": "x"}, ":x": value}), - json!({"a": "b"}), - json!({}) - ) - .as_deref(), - Some(INVALID_KEY), - "{value}" - ); - } - let limit = "1 validation error detected: Value '0' at 'limit' failed to satisfy \ - constraint: Member must have value greater than or equal to 1"; - for (extra, expected) in [ - (json!({"Limit": 0}), limit), - (json!({"Select": "bad"}), SELECT), - (json!({"ReturnConsumedCapacity": "bad"}), RCC), - (json!({"AttributesToGet": ["a"]}), MIX), - ] { - assert_eq!( - answer( - json!({":p": {"S": "x"}, ":x": {"X": "1"}}), - json!({"a": "b"}), - extra.clone() - ) - .as_deref(), - Some(expected), - "{extra}" - ); - } -} - -#[test] -fn the_names_map_is_checked_when_no_expression_reads_it() { - // Measured 2026-11-19 with KeyConditions and no KeyConditionExpression: an - // invalid key is reported alone, beside a value nothing reads and beside - // `{"N": "bob"}`. A valid names map leaves the number check to answer. - let key_conditions = - json!({"pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]}}); - for values in [ - None, - Some(json!({":v": {"S": "x"}})), - Some(json!({":v": {"N": "bob"}})), - ] { - let mut body = json!({ - "TableName": "t", - "KeyConditions": key_conditions, - "ExpressionAttributeNames": {"a": "b"}, - }); - if let Some(values) = values { - body["ExpressionAttributeValues"] = values; + let value = |reason: &str, key: &str| format!("{INVALID_VALUE}{reason} for key {key}"); + let (empty_x, empty_v) = (value(EMPTY, ":x"), value(EMPTY, ":v")); + let (several_v, null_x) = (value(SEVERAL, ":v"), value(NULL, ":x")); + let empty_map = "ExpressionAttributeNames must not be empty"; + let empty_name = + "ExpressionAttributeNames contains invalid value: Empty attribute name for key #a"; + let key_b = r#"ExpressionAttributeNames contains invalid key: Syntax error; key: "b""#; + let rows = [ + json!([false, {"a": "b"}, {":n": {"N": "bob"}}, INVALID_KEY]), + json!([false, {}, {":n": {"N": "bob"}}, empty_map]), + json!([false, {"#a": ""}, {":n": {"N": "bob"}}, empty_name]), + json!([false, {"a": "b"}, {":d": {"NS": ["1", "1"]}}, INVALID_KEY]), + json!([false, {"a": "b"}, {"Select": "bad"}, INVALID_KEY]), + json!([false, {"a": "b"}, {":n": {"N": "bob"}, "Limit": 0}, LIMIT_BELOW_ONE]), + json!([false, {"a": "b"}, {":n": {"N": "bob"}, "ReturnConsumedCapacity": "bad"}, rcc]), + json!([false, {"a": "b"}, {":n": {"N": "bob"}, "AttributesToGet": ["a"]}, MIX]), + json!([false, {"#a": "a"}, {":n": {"N": "bob"}}, NUMERIC_BOB]), + json!([false, {"a": "b"}, {":x": {"X": "1"}}, INVALID_KEY]), + json!([false, {"a": "b"}, {":x": {}}, INVALID_KEY]), + json!([false, {"a": "b"}, {":x": {"N": "1", "S": "x"}}, INVALID_KEY]), + json!([false, {"a": "b"}, {":x": {"X": "1"}, "Limit": 0}, limit]), + json!([false, {"a": "b"}, {":x": {"X": "1"}, "Select": "bad"}, select]), + json!([false, {"a": "b"}, {":x": {"X": "1"}, "ReturnConsumedCapacity": "bad"}, rcc]), + json!([false, {"a": "b"}, {":x": {"X": "1"}, "AttributesToGet": ["a"]}, MIX]), + json!([false, {"#a": ""}, {":x": {"X": "1"}}, empty_x]), + json!([false, {"#a": ""}, {":x": {}}, empty_x]), + json!([false, {"#a": ""}, {":v": {"N": "1", "S": "x"}}, several_v]), + json!([false, {"#a": ""}, {":x": null}, null_x]), + json!([false, {"#a": ""}, {":v": {"S": null}}, empty_v]), + json!([false, {"#a": "", "b": "c"}, {":x": {"X": "1"}}, key_b]), + json!([false, {"#a": ""}, {":a": {"S": "a", "X": "1"}}, empty_name]), + json!([false, {"#a": ""}, {":v": {"S": null, "N": "1"}}, empty_name]), + json!([true, {"a": "b"}, {}, INVALID_KEY]), + json!([true, {"a": "b"}, {":v": {"S": "x"}}, INVALID_KEY]), + json!([true, {"a": "b"}, {":v": {"N": "bob"}}, INVALID_KEY]), + json!([true, {"#a": "a"}, {":v": {"N": "bob"}}, NUMERIC_BOB]), + ]; + for row in rows { + let mut body = if row[0] == true { + json!({"TableName": "t", "KeyConditions": { + "pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]}}}) + } else { + body_with(json!({":p": {"S": "x"}}), json!({})) + }; + body["ExpressionAttributeNames"] = row[1].clone(); + for (member, value) in row[2].as_object().into_iter().flatten() { + if member.starts_with(':') { + body["ExpressionAttributeValues"][member] = value.clone(); + } else { + body[member] = value.clone(); + } } assert_eq!( message(validate_query_request_body(&body)).as_deref(), - Some(INVALID_KEY), + row[3].as_str(), "{body}" ); } - let body = json!({ - "TableName": "t", - "KeyConditions": key_conditions, - "ExpressionAttributeNames": {"#a": "a"}, - "ExpressionAttributeValues": {":v": {"N": "bob"}}, - }); - assert_eq!( - message(validate_query_request_body(&body)).as_deref(), - Some(NUMERIC_BOB) - ); } diff --git a/crates/engine/src/query_key_values/request_order_tests.rs b/crates/engine/src/query_key_values/request_order_tests.rs index c83d769ae..88d269c9d 100644 --- a/crates/engine/src/query_key_values/request_order_tests.rs +++ b/crates/engine/src/query_key_values/request_order_tests.rs @@ -6,7 +6,7 @@ use extenddb_core::error::DynamoDbError; use serde_json::json; -use super::tests::message; +use super::tests::{LIMIT_ZERO, NUMERIC_BOB, RCC_BAD, message, one_error}; use super::{LIMIT_BELOW_ONE, validate_query_request_body}; #[test] @@ -38,7 +38,7 @@ fn request_time_checks_run_limit_then_mix_then_numbers() { assert_eq!( message(validate_query_request_body(&bad_number)).as_deref(), - Some("The parameter cannot be converted to a numeric value: bob") + Some(NUMERIC_BOB) ); // A number only a FilterExpression reads, and one nothing reads. @@ -57,7 +57,7 @@ fn request_time_checks_run_limit_then_mix_then_numbers() { ] { assert_eq!( message(validate_query_request_body(&body)).as_deref(), - Some("The parameter cannot be converted to a numeric value: bob") + Some(NUMERIC_BOB) ); } @@ -89,16 +89,13 @@ fn enum_checks_sit_on_either_side_of_the_numbers() { rcc["ReturnConsumedCapacity"] = serde_json::json!("bad"); assert_eq!( message(validate_query_request_body(&rcc)).as_deref(), - Some( - "1 validation error detected: Value 'bad' at 'returnConsumedCapacity' failed to \ - satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]" - ) + Some(one_error(RCC_BAD).as_str()) ); let mut select = bad_number.clone(); select["Select"] = serde_json::json!("bad"); assert_eq!( message(validate_query_request_body(&select)).as_deref(), - Some("The parameter cannot be converted to a numeric value: bob") + Some(NUMERIC_BOB) ); for field in ["ReturnConsumedCapacity", "Select"] { let mut limit = bad_number.clone(); @@ -123,10 +120,6 @@ fn enum_checks_sit_on_either_side_of_the_numbers() { ); } -const RCC_MSG: &str = "1 validation error detected: Value 'bad' at 'returnConsumedCapacity' \ - failed to satisfy constraint: Member must satisfy enum value set: \ - [INDEXES, TOTAL, NONE]"; - #[test] fn return_consumed_capacity_is_reported_ahead_of_the_parameter_mix() { // Measured 2026-11-11 with each non-expression parameter beside @@ -165,7 +158,7 @@ fn return_consumed_capacity_is_reported_ahead_of_the_parameter_mix() { body["ReturnConsumedCapacity"] = json!("bad"); assert_eq!( message(validate_query_request_body(&body)).as_deref(), - Some(RCC_MSG), + Some(one_error(RCC_BAD).as_str()), "{name}" ); body["Limit"] = json!(0); @@ -264,10 +257,7 @@ fn a_shape_fault_in_another_field_is_reported_ahead_of_the_checks() { }); assert_eq!( message(validate_query_request_body(&unknown_type)).as_deref(), - Some( - "1 validation error detected: Value '0' at 'limit' failed to satisfy constraint: \ - Member must have value greater than or equal to 1" - ) + Some(one_error(LIMIT_ZERO).as_str()) ); // A body that passes every check is left to the handler's deserializer. diff --git a/crates/engine/src/query_key_values/tests.rs b/crates/engine/src/query_key_values/tests.rs index 2a2bce4b4..3a370992d 100644 --- a/crates/engine/src/query_key_values/tests.rs +++ b/crates/engine/src/query_key_values/tests.rs @@ -68,6 +68,33 @@ pub(super) fn message(result: Result<(), DynamoDbError>) -> Option { } } +/// The service's texts that the request-time check tests expect. +pub(super) const INVALID_VALUE: &str = "ExpressionAttributeValues contains invalid value: "; +pub(super) const EMPTY: &str = + "Supplied AttributeValue is empty, must contain exactly one of the supported datatypes"; +pub(super) const SEVERAL: &str = "Supplied AttributeValue has more than one datatypes set, must \ + contain exactly one of the supported datatypes"; +pub(super) const NULL: &str = "The supplied Item contains a null AttributeValue"; +pub(super) const NUMERIC_BOB: &str = "The parameter cannot be converted to a numeric value: bob"; +pub(super) const INVALID_KEY: &str = + r#"ExpressionAttributeNames contains invalid key: Syntax error; key: "a""#; +pub(super) const MIX: &str = "Can not use both expression and non-expression parameters in the \ + same request: Non-expression parameters: {AttributesToGet} \ + Expression parameters: {KeyConditionExpression}"; +pub(super) const SELECT_BAD: &str = "Value 'bad' at 'select' failed to satisfy constraint: Member \ + must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, \ + ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]"; +pub(super) const RCC_BAD: &str = "Value 'bad' at 'returnConsumedCapacity' failed to satisfy \ + constraint: Member must satisfy enum value set: [INDEXES, \ + TOTAL, NONE]"; +pub(super) const LIMIT_ZERO: &str = "Value '0' at 'limit' failed to satisfy constraint: Member \ + must have value greater than or equal to 1"; + +/// `clause` as the service's text for one validation error. +pub(super) fn one_error(clause: &str) -> String { + format!("1 validation error detected: {clause}") +} + const SS: &[(&str, ScalarAttributeType)] = &[ ("pk", ScalarAttributeType::S), ("sk", ScalarAttributeType::S), @@ -240,10 +267,7 @@ fn undefined_placeholder_and_undefined_attribute_are_left_to_other_checks() { #[test] fn number_values_that_are_not_numbers_are_refused_with_the_bare_message() { let cases = [ - ( - "bob", - "The parameter cannot be converted to a numeric value: bob", - ), + ("bob", NUMERIC_BOB), ( "1e", "The parameter cannot be converted to a numeric value: 1e", @@ -295,7 +319,7 @@ fn every_value_in_the_map_is_checked_whatever_reads_it() { let values = HashMap::from([(":p".to_owned(), s("x")), (":n".to_owned(), n("bob"))]); assert_eq!( message(validate_expression_attribute_value_numbers(&values)).as_deref(), - Some("The parameter cannot be converted to a numeric value: bob") + Some(NUMERIC_BOB) ); } @@ -320,7 +344,7 @@ fn numbers_nested_in_sets_lists_and_maps_are_checked() { let values = HashMap::from([(":p".to_owned(), s("x")), (":n".to_owned(), value.clone())]); assert_eq!( message(validate_expression_attribute_value_numbers(&values)).as_deref(), - Some("The parameter cannot be converted to a numeric value: bob"), + Some(NUMERIC_BOB), "{value:?}" ); } @@ -460,7 +484,7 @@ fn a_value_that_does_not_deserialize_does_not_stop_the_number_check_of_another() ); assert_eq!( message(validate_query_request_body(&body)).as_deref(), - Some("The parameter cannot be converted to a numeric value: bob"), + Some(NUMERIC_BOB), "{other}" ); } diff --git a/crates/engine/src/query_key_values/unreadable.rs b/crates/engine/src/query_key_values/unreadable.rs index 68ca5060e..7a9a1f259 100644 --- a/crates/engine/src/query_key_values/unreadable.rs +++ b/crates/engine/src/query_key_values/unreadable.rs @@ -14,7 +14,7 @@ use serde_json::{Map, Value}; use super::{ RETURN_CONSUMED_CAPACITY, SELECT, TYPE_DESCRIPTORS, first_fault, sorted_entries, - validate_names, validate_no_parameter_mix, + validate_name_keys, validate_names, validate_no_parameter_mix, }; /// Whether the service cannot read `value` as exactly one AttributeValue type: @@ -130,11 +130,12 @@ fn null_value() -> Value { /// 'limit' failed to satisfy constraint: Member must have value greater /// than or equal to 1`; /// 2. the expression and non-expression parameter mix; -/// 3. the `ExpressionAttributeNames` map (measured 2026-11-19: an invalid -/// names key beside `{"X": "1"}`, `{}` or `{"N": "1", "S": "x"}` answers -/// the names text, in either member order, and beside such a value a -/// `Limit` of 0, an invalid `Select` or `ReturnConsumedCapacity` and a mix -/// are reported ahead of it); see [`validate_names`]; +/// 3. the `ExpressionAttributeNames` key checks: an invalid key, a key over +/// 255 bytes and an empty map (measured 2026-11-19: an invalid names key +/// beside `{"X": "1"}`, `{}` or `{"N": "1", "S": "x"}` answers the names +/// text, in either member order, and beside such a value a `Limit` of 0, +/// an invalid `Select` or `ReturnConsumedCapacity` and a mix are reported +/// ahead of it); see [`validate_name_keys`]; /// 4. the first fault inside a value, in document order for `L` items and in /// key order for `M` members, as `ExpressionAttributeValues contains /// invalid value: for key `: a null (`The supplied @@ -142,7 +143,13 @@ fn null_value() -> Value { /// is the value of an `M` member), no type descriptor, more than one, or an /// `N` that is not a number. Such an `N` is echoed as written, and an empty /// one has no colon after the message. No `M` with more than one member was -/// measured. +/// measured; +/// 5. an empty name in `ExpressionAttributeNames` (measured 2026-11-19 in +/// either member order: `{"#a": ""}` beside `{"X": "1"}`, `{}`, `{"N": "1", +/// "S": "x"}`, a null or `{"S": null}` answers that value's text, beside +/// `{"S": "a", "X": "1"}`, which has no fault of its own, it answers the +/// empty name text, and `{"#a": "", "b": "c"}` beside `{"X": "1"}` answers +/// the invalid key text for `b`). /// /// When several values have a fault, the service names a value it cannot read /// as one type ahead of a number fault in another value. `:u` with `{"N": @@ -189,7 +196,7 @@ pub(super) fn unreadable_value_checks( } validate_no_parameter_mix(body)?; - validate_names(body)?; + validate_name_keys(body)?; // The values the service cannot read first; the sort is stable, so each // group keeps the placeholder order. @@ -203,7 +210,7 @@ pub(super) fn unreadable_value_checks( ))); } } - Ok(()) + validate_names(body) } /// The enum violation clause for `field` when the body holds a string that is diff --git a/crates/engine/src/query_key_values/unreadable_tests.rs b/crates/engine/src/query_key_values/unreadable_tests.rs index 2864157ee..ec6006678 100644 --- a/crates/engine/src/query_key_values/unreadable_tests.rs +++ b/crates/engine/src/query_key_values/unreadable_tests.rs @@ -6,45 +6,41 @@ use extenddb_core::error::DynamoDbError; use serde_json::{Value, json}; -use super::tests::{body_with, message}; +use super::tests::{ + EMPTY, INVALID_KEY, INVALID_VALUE, LIMIT_ZERO, MIX, NULL, NUMERIC_BOB, RCC_BAD, SELECT_BAD, + SEVERAL, body_with, message, one_error, +}; use super::validate_query_request_body; -const INVALID_VALUE: &str = "ExpressionAttributeValues contains invalid value: "; -const EMPTY: &str = - "Supplied AttributeValue is empty, must contain exactly one of the supported datatypes"; - #[test] fn a_value_the_service_cannot_read_as_one_type_is_named_with_its_placeholder() { // Measured 2026-11-11, each value alone beside `:p = {"S": "x"}`. - let several = "Supplied AttributeValue has more than one datatypes set, must contain \ - exactly one of the supported datatypes"; - let null = "The supplied Item contains a null AttributeValue"; for (value, reason) in [ (json!({"X": "1"}), EMPTY.to_owned()), - (Value::Null, null.to_owned()), + (Value::Null, NULL.to_owned()), (json!({}), EMPTY.to_owned()), - (json!({"S": "a", "N": "1"}), several.to_owned()), + (json!({"S": "a", "N": "1"}), SEVERAL.to_owned()), (json!({"L": [{"X": "1"}]}), EMPTY.to_owned()), - (json!({"L": [null]}), null.to_owned()), + (json!({"L": [null]}), NULL.to_owned()), (json!({"L": [{}]}), EMPTY.to_owned()), - (json!({"L": [{"S": "a", "N": "1"}]}), several.to_owned()), + (json!({"L": [{"S": "a", "N": "1"}]}), SEVERAL.to_owned()), (json!({"L": [{"S": "a"}, {"X": "1"}]}), EMPTY.to_owned()), (json!({"M": {"k": {"X": "1"}}}), EMPTY.to_owned()), (json!({"M": {"k": {}}}), EMPTY.to_owned()), - (json!({"M": {"k": null}}), format!("{null}: k is null")), + (json!({"M": {"k": null}}), format!("{NULL}: k is null")), ( json!({"M": {"k": {"M": {"j": null}}}}), - format!("{null}: j is null"), + format!("{NULL}: j is null"), ), - (json!({"M": {"k": {"L": [null]}}}), null.to_owned()), + (json!({"M": {"k": {"L": [null]}}}), NULL.to_owned()), ( json!({"L": [{"M": {"k": null}}]}), - format!("{null}: k is null"), + format!("{NULL}: k is null"), ), // The first fault in document order. ( json!({"L": [{"N": "bob"}, {"X": "1"}]}), - "The parameter cannot be converted to a numeric value: bob".to_owned(), + NUMERIC_BOB.to_owned(), ), (json!({"L": [{"X": "1"}, {"N": "bob"}]}), EMPTY.to_owned()), ] { @@ -65,11 +61,9 @@ fn a_number_fault_in_a_value_with_several_types_is_named_ahead_of_the_several_ty // only when no payload has a fault. let numeric = |text: &str| format!("The parameter cannot be converted to a numeric value: {text}"); - let several = "Supplied AttributeValue has more than one datatypes set, must contain \ - exactly one of the supported datatypes"; for (value, reason) in [ (json!({"N": "bob", "S": "x"}), numeric("bob")), - (json!({"N": "1", "S": "x"}), several.to_owned()), + (json!({"N": "1", "S": "x"}), SEVERAL.to_owned()), ( json!({"N": "", "S": "x"}), "The parameter cannot be converted to a numeric value".to_owned(), @@ -87,10 +81,7 @@ fn a_number_fault_in_a_value_with_several_types_is_named_ahead_of_the_several_ty (json!({"S": "x", "L": [{"N": "bob"}]}), numeric("bob")), (json!({"S": "x", "M": {"a": {"N": "bob"}}}), numeric("bob")), (json!({"S": "x", "L": [{"X": "1"}]}), EMPTY.to_owned()), - ( - json!({"S": "x", "L": [null]}), - "The supplied Item contains a null AttributeValue".to_owned(), - ), + (json!({"S": "x", "L": [null]}), NULL.to_owned()), (json!({"N": "aaa", "NS": ["bbb"]}), numeric("aaa")), (json!({"N": "bbb", "L": [{"N": "aaa"}]}), numeric("bbb")), (json!({"NS": ["aaa"], "L": [{"N": "bbb"}]}), numeric("aaa")), @@ -113,11 +104,7 @@ fn a_number_fault_in_a_value_with_several_types_is_named_ahead_of_the_several_ty ); assert_eq!( message(validate_query_request_body(&body)), - Some( - "1 validation error detected: Value '0' at 'limit' failed to satisfy constraint: \ - Member must have value greater than or equal to 1" - .to_owned() - ) + Some(one_error(LIMIT_ZERO)) ); } @@ -172,23 +159,22 @@ fn a_value_the_service_cannot_read_is_named_ahead_of_a_number_fault() { // or `:a` when it holds a value it cannot read as one type (28 of 28 // requests for `:z = {"X": "1"}`), and names `:u` when the other value has // no fault of its own. - let several = "Supplied AttributeValue has more than one datatypes set, must contain \ - exactly one of the supported datatypes"; - let null = "The supplied Item contains a null AttributeValue"; - let numeric = "The parameter cannot be converted to a numeric value: bob"; for (value, reason) in [ (json!({"X": "1"}), EMPTY.to_owned()), - (Value::Null, null.to_owned()), + (Value::Null, NULL.to_owned()), (json!({}), EMPTY.to_owned()), - (json!({"S": "a", "N": "1"}), several.to_owned()), + (json!({"S": "a", "N": "1"}), SEVERAL.to_owned()), (json!({"L": [{"X": "1"}]}), EMPTY.to_owned()), - (json!({"L": [null]}), null.to_owned()), + (json!({"L": [null]}), NULL.to_owned()), (json!({"L": [{}]}), EMPTY.to_owned()), - (json!({"L": [{"S": "a", "N": "1"}]}), several.to_owned()), + (json!({"L": [{"S": "a", "N": "1"}]}), SEVERAL.to_owned()), (json!({"M": {"k": {"X": "1"}}}), EMPTY.to_owned()), - (json!({"M": {"k": null}}), format!("{null}: k is null")), + (json!({"M": {"k": null}}), format!("{NULL}: k is null")), (json!({"L": [{"S": "a"}, {"X": "1"}]}), EMPTY.to_owned()), - (json!({"L": [{"N": "bob"}, {"X": "1"}]}), numeric.to_owned()), + ( + json!({"L": [{"N": "bob"}, {"X": "1"}]}), + NUMERIC_BOB.to_owned(), + ), (json!({"L": [{"X": "1"}, {"N": "bob"}]}), EMPTY.to_owned()), ] { let body = body_with( @@ -203,9 +189,9 @@ fn a_value_the_service_cannot_read_is_named_ahead_of_a_number_fault() { } for (value, reason) in [ (json!({"X": "1"}), EMPTY), - (Value::Null, null), + (Value::Null, NULL), (json!({}), EMPTY), - (json!({"S": "a", "N": "1"}), several), + (json!({"S": "a", "N": "1"}), SEVERAL), (json!({"L": [{"X": "1"}]}), EMPTY), ] { let body = body_with( @@ -225,7 +211,7 @@ fn a_value_the_service_cannot_read_is_named_ahead_of_a_number_fault() { let body = body_with(values.clone(), json!({})); assert_eq!( message(validate_query_request_body(&body)), - Some(format!("{INVALID_VALUE}{numeric} for key :u")), + Some(format!("{INVALID_VALUE}{NUMERIC_BOB} for key :u")), "{values}" ); } @@ -236,54 +222,28 @@ fn beside_a_value_the_service_cannot_read_the_enums_and_limit_are_reported_toget // Measured 2026-11-11 beside `:z = {"X": "1"}`: Select, then // ReturnConsumedCapacity, then Limit, in one message, ahead of the // parameter mix; the mix ahead of the values. - let select = "Value 'bad' at 'select' failed to satisfy constraint: Member must satisfy \ - enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, \ - ALL_PROJECTED_ATTRIBUTES]"; - let rcc = "Value 'bad' at 'returnConsumedCapacity' failed to satisfy constraint: Member \ - must satisfy enum value set: [INDEXES, TOTAL, NONE]"; - let limit = |n: i64| { - format!( - "Value '{n}' at 'limit' failed to satisfy constraint: Member must have value \ - greater than or equal to 1" - ) - }; - let mix = "Can not use both expression and non-expression parameters in the same request: \ - Non-expression parameters: {AttributesToGet} Expression parameters: \ - {KeyConditionExpression}"; let values = json!({":p": {"S": "x"}, ":u": {"N": "bob"}, ":z": {"X": "1"}}); for (extra, expected) in [ - ( - json!({"Limit": 0}), - format!("1 validation error detected: {}", limit(0)), - ), + (json!({"Limit": 0}), one_error(LIMIT_ZERO)), ( json!({"Limit": -1}), - format!("1 validation error detected: {}", limit(-1)), - ), - ( - json!({"Select": "bad"}), - format!("1 validation error detected: {select}"), - ), - ( - json!({"ReturnConsumedCapacity": "bad"}), - format!("1 validation error detected: {rcc}"), + one_error(&LIMIT_ZERO.replace("'0'", "'-1'")), ), + (json!({"Select": "bad"}), one_error(SELECT_BAD)), + (json!({"ReturnConsumedCapacity": "bad"}), one_error(RCC_BAD)), ( json!({"Limit": 0, "ReturnConsumedCapacity": "bad"}), - format!("2 validation errors detected: {rcc}; {}", limit(0)), + format!("2 validation errors detected: {RCC_BAD}; {LIMIT_ZERO}"), ), ( json!({"Limit": 0, "Select": "bad", "AttributesToGet": ["a"]}), - format!("2 validation errors detected: {select}; {}", limit(0)), + format!("2 validation errors detected: {SELECT_BAD}; {LIMIT_ZERO}"), ), ( json!({"Limit": 0, "ReturnConsumedCapacity": "bad", "Select": "bad"}), - format!( - "3 validation errors detected: {select}; {rcc}; {}", - limit(0) - ), + format!("3 validation errors detected: {SELECT_BAD}; {RCC_BAD}; {LIMIT_ZERO}"), ), - (json!({"AttributesToGet": ["a"]}), mix.to_owned()), + (json!({"AttributesToGet": ["a"]}), MIX.to_owned()), ] { let body = body_with(values.clone(), extra.clone()); assert_eq!( @@ -299,7 +259,9 @@ fn beside_a_value_the_service_cannot_read_the_enums_and_limit_are_reported_toget ); assert_eq!( message(validate_query_request_body(&body)), - Some(format!("2 validation errors detected: {rcc}; {}", limit(0))) + Some(format!( + "2 validation errors detected: {RCC_BAD}; {LIMIT_ZERO}" + )) ); } @@ -356,11 +318,7 @@ fn a_json_type_fault_inside_a_value_the_service_cannot_read_is_a_shape_fault() { ); assert_eq!( message(validate_query_request_body(&body)), - Some( - "1 validation error detected: Value '0' at 'limit' failed to satisfy constraint: \ - Member must have value greater than or equal to 1" - .to_owned() - ) + Some(one_error(LIMIT_ZERO)) ); } @@ -369,11 +327,6 @@ fn a_type_descriptor_with_a_null_payload_counts_as_absent() { // Measured 2026-11-19 on Query, each body twice: the service reads a null // payload as no payload, so `{"S": null}` is a value it cannot read as one // type, and the request takes that order of checks. - let select = "Value 'bad' at 'select' failed to satisfy constraint: Member must satisfy \ - enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, \ - ALL_PROJECTED_ATTRIBUTES]"; - let limit = "Value '0' at 'limit' failed to satisfy constraint: Member must have value \ - greater than or equal to 1"; let empty = format!("{INVALID_VALUE}{EMPTY} for key :v"); for (value, extra, expected) in [ (json!({"S": null}), json!({}), empty.clone()), @@ -382,45 +335,37 @@ fn a_type_descriptor_with_a_null_payload_counts_as_absent() { ( json!({"S": null, "N": "bob"}), json!({}), - format!( - "{INVALID_VALUE}The parameter cannot be converted to a numeric value: bob for \ - key :v" - ), + format!("{INVALID_VALUE}{NUMERIC_BOB} for key :v"), ), ( json!({"S": null}), json!({"Select": "bad"}), - format!("1 validation error detected: {select}"), + one_error(SELECT_BAD), ), ( json!({"S": null}), json!({"Limit": 0}), - format!("1 validation error detected: {limit}"), + one_error(LIMIT_ZERO), ), ( json!({"S": null}), json!({"Select": "bad", "Limit": 0}), - format!("2 validation errors detected: {select}; {limit}"), + format!("2 validation errors detected: {SELECT_BAD}; {LIMIT_ZERO}"), ), ( json!({"S": null}), json!({"ReturnConsumedCapacity": "bad"}), - "1 validation error detected: Value 'bad' at 'returnConsumedCapacity' failed to \ - satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]" - .to_owned(), + one_error(RCC_BAD), ), ( json!({"S": null}), json!({"AttributesToGet": ["a"]}), - "Can not use both expression and non-expression parameters in the same request: \ - Non-expression parameters: {AttributesToGet} Expression parameters: \ - {KeyConditionExpression}" - .to_owned(), + MIX.to_owned(), ), ( json!({"S": null}), json!({"ExpressionAttributeNames": {"a": "b"}}), - r#"ExpressionAttributeNames contains invalid key: Syntax error; key: "a""#.to_owned(), + INVALID_KEY.to_owned(), ), ] { let body = body_with(json!({":p": {"S": "x"}, ":v": value}), extra); diff --git a/crates/server/src/request_helpers.rs b/crates/server/src/request_helpers.rs index a3fea4349..6c205c5eb 100755 --- a/crates/server/src/request_helpers.rs +++ b/crates/server/src/request_helpers.rs @@ -245,22 +245,9 @@ pub(crate) async fn authorize_request( authz_resource::validate_tag_resource_arn_shape(arn)?; } - // A Query's request-time checks (Limit, the expression and non-expression - // parameter mix, the ReturnConsumedCapacity and Select enums, the - // ExpressionAttributeNames map, every number in ExpressionAttributeValues) - // run before the IAM decision, whatever the caller's policy. The engine - // makes the same checks at request time; they run here as well because - // authorization binds no dynamodb:LeadingKeys value to a number it cannot - // parse, and a fence that needs the key present (ForAnyValue, a Null - // guard, the plain operators) would otherwise answer AccessDeniedException - // where ValidationException is the request's error. The checks read the - // raw body, so a field that does not deserialize does not skip them. - // - // They run after the cross-account refusal above, so a Query that names a - // table ARN in another account gets AccessDeniedException without them. - // The service runs them first for a body it can read (measured - // 2026-11-12: with a table ARN in another account, `{"N": "bob"}` answers - // the numeric message and a `Limit` of 0 the `Limit` text). + // A Query's request-time checks run before the IAM decision, after the + // cross-account refusal above; see + // `extenddb_engine::query_key_values::validate_query_request_body`. if operation == "Query" { extenddb_engine::query_key_values::validate_query_request_body(input)?; } diff --git a/tests/test_query_value_shapes.py b/tests/test_query_value_shapes.py index fb67d26fe..4281c318d 100644 --- a/tests/test_query_value_shapes.py +++ b/tests/test_query_value_shapes.py @@ -115,6 +115,12 @@ def test_control_without_a_shape_fault_answers_the_check(self, dynamodb_client, S_PLUS_X = {"S": "a", "X": "1"} LIMIT_0_AT = ("Value '0' at 'limit' failed to satisfy constraint: " "Member must have value greater than or equal to 1") +SELECT_MSG = ("1 validation error detected: Value 'bad' at 'select' failed to satisfy constraint: " + "Member must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, " + "ALL_PROJECTED_ATTRIBUTES]") +ATTRIBUTES_TO_GET_MIX = ( + "Can not use both expression and non-expression parameters in the same request: " + "Non-expression parameters: {AttributesToGet} Expression parameters: {KeyConditionExpression}") # (row, values beside :p, other fields, the service's message). UNREADABLE = [ @@ -135,13 +141,8 @@ def test_control_without_a_shape_fault_answers_the_check(self, dynamodb_client, ("Limit 0 and ReturnConsumedCapacity", {":z": X1}, {"Limit": 0, "ReturnConsumedCapacity": "bad"}, "2 validation errors detected: " + RCC_MSG.removeprefix("1 validation error detected: ") + "; " + LIMIT_0_AT), - ("invalid Select", {":z": X1, ":u": NB}, {"Select": "bad"}, - "1 validation error detected: Value 'bad' at 'select' failed to satisfy constraint: Member " - "must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, " - "ALL_PROJECTED_ATTRIBUTES]"), - ("AttributesToGet", {":z": X1, ":u": NB}, {"AttributesToGet": ["a"]}, - "Can not use both expression and non-expression parameters in the same request: " - "Non-expression parameters: {AttributesToGet} Expression parameters: {KeyConditionExpression}"), + ("invalid Select", {":z": X1, ":u": NB}, {"Select": "bad"}, SELECT_MSG), + ("AttributesToGet", {":z": X1, ":u": NB}, {"AttributesToGet": ["a"]}, ATTRIBUTES_TO_GET_MIX), # Beside a second type descriptor, a payload with a fault is named ahead of # the more than one datatypes text, whatever order the members are in # (measured 2026-11-19). @@ -161,17 +162,13 @@ def test_control_without_a_shape_fault_answers_the_check(self, dynamodb_client, ("S null in an L", {":z": {"L": [{"S": None}]}}, {}, INVALID_VALUE + EMPTY_AV + " for key :z"), ("S null beside N bob", {":z": {"S": None, "N": "bob"}}, {}, INVALID_VALUE + NUMERIC + "bob for key :z"), - ("S null with an invalid Select", {":z": {"S": None}}, {"Select": "bad"}, - "1 validation error detected: Value 'bad' at 'select' failed to satisfy constraint: Member " - "must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, " - "ALL_PROJECTED_ATTRIBUTES]"), + ("S null with an invalid Select", {":z": {"S": None}}, {"Select": "bad"}, SELECT_MSG), ("S null with Limit 0", {":z": {"S": None}}, {"Limit": 0}, "1 validation error detected: " + LIMIT_0_AT), ("S null with ReturnConsumedCapacity", {":z": {"S": None}}, {"ReturnConsumedCapacity": "bad"}, RCC_MSG), ("S null with AttributesToGet", {":z": {"S": None}}, {"AttributesToGet": ["a"]}, - "Can not use both expression and non-expression parameters in the same request: " - "Non-expression parameters: {AttributesToGet} Expression parameters: {KeyConditionExpression}"), + ATTRIBUTES_TO_GET_MIX), ] @@ -209,12 +206,6 @@ def test_the_value_the_service_cannot_read_is_named_beside_n_bob(self, dynamodb_ INVALID_KEY = 'ExpressionAttributeNames contains invalid key: Syntax error; key: "a"' BAD_NAMES = {"a": "b"} -SELECT_MSG = ("1 validation error detected: Value 'bad' at 'select' failed to satisfy constraint: " - "Member must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, " - "ALL_PROJECTED_ATTRIBUTES]") -ATTRIBUTES_TO_GET_MIX = ( - "Can not use both expression and non-expression parameters in the same request: " - "Non-expression parameters: {AttributesToGet} Expression parameters: {KeyConditionExpression}") # (row, ExpressionAttributeNames, values beside :p, other members, the # service's message). @@ -241,6 +232,10 @@ def test_the_value_the_service_cannot_read_is_named_beside_n_bob(self, dynamodb_ {":x": X1}, {"ReturnConsumedCapacity": "bad"}, RCC_MSG), ("AttributesToGet beside an unknown descriptor and an invalid key", BAD_NAMES, {":x": X1}, {"AttributesToGet": ["a"]}, ATTRIBUTES_TO_GET_MIX), + ("empty name beside an unknown descriptor", {"#a": ""}, {":x": X1}, {}, + INVALID_VALUE + EMPTY_AV + " for key :x"), + ("empty name and invalid key beside an unknown descriptor", {"#a": "", "b": "c"}, {":x": X1}, + {}, 'ExpressionAttributeNames contains invalid key: Syntax error; key: "b"'), ] # (row, ExpressionAttributeNames, ExpressionAttributeValues or None, the @@ -263,10 +258,11 @@ class TestExpressionAttributeNamesOrder: """The ExpressionAttributeNames checks (an empty map, a key that is not `#` and a name, an empty name) are reported after Limit, ReturnConsumedCapacity and the parameter mix, and ahead of the number - check, a duplicate set member, Select and a value the service cannot read - as one type, whatever the member order (measured 2026-11-19). Each body is - sent with ExpressionAttributeNames ahead of the other members and after - them.""" + check, a duplicate set member and Select. Beside a value the service + cannot read as one type, the key checks and the empty map are reported + ahead of the value, and an empty name after it. The answers are the same + in either member order (measured 2026-11-19). Each body is sent with + ExpressionAttributeNames ahead of the other members and after them.""" @pytest.mark.parametrize("names_first", [True, False], ids=["names first", "names last"]) @pytest.mark.parametrize("row,names,values,extra,expected", NAMES, ids=[r[0] for r in NAMES]) From 99dc1349e073b1aa84e9260e21aec9d013a25d82 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:53:07 +0000 Subject: [PATCH 20/30] docs(query): scope four comments on the names checks The doc of validate_query_request_body said that the service makes the request-time checks first on a Query that names a table ARN in another account. The measurement covers a body the service can read, and the doc now says so. The doc of validate_names now lists the check on a key over 255 bytes, which the deserializer makes and which validate_name_keys names. Step 5 of the unreadable_value_checks doc is three sentences. The first list in the docstring of TestExpressionAttributeNamesOrder now covers readable values only. The docstring also gives the place of the key checks beside a value the service cannot read. No code or test row changes. --- crates/engine/src/query_key_values.rs | 11 ++++++----- .../engine/src/query_key_values/unreadable.rs | 10 +++++----- tests/test_query_value_shapes.py | 18 ++++++++++-------- 3 files changed, 21 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index 6dbfa5ea8..00ce9f958 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -107,8 +107,9 @@ const SELECT: &[&str] = &[ /// answers the shape fault first as well. It comes after the server's /// cross-account refusal, so a `Query` that names a table ARN in another /// account answers `AccessDeniedException` without these checks, where the -/// service makes them first (measured 2026-11-12: with such an ARN, `{"N": -/// "bob"}` answers the numeric message and a `Limit` of 0 the `Limit` text). +/// service makes them first for a body it can read (measured 2026-11-12: with +/// such an ARN, `{"N": "bob"}` answers the numeric message and a `Limit` of 0 +/// the `Limit` text). /// /// # Errors /// @@ -227,9 +228,9 @@ fn validate_no_parameter_mix(body: &Value) -> Result<(), DynamoDbError> { } /// The checks the `ExpressionAttributeNames` deserializer makes, on the raw -/// body: an empty map, a key that is not `#` and a name, and an empty name, -/// with the deserializer's text. A map or name of another JSON type is a shape -/// fault, which this leaves to the shape fault check. +/// body: an empty map, a key that is not `#` and a name, a key over 255 bytes, +/// and an empty name, with the deserializer's text. A map or name of another +/// JSON type is a shape fault, which this leaves to the shape fault check. /// /// # Errors /// diff --git a/crates/engine/src/query_key_values/unreadable.rs b/crates/engine/src/query_key_values/unreadable.rs index 7a9a1f259..ea670cc30 100644 --- a/crates/engine/src/query_key_values/unreadable.rs +++ b/crates/engine/src/query_key_values/unreadable.rs @@ -145,11 +145,11 @@ fn null_value() -> Value { /// one has no colon after the message. No `M` with more than one member was /// measured; /// 5. an empty name in `ExpressionAttributeNames` (measured 2026-11-19 in -/// either member order: `{"#a": ""}` beside `{"X": "1"}`, `{}`, `{"N": "1", -/// "S": "x"}`, a null or `{"S": null}` answers that value's text, beside -/// `{"S": "a", "X": "1"}`, which has no fault of its own, it answers the -/// empty name text, and `{"#a": "", "b": "c"}` beside `{"X": "1"}` answers -/// the invalid key text for `b`). +/// either member order). `{"#a": ""}` beside `{"X": "1"}`, `{}`, `{"N": +/// "1", "S": "x"}`, a null or `{"S": null}` answers that value's text. +/// Beside `{"S": "a", "X": "1"}`, which has no fault of its own, it answers +/// the empty name text. `{"#a": "", "b": "c"}` beside `{"X": "1"}` answers +/// the invalid key text for `b`. /// /// When several values have a fault, the service names a value it cannot read /// as one type ahead of a number fault in another value. `:u` with `{"N": diff --git a/tests/test_query_value_shapes.py b/tests/test_query_value_shapes.py index 4281c318d..626042efe 100644 --- a/tests/test_query_value_shapes.py +++ b/tests/test_query_value_shapes.py @@ -255,14 +255,16 @@ def _assert_validation(status, payload, expected): class TestExpressionAttributeNamesOrder: - """The ExpressionAttributeNames checks (an empty map, a key that is not - `#` and a name, an empty name) are reported after Limit, - ReturnConsumedCapacity and the parameter mix, and ahead of the number - check, a duplicate set member and Select. Beside a value the service - cannot read as one type, the key checks and the empty map are reported - ahead of the value, and an empty name after it. The answers are the same - in either member order (measured 2026-11-19). Each body is sent with - ExpressionAttributeNames ahead of the other members and after them.""" + """With readable values, the ExpressionAttributeNames checks (an empty + map, a key that is not `#` and a name, a key over 255 bytes, an empty + name) are reported after Limit, ReturnConsumedCapacity and the parameter + mix, and ahead of the number check, a duplicate set member and Select. + Beside a value the service cannot read as one type, the key checks and + the empty map are reported after the Select, ReturnConsumedCapacity and + Limit step and the mix, and ahead of the value, and an empty name after + it. The answers are the same in either member order (measured + 2026-11-19). Each body is sent with ExpressionAttributeNames ahead of the + other members and after them.""" @pytest.mark.parametrize("names_first", [True, False], ids=["names first", "names last"]) @pytest.mark.parametrize("row,names,values,extra,expected", NAMES, ids=[r[0] for r in NAMES]) From 680c83b857d2c02fa846fa3109169f35800e96fc Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:59:03 +0000 Subject: [PATCH 21/30] refactor(query): take three message texts from core query_key_values.rs kept private copies of three texts that core already defines: NOT_A_NUMBER of the number check, and EMPTY_ATTRIBUTE_VALUE and MULTI_ATTRIBUTE_VALUE of the AttributeValue deserializer. Core now makes the three public, and the Query check imports them. The texts do not change. NULL_VALUE and TYPE_DESCRIPTORS stay in query_key_values.rs. Core's only copies are private constants of its partiql module. A build without the partiql feature leaves that module out, and the engine builds without the feature. --- crates/core/src/types/attribute_value.rs | 6 +++-- crates/core/src/types/mod.rs | 2 +- crates/core/src/validation/number.rs | 2 +- crates/engine/src/query_key_values.rs | 32 +++++++++++++----------- 4 files changed, 23 insertions(+), 19 deletions(-) diff --git a/crates/core/src/types/attribute_value.rs b/crates/core/src/types/attribute_value.rs index 85b9bab1f..5b728e106 100755 --- a/crates/core/src/types/attribute_value.rs +++ b/crates/core/src/types/attribute_value.rs @@ -68,9 +68,11 @@ impl<'de> Deserialize<'de> for AttributeValue { struct AttributeValueVisitor; -const EMPTY_ATTRIBUTE_VALUE: &str = +/// The deserializer's text for a value with no type descriptor. +pub const EMPTY_ATTRIBUTE_VALUE: &str = "Supplied AttributeValue is empty, must contain exactly one of the supported datatypes"; -const MULTI_ATTRIBUTE_VALUE: &str = "Supplied AttributeValue has more than one datatypes set, must contain exactly one of the supported datatypes"; +/// The deserializer's text for a value with more than one type descriptor. +pub const MULTI_ATTRIBUTE_VALUE: &str = "Supplied AttributeValue has more than one datatypes set, must contain exactly one of the supported datatypes"; 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 1cdaa4041..f8fa4071c 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; +pub use attribute_value::{AttributeValue, EMPTY_ATTRIBUTE_VALUE, MULTI_ATTRIBUTE_VALUE}; pub use backup::{ BackupDescription, BackupDetails, BackupSummary, ContinuousBackupsDescription, GlobalSecondaryIndexInfo, LocalSecondaryIndexInfo, PointInTimeRecoveryDescription, diff --git a/crates/core/src/validation/number.rs b/crates/core/src/validation/number.rs index b50094252..e042f8a4a 100644 --- a/crates/core/src/validation/number.rs +++ b/crates/core/src/validation/number.rs @@ -17,7 +17,7 @@ pub(super) const MIN_MAGNITUDE: i64 = MIN_EXPONENT as i64 + 1; /// The service's text for a value that is not a number. A malformed value /// is named after a colon; an empty one is not. -const NOT_A_NUMBER: &str = "The parameter cannot be converted to a numeric value"; +pub const NOT_A_NUMBER: &str = "The parameter cannot be converted to a numeric value"; /// Why a string is not a number `DynamoDB` can store, as /// [`normalize_number`] reports it. diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index 00ce9f958..b3f10b89c 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -30,7 +30,10 @@ use extenddb_core::error::DynamoDbError; use extenddb_core::expression::{ Expr, ExpressionMaps, KeyCondition, PathElement, SortKeyCondition, }; -use extenddb_core::types::{AttributeDefinition, QueryInput}; +use extenddb_core::types::{ + AttributeDefinition, EMPTY_ATTRIBUTE_VALUE, MULTI_ATTRIBUTE_VALUE, QueryInput, +}; +use extenddb_core::validation::number::NOT_A_NUMBER; use serde::de::DeserializeOwned; use serde_json::{Map, Value}; @@ -44,16 +47,15 @@ pub const KEY_CONDITION_TYPE_MISMATCH: &str = "One or more parameter values were /// The service's text for a `Limit` below 1 on `Query`. pub const LIMIT_BELOW_ONE: &str = "1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1"; -/// The bare numeric message the number validator uses for an empty `N`. -const EMPTY_NUMBER: &str = "The parameter cannot be converted to a numeric value"; - -/// The service's texts for a value it cannot read as one type. +/// The service's text for a null value. Core's copy is a private constant of +/// its `partiql` module, which a build without the `partiql` feature leaves +/// out. const NULL_VALUE: &str = "The supplied Item contains a null AttributeValue"; -const EMPTY_VALUE: &str = - "Supplied AttributeValue is empty, must contain exactly one of the supported datatypes"; -const SEVERAL_TYPES: &str = "Supplied AttributeValue has more than one datatypes set, must contain exactly one of the supported datatypes"; -/// The type descriptors of an AttributeValue. +/// The type descriptors of an AttributeValue, in the order the service reads +/// the payloads of a value with several type descriptors (see +/// [`first_fault`]). Core's list is a private constant of its `partiql` +/// module, as for [`NULL_VALUE`]. const TYPE_DESCRIPTORS: [&str; 10] = ["S", "N", "B", "SS", "NS", "BS", "M", "L", "NULL", "BOOL"]; /// The members of the two enums the request-time checks read. @@ -313,7 +315,7 @@ impl Fault<'_> { fn request_time_text(self) -> String { match self { Fault::NotANumber(text) => format!( - "{EMPTY_NUMBER}: {}", + "{NOT_A_NUMBER}: {}", crate::decimal_digits::fold_decimal_digits(text) ), other => other.reason(), @@ -326,10 +328,10 @@ impl Fault<'_> { match self { Fault::Null(None) => NULL_VALUE.to_owned(), Fault::Null(Some(member)) => format!("{NULL_VALUE}: {member} is null"), - Fault::Empty => EMPTY_VALUE.to_owned(), - Fault::SeveralTypes => SEVERAL_TYPES.to_owned(), - Fault::NotANumber("") => EMPTY_NUMBER.to_owned(), - Fault::NotANumber(text) => format!("{EMPTY_NUMBER}: {text}"), + Fault::Empty => EMPTY_ATTRIBUTE_VALUE.to_owned(), + Fault::SeveralTypes => MULTI_ATTRIBUTE_VALUE.to_owned(), + Fault::NotANumber("") => NOT_A_NUMBER.to_owned(), + Fault::NotANumber(text) => format!("{NOT_A_NUMBER}: {text}"), Fault::Refused(msg) => msg, } } @@ -388,7 +390,7 @@ fn number_fault(text: &str) -> Option> { let folded = crate::decimal_digits::fold_decimal_digits(text); match extenddb_core::validation::number::validate_and_normalize_number(&folded) { Ok(_) => None, - Err(DynamoDbError::ValidationException(msg)) if msg.starts_with(EMPTY_NUMBER) => { + Err(DynamoDbError::ValidationException(msg)) if msg.starts_with(NOT_A_NUMBER) => { Some(Fault::NotANumber(text)) } Err(DynamoDbError::ValidationException(msg)) => Some(Fault::Refused(msg)), From f07a5654077c962954282797a3386f7542998e2a Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:59:09 +0000 Subject: [PATCH 22/30] docs(query): give the M member order of the MongoDB build The doc of first_fault said that it visits M members in key order, because serde_json keeps the members of an object sorted by key. The MongoDB build turns on the preserve_order feature of serde_json through bson, so that build visits the members in document order. The docs of first_fault and Fault, and step 4 of the unreadable_value_checks doc, now give the iteration order of the map. No code changes. --- crates/engine/src/query_key_values.rs | 18 ++++++++++-------- .../engine/src/query_key_values/unreadable.rs | 14 +++++++------- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index b3f10b89c..5fba98d24 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -292,7 +292,7 @@ fn sorted_entries(values: &Map) -> Vec<(&String, &Value)> { } /// The first fault inside one value, in document order for `L` items and in -/// key order for `M` members. +/// the map's iteration order for `M` members (see [`first_fault`]). enum Fault<'a> { /// A null, with the member name when it is the value of an `M` member. Null(Option<&'a str>), @@ -340,13 +340,15 @@ impl Fault<'_> { /// The first fault in `value` (`member` is its name when it is the value of an /// `M` member): a null or no type descriptor, then the numbers in `N`, `NS` /// and every value an `L` or `M` holds, then more than one type descriptor. -/// `L` items are visited in document order and `M` members in key order: this -/// build of `serde_json` keeps an object's members sorted by key. A value of -/// another JSON type, and an `N` or `NS` payload of the wrong JSON type, are -/// shape faults the deserializer reports. A type descriptor with a null -/// payload counts as absent, as the service reads it (measured 2026-11-19: -/// `{"S": null}` answers the empty value text, and `{"S": null, "N": "1"}` in -/// a `FilterExpression` is accepted). +/// `L` items are visited in document order and `M` members in the map's +/// iteration order: sorted by key without the `preserve_order` feature of +/// `serde_json`, in document order with it, as in the MongoDB build (bson +/// turns the feature on). A value of another JSON type, and an `N` or `NS` +/// payload of the wrong JSON type, are shape faults the deserializer +/// reports. A type descriptor with a null payload counts as absent, as the +/// service reads it (measured 2026-11-19: `{"S": null}` answers the empty +/// value text, and `{"S": null, "N": "1"}` in a `FilterExpression` is +/// accepted). /// /// With several type descriptors, the service reads each payload in the order /// of [`TYPE_DESCRIPTORS`], whatever order the request wrote them in, and diff --git a/crates/engine/src/query_key_values/unreadable.rs b/crates/engine/src/query_key_values/unreadable.rs index ea670cc30..385b56218 100644 --- a/crates/engine/src/query_key_values/unreadable.rs +++ b/crates/engine/src/query_key_values/unreadable.rs @@ -137,13 +137,13 @@ fn null_value() -> Value { /// an invalid `Select` or `ReturnConsumedCapacity` and a mix are reported /// ahead of it); see [`validate_name_keys`]; /// 4. the first fault inside a value, in document order for `L` items and in -/// key order for `M` members, as `ExpressionAttributeValues contains -/// invalid value: for key `: a null (`The supplied -/// Item contains a null AttributeValue`, with `: is null` when it -/// is the value of an `M` member), no type descriptor, more than one, or an -/// `N` that is not a number. Such an `N` is echoed as written, and an empty -/// one has no colon after the message. No `M` with more than one member was -/// measured; +/// the map's iteration order for `M` members (see [`first_fault`]), as +/// `ExpressionAttributeValues contains invalid value: for key +/// `: a null (`The supplied Item contains a null +/// AttributeValue`, with `: is null` when it is the value of an +/// `M` member), no type descriptor, more than one, or an `N` that is not a +/// number. Such an `N` is echoed as written, and an empty one has no colon +/// after the message. No `M` with more than one member was measured; /// 5. an empty name in `ExpressionAttributeNames` (measured 2026-11-19 in /// either member order). `{"#a": ""}` beside `{"X": "1"}`, `{}`, `{"N": /// "1", "S": "x"}`, a null or `{"S": null}` answers that value's text. From 467e287afedba42a74c504e2ec120d59a489dcf1 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:59:16 +0000 Subject: [PATCH 23/30] test(query): give the service's text for each shape fault row TestShapeFaultsAreReportedFirst asserts the error type only, because the SerializationException texts of the service differ from those of ExtendDB (#1012). Each row of SHAPE_FAULTS now has a comment with the message of the service, from the measurements of 2026-10-25 and 2026-11-11. No row changes. --- tests/test_query_value_shapes.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/tests/test_query_value_shapes.py b/tests/test_query_value_shapes.py index 626042efe..39c60ca0d 100644 --- a/tests/test_query_value_shapes.py +++ b/tests/test_query_value_shapes.py @@ -49,35 +49,47 @@ def _raw_query(client, body: dict): SHAPE_FAULTS = [ + # The service: "Unexpected field type". ("Limit 0 with ExpressionAttributeValues string", {"KeyConditionExpression": "pk = :p", "Limit": 0, "ExpressionAttributeValues": "x"}), + # The service: "Unexpected field type". ("ExpressionAttributeNames string with N bob", {"KeyConditionExpression": "pk = :p", "ExpressionAttributeNames": "x", "ExpressionAttributeValues": {":p": NB}}), + # The service: "STRING_VALUE cannot be converted to Integer". ("Limit string with N bob", {"KeyConditionExpression": "pk = :p", "Limit": "1", "ExpressionAttributeValues": {":p": NB}}), + # The service: "Start of structure or map found where not expected". ("AttributesToGet object with ProjectionExpression", {"KeyConditionExpression": "pk = :p", "AttributesToGet": {"a": 1}, "ProjectionExpression": "a", "ExpressionAttributeValues": {":p": SX}}), + # The service: no message. ("QueryFilter array with FilterExpression", {"KeyConditionExpression": "pk = :p", "QueryFilter": [1], "FilterExpression": "a = :p", "ExpressionAttributeValues": {":p": SX}}), + # The service: "NUMBER_VALUE cannot be converted to String". ("Select number with N bob", {"KeyConditionExpression": "pk = :p", "Select": 5, "ExpressionAttributeValues": {":p": NB}}), + # The service: "NUMBER_VALUE cannot be converted to String". ("Limit 0 with Select number", {"KeyConditionExpression": "pk = :p", "Limit": 0, "Select": 5, "ExpressionAttributeValues": {":p": SX}}), # A field of the wrong JSON type inside a value the service cannot read as # one type (measured 2026-11-11). + # The service: "Unexpected value type in payload". ("string beside a null in an L", {"KeyConditionExpression": "pk = :p", "ExpressionAttributeValues": {":p": SX, ":z": {"L": [None, "x"]}}}), + # The service: "NUMBER_VALUE cannot be converted to String". ("N number beside an unknown descriptor in an L", {"KeyConditionExpression": "pk = :p", "ExpressionAttributeValues": {":p": SX, ":z": {"L": [{"X": "1"}, {"N": 5}]}}}), + # The service: "NUMBER_VALUE cannot be converted to String". ("S number beside an unknown descriptor with Limit 0", {"KeyConditionExpression": "pk = :p", "Limit": 0, "ExpressionAttributeValues": {":p": SX, ":z": {"S": 5, "X": "1"}}}), + # The service: "Base64 encoded length is expected a multiple of 4 bytes but + # found: 2". ("B not base64 beside a null in an L", {"KeyConditionExpression": "pk = :p", "ExpressionAttributeValues": {":p": SX, ":z": {"L": [None, {"B": "!!"}]}}}), @@ -88,7 +100,8 @@ class TestShapeFaultsAreReportedFirst: """A field of the wrong JSON type anywhere in the body answers SerializationException ahead of the Limit, parameter mix, enum and number checks (measured 2026-10-25 11:31 UTC). The message texts differ between - the service and extenddb, so only the error type is asserted.""" + the service and extenddb (#1012), so only the error type is asserted. The + comment on each row gives the service's message.""" @pytest.mark.parametrize("row,body", SHAPE_FAULTS, ids=[r[0] for r in SHAPE_FAULTS]) def test_rows(self, dynamodb_client, ss_table, row, body): From e2d90f1a6c7071012060304e5f0d3c6a2da6bcf2 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:59:16 +0000 Subject: [PATCH 24/30] docs: list three Query differences from DynamoDB docs/differences-from-dynamodb.md gets a Query section. Its rows give the order of the cross-account refusal and the request checks (#974), and N values written with Unicode decimal digits (#565). A third row gives the wrapper that the service adds beside a Limit above 2147483647 (#976). --- docs/differences-from-dynamodb.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index c44479284..5430a1623 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -90,6 +90,14 @@ from a request sent to that service or backend. | Tag condition keys on tag operations | `aws:RequestTag/` and `aws:TagKeys` are populated for `TagResource` and `CreateTable`, and `aws:TagKeys` for `UntagResource` (service authorization reference, dynamodb v1.5). Whether `CreateTable` with `Tags` is also authorized as `dynamodb:TagResource` was not measured | The same three operations populate the same keys, and every other operation leaves both absent. The operator semantics (set operators, `Null`, a bare negated operator on an absent `aws:TagKeys`, tag name case) come from `iam simulate-custom-policy` runs, not from DynamoDB requests. A request that names one tag under two spellings with differing values fails closed: a `Deny` that reads the key blocks and an `Allow` that reads it does not grant; the service's answer was not measured. The variable `${aws:TagKeys}` in a condition value has no value: a positive operator is false against it and a negated one true (measured with the IAM policy simulator on 2026-10-27), and its text is not compared (measured the same way on 2026-10-31). On a table resource policy a `StringEquals` `Deny` with it did not apply for either tag order (measured 2026-10-27). Tag names in `aws:RequestTag/` match without regard to case on both (`Étag` and `étag` match on the service), but ExtendDB's Unicode case folding also equates the sharp s with `ss` (`Straße` and `STRASSE`), which the service does not (measured on IAM and on a table resource policy, 2026-10-27). An `Allow` gated on `aws:RequestTag/STRASSE` grants a request carrying `Straße` on ExtendDB where the service would not (inferred from the same measurement; the Allow direction was not run) | | A tag key repeated in one `TagResource` or `CreateTable` request | `ValidationException` "Duplicate Tag Keys provided as input: Duplicate Tag Key found " on both operations (measured 2026-10-27), and nothing is stored | `TagResource` accepts it and stores the last value, and authorization reads that value. `CreateTable` answers HTTP 500 `InternalServerError` on SQLite and PostgreSQL and creates nothing, because the tags are inserted with a plain `INSERT`. Measured on SQLite and PostgreSQL on 2026-10-27 | +## Query + +| Area | DynamoDB | ExtendDB | +|------|----------|------| +| A `Query` that names a table ARN in another account and has a fault in its request | The request checks come first: `{"N": "bob"}` answers `The parameter cannot be converted to a numeric value: bob`, and `Limit: 0` answers `1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1`. A body with no fault answers `AccessDeniedException` "The caller is not authorized to access the specified resource." (measured 2026-11-12) | `AccessDeniedException`, with the answers of "A resource ARN in another account" above, ahead of the request checks (#974) | +| An `N` value written with Unicode decimal digits, such as `{"N": "1"}` | Read as the number its digits stand for. A fullwidth, Arabic-Indic or Devanagari one as a sort key value or a filter value matches an item with `N` `1`, and `PutItem` stores `{"N": "1"}` as `1` (measured 2026-10-25). Digit one of each of the 37 runs of ten `Nd` digits below U+10000 in Unicode 15.0 is accepted as a filter value, and digit one of each of the 31 runs from U+104A0 up is refused with `The parameter cannot be converted to a numeric value: ` (measured 2026-11-11) | The `Query` number check accepts the digits of the 37 runs and refuses those of the 31 runs. The key condition, the filter and `ExclusiveStartKey` read the value as written, so a value written with these digits matches no item stored with the ASCII digits. A key condition value for a numeric sort key, or an `ExclusiveStartKey`, written that way answers `InternalServerError` on SQLite and PostgreSQL. `PutItem`, `UpdateItem` and the batch and transaction writes refuse the value (#565) | +| An `N` value that is not a number beside a `Limit` above 2147483647 | `Limit: 2147483648` beside `:u` = `{"N": "bob"}` answers `ExpressionAttributeValues contains invalid value: The parameter cannot be converted to a numeric value: bob for key :u`. `Limit: 2147483647` beside it answers the text without the `ExpressionAttributeValues contains invalid value: ` wrapper (measured 2026-11-12) | The text without the wrapper for both (#976) | + ## Secondary Indexes | Area | DynamoDB | ExtendDB | From d7e6ff35ba0ac7d95f69dabe077c15133bec9820 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:00:31 +0000 Subject: [PATCH 25/30] fix(query): find a shape fault in any member and value When a request-time check fails, validate_query_request_body looks for a member of the wrong JSON type, because the service reports one ahead of the checks. It deserialized the whole body once, and serde stops at the first member that fails, in map order. An empty NS in ExpressionAttributeValues stopped it, so Select: 5 beside a Limit of 0 answered the Limit text, where the service answers SerializationException. shape_fault_first now reads each member on its own, beside TableName, and each ExpressionAttributeValues value on its own. The check also counted two kinds of member as shape faults that the service reads. One is a string in ConsistentRead or ScanIndexForward that the service reads as a boolean, such as "true", "T" or "0". The other is a number in Limit. Beside Select: "NOPE", each answered SerializationException here, where the service and main answer the Select text. The check now skips them. A string such as "on" stays a shape fault, as on the service. The handler's deserializer still refuses every string in these members. I measured the service answers on 2026-11-23, each body twice. On e2d90f1a6, 7 of the 11 new unit rows fail, and 7 of the 11 new rows in tests/test_query_value_shapes.py fail. --- crates/engine/src/query_key_values.rs | 113 ++++++++++++++---- .../query_key_values/request_order_tests.rs | 88 ++++++++++++++ tests/test_query_value_shapes.py | 81 +++++++++++-- 3 files changed, 252 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index 5fba98d24..2405c3418 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -88,10 +88,11 @@ const SELECT: &[&str] = &[ /// /// The checks read the raw body, so a field that does not deserialize (an /// invalid `Select`, for one) does not stop the ones before it. When a check -/// fails, the body is deserialized as a [`QueryInput`], and a -/// `SerializationException` from that (a field of the wrong JSON shape -/// anywhere in the body) is the answer instead, as the service reports a shape -/// fault ahead of every validation (measured 2026-10-25: a `Limit` of 0 with a +/// fails, each member of the body is deserialized on its own as part of a +/// [`QueryInput`] (see `shape_fault_first`), and a `SerializationException` +/// from that (a member of the wrong JSON type, in any member order) is the +/// answer instead, as the service reports a shape fault ahead of every +/// validation (measured 2026-10-25: a `Limit` of 0 with a /// string `ExpressionAttributeValues`, a string `ExpressionAttributeNames` with /// an `N` value that is not a number, and a `Limit` of 0 with `Select: 5` all /// answer `SerializationException`). A `ValidationException` the deserializer @@ -123,30 +124,98 @@ pub fn validate_query_request_body(body: &Value) -> Result<(), DynamoDbError> { } /// When a request-time check has failed with `check`, the deserializer's -/// `SerializationException` for `body` if there is one, else `check`. The two -/// enum fields stay in the body: an enum value that is a string but not a -/// member deserializes to a `ValidationException`, which this ignores, and one -/// of another JSON type is a shape fault the service reports ahead of the -/// checks (measured 2026-10-25: `Select: 5` with a `Limit` of 0 answers -/// `SerializationException: NUMBER_VALUE cannot be converted to String`). +/// `SerializationException` for a member of `body` if there is one, else +/// `check`. The service reports a member of the wrong JSON type ahead of the +/// checks whatever the member order (measured 2026-11-23, each body twice: +/// `Select: 5` beside `{"X": "1"}` or an empty `NS`, and `{"S": 5}` after an +/// empty `NS` in another value, each with a `Limit` of 0, answer +/// `SerializationException: NUMBER_VALUE cannot be converted to String` on +/// `Query`, and the first of them on `Scan` too). So each member is +/// deserialized on its own as a `T`, beside the body's `TableName` (the one +/// member `T` must have), and each `ExpressionAttributeValues` entry on its +/// own. The answer is the first shape fault in the map's iteration order (see +/// [`first_fault`]). Inside one member or entry, the deserializer stops at the +/// first fault. /// -/// An AttributeValue with an unknown type descriptor is not a shape fault to -/// the service: `Limit: 0` beside `{"X": "1"}` answers the `Limit` -/// `ValidationException` (measured 2026-10-25), so the deserializer's -/// `SerializationException` for that message does not preempt the check. +/// These are not shape faults here: +/// +/// - an enum value that is a string but not a member, which deserializes to a +/// `ValidationException`. One of another JSON type is a shape fault +/// (measured 2026-10-25: `Select: 5` with a `Limit` of 0 answers +/// `SerializationException: NUMBER_VALUE cannot be converted to String`); +/// - an AttributeValue with an unknown type descriptor, a value the service +/// cannot read as one type: `Limit: 0` beside `{"X": "1"}` answers the +/// `Limit` `ValidationException` (measured 2026-10-25 and 2026-11-23); +/// - a member the service reads from a JSON type that `T` refuses: a string +/// in `ConsistentRead` or `ScanIndexForward` that the service reads as a +/// boolean (see [`BOOLEAN_TEXTS`]), and any number in `Limit`. Measured +/// 2026-11-23: `ConsistentRead: "true"` or `"T"`, `ScanIndexForward: +/// "true"` or `"0"`, and `Limit: 1.5` beside `Select: "NOPE"` answer the +/// `Select` text on `Query`, as `ConsistentRead: "true"` does on `Scan`, and +/// `ConsistentRead: "yes"` with a table that does not exist answers +/// `ResourceNotFoundException`. `ConsistentRead: "on"` answers +/// `SerializationException: Unexpected token received from parser`, and +/// `ConsistentRead: 1` `SerializationException: NUMBER_VALUE cannot be +/// converted to Boolean`. The handler's own deserialization still refuses +/// every string in these members. pub(crate) fn shape_fault_first( body: &Value, check: DynamoDbError, ) -> DynamoDbError { - match serde_json::from_value::(body.clone()) { - Err(e) => match crate::deserialize_error(e) { - DynamoDbError::SerializationException(msg) if msg.contains(UNKNOWN_TYPE_DESCRIPTOR) => { - check + let read = |name: &str, value: Value| { + let mut one: Map = body + .get("TableName") + .map(|table_name| ("TableName".to_owned(), table_name.clone())) + .into_iter() + .collect(); + one.insert(name.to_owned(), value); + shape_fault::(Value::Object(one)) + }; + body.as_object() + .into_iter() + .flatten() + .find_map(|(name, value)| match (name.as_str(), value) { + ("ConsistentRead" | "ScanIndexForward", Value::String(text)) + if BOOLEAN_TEXTS + .iter() + .any(|word| word.eq_ignore_ascii_case(text)) => + { + None + } + ("Limit", Value::Number(_)) => None, + ("ExpressionAttributeValues", Value::Object(entries)) => { + entries.iter().find_map(|(key, entry)| { + read( + name, + Value::Object(Map::from_iter([(key.clone(), entry.clone())])), + ) + }) } - shape @ DynamoDbError::SerializationException(_) => shape, - _ => check, - }, - Ok(_) => check, + _ => read(name, value.clone()), + }) + .unwrap_or(check) +} + +/// The strings the service reads as a boolean, in any ASCII case: the first +/// five as true, the others as false. It refuses every other string with +/// `SerializationException`. Measured 2026-11-10 for each of them in +/// `UpdateContinuousBackups` `PointInTimeRecoveryEnabled`, 2026-11-11 for +/// `"yes"` and `"TRUE"` in `GetItem` `ConsistentRead` and `"no"` in `Query` +/// `ScanIndexForward`, and 2026-11-23 on `Query` for `"T"`, `"0"` and the +/// refused `"on"`. +const BOOLEAN_TEXTS: [&str; 10] = ["true", "t", "yes", "y", "1", "false", "f", "no", "n", "0"]; + +/// 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 { + match serde_json::from_value::(body).map_err(crate::deserialize_error) { + Err(DynamoDbError::SerializationException(msg)) + if msg.contains(UNKNOWN_TYPE_DESCRIPTOR) => + { + None + } + Err(shape @ DynamoDbError::SerializationException(_)) => Some(shape), + _ => None, } } diff --git a/crates/engine/src/query_key_values/request_order_tests.rs b/crates/engine/src/query_key_values/request_order_tests.rs index 88d269c9d..75b1b04fe 100644 --- a/crates/engine/src/query_key_values/request_order_tests.rs +++ b/crates/engine/src/query_key_values/request_order_tests.rs @@ -170,6 +170,94 @@ fn return_consumed_capacity_is_reported_ahead_of_the_parameter_mix() { } } +#[test] +fn each_member_and_value_is_read_on_its_own_for_a_shape_fault() { + // Measured 2026-11-23, each body twice, with a table that does not exist. + // A shape fault is reported past an unknown descriptor or an empty set in + // another member or value, a number or an `"on"` in `ConsistentRead` is a + // shape fault, and a member the service reads from a JSON type the typed + // input refuses leaves the check's answer. Each row holds the values, the + // other members and the answer. + let shape = |text: &str| { + ( + "SerializationException", + format!("Start of structure or map found where not expected: {text}"), + ) + }; + let select_5 = shape("invalid type: integer `5`, expected a string"); + let select_nope = ( + "ValidationException", + one_error(&super::tests::SELECT_BAD.replace("'bad'", "'NOPE'")), + ); + let (x1, sx) = (json!({":u": {"X": "1"}}), json!({":p": {"S": "x"}})); + let rows = [ + ( + x1.clone(), + json!({"Limit": 0, "Select": 5, "KeyConditionExpression": "pk = :u"}), + select_5.clone(), + ), + ( + x1, + json!({"Limit": 0, "KeyConditionExpression": "pk = :u"}), + ("ValidationException", one_error(LIMIT_ZERO)), + ), + ( + json!({":p": {"S": "x"}, ":s": {"NS": []}}), + json!({"Limit": 0, "Select": 5}), + select_5, + ), + ( + json!({":p": {"S": "x"}, ":a": {"NS": []}, ":b": {"S": 5}}), + json!({"Limit": 0}), + shape("S value must be a string"), + ), + ( + sx.clone(), + json!({"ConsistentRead": 1, "Select": "NOPE"}), + shape("invalid type: integer `1`, expected a boolean"), + ), + ( + sx.clone(), + json!({"ConsistentRead": "true", "Select": "NOPE"}), + select_nope.clone(), + ), + ( + sx.clone(), + json!({"ConsistentRead": "T", "Select": "NOPE"}), + select_nope.clone(), + ), + ( + sx.clone(), + json!({"ConsistentRead": "on", "Select": "NOPE"}), + shape(r#"invalid type: string "on", expected a boolean"#), + ), + ( + sx.clone(), + json!({"ScanIndexForward": "true", "Select": "NOPE"}), + select_nope.clone(), + ), + ( + sx.clone(), + json!({"ScanIndexForward": "0", "Select": "NOPE"}), + select_nope.clone(), + ), + (sx, json!({"Limit": 1.5, "Select": "NOPE"}), select_nope), + ]; + let mismatches: Vec = rows + .into_iter() + .filter_map(|(values, extra, expected)| { + let body = super::tests::body_with(values, extra); + let answer = match validate_query_request_body(&body) { + Err(DynamoDbError::SerializationException(msg)) => ("SerializationException", msg), + Err(DynamoDbError::ValidationException(msg)) => ("ValidationException", msg), + other => panic!("{body}: unexpected answer {other:?}"), + }; + (answer != expected).then(|| format!("{body}: {answer:?}")) + }) + .collect(); + assert!(mismatches.is_empty(), "{mismatches:#?}"); +} + #[test] fn a_shape_fault_in_another_field_is_reported_ahead_of_the_checks() { // Measured 2026-10-25: a field of the wrong JSON type diff --git a/tests/test_query_value_shapes.py b/tests/test_query_value_shapes.py index 39c60ca0d..f2f005286 100644 --- a/tests/test_query_value_shapes.py +++ b/tests/test_query_value_shapes.py @@ -2,11 +2,12 @@ # SPDX-License-Identifier: Apache-2.0 """Query request bodies the service does not read as written: a field of the -wrong JSON type, an ExpressionAttributeValues value the service cannot read as -one type, and an ExpressionAttributeNames map the service refuses, in both -member orders. boto3 refuses or reshapes these bodies, so they go out as -written. Every expected answer below was measured against the service on -2026-10-25 (11:31 UTC), 2026-11-11 and 2026-11-19. +wrong JSON type, a member of another JSON type that the service reads, an +ExpressionAttributeValues value the service cannot read as one type, and an +ExpressionAttributeNames map the service refuses, in both member orders. boto3 +refuses or reshapes these bodies, so they go out as written. Every expected +answer below was measured against the service on 2026-10-25 (11:31 UTC), +2026-11-11, 2026-11-19 and 2026-11-23. Dual-target: runs against the service and against extenddb with the same assertions. @@ -93,15 +94,39 @@ def _raw_query(client, body: dict): ("B not base64 beside a null in an L", {"KeyConditionExpression": "pk = :p", "ExpressionAttributeValues": {":p": SX, ":z": {"L": [None, {"B": "!!"}]}}}), + # A shape fault past another fault in another member or value (measured + # 2026-11-23). + # The service: "NUMBER_VALUE cannot be converted to String". + ("Select number beside an unknown descriptor with Limit 0", + {"Limit": 0, "ExpressionAttributeValues": {":u": {"X": "1"}}, "Select": 5, + "KeyConditionExpression": "pk = :u"}), + # The service: "NUMBER_VALUE cannot be converted to String". + ("Select number beside an empty NS with Limit 0", + {"Limit": 0, "ExpressionAttributeValues": {":p": SX, ":s": {"NS": []}}, "Select": 5, + "KeyConditionExpression": "pk = :p"}), + # The service: "NUMBER_VALUE cannot be converted to String". + ("S number after an empty NS in another value with Limit 0", + {"Limit": 0, "ExpressionAttributeValues": {":p": SX, ":a": {"NS": []}, ":b": {"S": 5}}, + "KeyConditionExpression": "pk = :p"}), + # The service: "NUMBER_VALUE cannot be converted to Boolean". + ("ConsistentRead number with an invalid Select", + {"ConsistentRead": 1, "Select": "NOPE", "KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": {":p": SX}}), + # The service: "Unexpected token received from parser". + ("ConsistentRead on with an invalid Select", + {"ConsistentRead": "on", "Select": "NOPE", "KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": {":p": SX}}), ] class TestShapeFaultsAreReportedFirst: """A field of the wrong JSON type anywhere in the body answers SerializationException ahead of the Limit, parameter mix, enum and number - checks (measured 2026-10-25 11:31 UTC). The message texts differ between - the service and extenddb (#1012), so only the error type is asserted. The - comment on each row gives the service's message.""" + checks (measured 2026-10-25 11:31 UTC), also when an unknown descriptor or + an empty set sits in another member or value (measured 2026-11-23). The + message texts differ between the service and extenddb (#1012), so only the + error type is asserted. The comment on each row gives the service's + message.""" @pytest.mark.parametrize("row,body", SHAPE_FAULTS, ids=[r[0] for r in SHAPE_FAULTS]) def test_rows(self, dynamodb_client, ss_table, row, body): @@ -217,6 +242,46 @@ def test_the_value_the_service_cannot_read_is_named_beside_n_bob(self, dynamodb_ INVALID_VALUE + EMPTY_AV + " for key :z") +SELECT_NOPE = SELECT_MSG.replace("'bad'", "'NOPE'") + +# (row, body without TableName, the service's message), measured 2026-11-23. +NO_SHAPE_FAULT = [ + ("Limit 0 beside an unknown descriptor as the key value", + {"Limit": 0, "ExpressionAttributeValues": {":u": X1}, "KeyConditionExpression": "pk = :u"}, + "1 validation error detected: " + LIMIT_0_AT), + ("ConsistentRead string with an invalid Select", + {"ConsistentRead": "true", "Select": "NOPE", "KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": {":p": SX}}, SELECT_NOPE), + ("ConsistentRead T with an invalid Select", + {"ConsistentRead": "T", "Select": "NOPE", "KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": {":p": SX}}, SELECT_NOPE), + ("ScanIndexForward string with an invalid Select", + {"ScanIndexForward": "true", "Select": "NOPE", "KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": {":p": SX}}, SELECT_NOPE), + ("ScanIndexForward 0 with an invalid Select", + {"ScanIndexForward": "0", "Select": "NOPE", "KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": {":p": SX}}, SELECT_NOPE), + ("Limit 1.5 with an invalid Select", + {"Limit": 1.5, "Select": "NOPE", "KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": {":p": SX}}, SELECT_NOPE), +] + + +class TestMembersTheServiceReadsAreNotShapeFaults: + """The service reads a ConsistentRead or ScanIndexForward string such as + "true", "T" or "0" as a boolean and any number in Limit as an integer, and + an unknown descriptor is a value it cannot read as one type. So none of + them answers SerializationException, and the check's answer stands + (measured 2026-11-23). A string such as "on" is a shape fault (see + SHAPE_FAULTS).""" + + @pytest.mark.parametrize("row,body,expected", NO_SHAPE_FAULT, + ids=[r[0] for r in NO_SHAPE_FAULT]) + def test_rows(self, dynamodb_client, ss_table, row, body, expected): + _assert_validation(*_raw_query(dynamodb_client, {"TableName": ss_table, **body}), + expected) + + INVALID_KEY = 'ExpressionAttributeNames contains invalid key: Syntax error; key: "a"' BAD_NAMES = {"a": "b"} From 039729c0ba24407e67f7875e7675c54f2dacc37a Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:57:13 +0000 Subject: [PATCH 26/30] fix(scan): run the request checks in the service's order After the merge of fix/query-key-value-types, the number check takes the raw ExpressionAttributeValues map, so Scan passes it that map. Scan does not deserialize the map first any more, and a value that does not deserialize no longer skips the check of the other values. The checks now run in the order the service uses: 1. the Limit, Segment and TotalSegments ranges 2. the ReturnConsumedCapacity enum 3. the expression and non-expression parameter mix 4. the ExpressionAttributeNames checks 5. the numbers 6. an empty set or a set with a duplicate member 7. the Select enum Before this change, the mix check ran ahead of the ReturnConsumedCapacity check. The Select check also ran ahead of the names and set checks, which only the handler made. A value that the service cannot read as one type (a null, {}, an unknown type descriptor) changes the order, as on Query. The answer then gives an invalid Select and ReturnConsumedCapacity in one message, ahead of the mix, the names and the values. The caller passes in the mix check, so Scan checks its own members. A null in such a value is not a shape fault, and a number in Segment or TotalSegments is not one either, as for Limit. The Limit check uses the text Query uses, also below the int32 range. The Segment and TotalSegments texts do not change. Measured on 2026-11-19 and 2026-11-23 (us-east-1), each request twice. --- crates/engine/src/lib.rs | 6 +- crates/engine/src/query_key_values.rs | 24 +- .../engine/src/query_key_values/unreadable.rs | 21 +- crates/engine/src/scan.rs | 13 +- crates/engine/src/scan_request.rs | 193 +++++++++------ crates/engine/src/scan_request/tests.rs | 213 +++++++++++++--- tests/test_scan_number_values.py | 230 ++++++++++++++---- 7 files changed, 510 insertions(+), 190 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 58b185f58..57418c635 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -273,8 +273,10 @@ pub(crate) const RETURN_VALUES_MEMBERS: &[&str] = /// Pre-validate enum fields in a JSON body and return a combined error if /// multiple are invalid, in the order listed. Whether an operation aggregates /// its enum violations or stops at the first is per operation on the service -/// (PutItem and DeleteItem aggregate; UpdateItem, Query and Scan stop at the -/// first), so callers choose by passing one list or several sequential calls. +/// (`PutItem` and `DeleteItem` aggregate; `UpdateItem` stops at the first, and +/// so do `Query` and `Scan` for a body whose `ExpressionAttributeValues` the +/// service can read), so callers choose by passing one list or several +/// sequential calls. pub(crate) fn validate_enum_fields( body: &serde_json::Value, fields: &[EnumField<'_>], diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index c64badbff..c0684d7a3 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -39,7 +39,7 @@ use serde_json::{Map, Value}; mod unreadable; -use unreadable::{readable_for_shape_check, unreadable, unreadable_value_checks}; +pub(crate) use unreadable::{readable_for_shape_check, unreadable, unreadable_value_checks}; /// The service's text for a key condition value of the wrong type. pub const KEY_CONDITION_TYPE_MISMATCH: &str = "One or more parameter values were invalid: Condition parameter type does not match schema type"; @@ -59,8 +59,8 @@ const NULL_VALUE: &str = "The supplied Item contains a null AttributeValue"; const TYPE_DESCRIPTORS: [&str; 10] = ["S", "N", "B", "SS", "NS", "BS", "M", "L", "NULL", "BOOL"]; /// The members of the two enums the request-time checks read. -const RETURN_CONSUMED_CAPACITY: &[&str] = &["INDEXES", "TOTAL", "NONE"]; -const SELECT: &[&str] = &[ +pub(crate) const RETURN_CONSUMED_CAPACITY: &[&str] = &["INDEXES", "TOTAL", "NONE"]; +pub(crate) const SELECT: &[&str] = &[ "SPECIFIC_ATTRIBUTES", "COUNT", "ALL_ATTRIBUTES", @@ -148,10 +148,12 @@ pub fn validate_query_request_body(body: &Value) -> Result<(), DynamoDbError> { /// `Limit` `ValidationException` (measured 2026-10-25 and 2026-11-23); /// - a member the service reads from a JSON type that `T` refuses: a string /// in `ConsistentRead` or `ScanIndexForward` that the service reads as a -/// boolean (see [`BOOLEAN_TEXTS`]), and any number in `Limit`. Measured -/// 2026-11-23: `ConsistentRead: "true"` or `"T"`, `ScanIndexForward: -/// "true"` or `"0"`, and `Limit: 1.5` beside `Select: "NOPE"` answer the -/// `Select` text on `Query`, as `ConsistentRead: "true"` does on `Scan`, and +/// boolean (see [`BOOLEAN_TEXTS`]), and any number in `Limit`, `Segment` or +/// `TotalSegments`. Measured 2026-11-23, beside `Select: "NOPE"`: +/// `ConsistentRead: "true"` or `"T"`, `ScanIndexForward: "true"` or `"0"`, +/// and `Limit: 1.5` answer the `Select` text on `Query`, and +/// `ConsistentRead: "true"`, `Segment: 1.5` with `TotalSegments: 2`, and +/// `TotalSegments: 2.5` with `Segment: 0` answer it on `Scan`. /// `ConsistentRead: "yes"` with a table that does not exist answers /// `ResourceNotFoundException`. `ConsistentRead: "on"` answers /// `SerializationException: Unexpected token received from parser`, and @@ -182,7 +184,7 @@ pub(crate) fn shape_fault_first( { None } - ("Limit", Value::Number(_)) => None, + ("Limit" | "Segment" | "TotalSegments", Value::Number(_)) => None, ("ExpressionAttributeValues", Value::Object(entries)) => { entries.iter().find_map(|(key, entry)| { read( @@ -232,7 +234,7 @@ fn query_request_checks(body: &Value) -> Result<(), DynamoDbError> { if let Some(values) = values && values.values().any(unreadable) { - return unreadable_value_checks(body, values); + return unreadable_value_checks(body, values, validate_no_parameter_mix); } if let Some(limit) = body.get("Limit").and_then(Value::as_i64) @@ -354,7 +356,7 @@ pub(crate) fn non_empty(body: &Value, field: &str) -> bool { /// The entries of `values` by placeholder, so the reported value is /// deterministic when several are invalid. -fn sorted_entries(values: &Map) -> Vec<(&String, &Value)> { +pub(crate) fn sorted_entries(values: &Map) -> Vec<(&String, &Value)> { let mut entries: Vec<(&String, &Value)> = values.iter().collect(); entries.sort_by_key(|(key, _)| *key); entries @@ -491,7 +493,7 @@ fn number_fault(text: &str) -> Option> { /// # Errors /// /// Returns `DynamoDbError::ValidationException` with the service's text. -fn validate_expression_attribute_value_numbers( +pub(crate) fn validate_expression_attribute_value_numbers( values: &Map, ) -> Result<(), DynamoDbError> { match sorted_entries(values) diff --git a/crates/engine/src/query_key_values/unreadable.rs b/crates/engine/src/query_key_values/unreadable.rs index 385b56218..aa3011e39 100644 --- a/crates/engine/src/query_key_values/unreadable.rs +++ b/crates/engine/src/query_key_values/unreadable.rs @@ -14,7 +14,7 @@ use serde_json::{Map, Value}; use super::{ RETURN_CONSUMED_CAPACITY, SELECT, TYPE_DESCRIPTORS, first_fault, sorted_entries, - validate_name_keys, validate_names, validate_no_parameter_mix, + validate_name_keys, validate_names, }; /// Whether the service cannot read `value` as exactly one AttributeValue type: @@ -23,7 +23,7 @@ use super::{ /// value an `L` or `M` holds (measured 2026-11-19: `{"S": null}` beside a /// `Limit` of 0 answers `Value '0' at 'limit'`, as `{"X": "1"}` does). A value /// of another JSON type is a shape fault instead. -pub(super) fn unreadable(value: &Value) -> bool { +pub(crate) fn unreadable(value: &Value) -> bool { match value { Value::Null => true, Value::Object(map) => { @@ -54,7 +54,7 @@ pub(super) fn unreadable(value: &Value) -> bool { /// 2026-11-11: `{"L": [null, "x"]}`, `{"L": [{"X": "1"}, {"N": 5}]}` and /// `{"L": [null, {"B": "!!"}]}`, and `{"S": 5, "X": "1"}` and `{"S": 5, "N": /// "1"}` beside a `Limit` of 0, all answer `SerializationException`. -pub(super) fn readable_for_shape_check(body: &Value) -> Cow<'_, Value> { +pub(crate) fn readable_for_shape_check(body: &Value) -> Cow<'_, Value> { match body .get("ExpressionAttributeValues") .and_then(Value::as_object) @@ -129,7 +129,8 @@ fn null_value() -> Value { /// 'returnConsumedCapacity' failed to satisfy constraint: ...; Value '0' at /// 'limit' failed to satisfy constraint: Member must have value greater /// than or equal to 1`; -/// 2. the expression and non-expression parameter mix; +/// 2. the expression and non-expression parameter mix, which +/// `validate_parameter_mix` checks with the operation's members; /// 3. the `ExpressionAttributeNames` key checks: an invalid key, a key over /// 255 bytes and an empty map (measured 2026-11-19: an invalid names key /// beside `{"X": "1"}`, `{}` or `{"N": "1", "S": "x"}` answers the names @@ -162,9 +163,17 @@ fn null_value() -> Value { /// `:a` with `{"X": "1"}` beside `:b` with a null names `:b`, and `:a` with a /// null beside `:b` with `{"X": "1"}` names `:b`. This order names `:z`, `:a` /// and `:a` for them. -pub(super) fn unreadable_value_checks( +/// +/// The `Scan` request-time checks call this too, after their range checks. +/// Measured on `Scan` 2026-11-23, each request twice: an invalid `Select` and +/// `ReturnConsumedCapacity` beside `{}` answer both clauses in one message, +/// and a null, `{"L": [null]}` or `{"S": null}` beside an invalid `Select` +/// answers the `Select` text. `:a` with `{}` beside `:n` with `{"N": "bob"}` +/// names `:n` there, where this order names `:a`. +pub(crate) fn unreadable_value_checks( body: &Value, values: &Map, + validate_parameter_mix: fn(&Value) -> Result<(), DynamoDbError>, ) -> Result<(), DynamoDbError> { let mut violations: Vec = [ enum_violation(body, "Select", "select", SELECT), @@ -195,7 +204,7 @@ pub(super) fn unreadable_value_checks( ))); } - validate_no_parameter_mix(body)?; + validate_parameter_mix(body)?; validate_name_keys(body)?; // The values the service cannot read first; the sort is stable, so each diff --git a/crates/engine/src/scan.rs b/crates/engine/src/scan.rs index 48fdc1a5d..a9a137e6c 100755 --- a/crates/engine/src/scan.rs +++ b/crates/engine/src/scan.rs @@ -42,12 +42,13 @@ pub async fn handle_scan( ctx: &OperationContext, ) -> Result { // Request-time checks on the raw body, in the service's order: the Limit, - // Segment and TotalSegments ranges, the expression and non-expression - // parameter mix, the ReturnConsumedCapacity enum, every number in - // ExpressionAttributeValues, the Select enum. They run before typed - // deserialization so a field that does not deserialize does not stop the - // ones before it; a field of the wrong JSON type anywhere in the body is - // reported ahead of them; see `scan_request`. + // Segment and TotalSegments ranges, the ReturnConsumedCapacity enum, the + // expression and non-expression parameter mix, the + // ExpressionAttributeNames checks, every number in + // ExpressionAttributeValues, the set faults, the Select enum. They run + // before typed deserialization so a field that does not deserialize does + // not stop the ones before it; a field of the wrong JSON type is reported + // ahead of them; see `scan_request`. crate::scan_request::validate_scan_request_body(&body)?; let input: ScanInput = serde_json::from_value(body).map_err(crate::deserialize_error)?; diff --git a/crates/engine/src/scan_request.rs b/crates/engine/src/scan_request.rs index 2214d0058..d72c35973 100644 --- a/crates/engine/src/scan_request.rs +++ b/crates/engine/src/scan_request.rs @@ -2,66 +2,82 @@ // SPDX-License-Identifier: Apache-2.0 //! The `Scan` checks that run on the request body alone, before the body is -//! deserialized and before the table is looked up, in the service's order. +//! deserialized and before the table is looked up. //! -//! Measured 2026-10-25 (us-east-1, each request twice): +//! Measured 2026-10-25, 2026-11-19 and 2026-11-23 (us-east-1, each request +//! twice), for a body whose `ExpressionAttributeValues` the service can read, +//! the service answers in this order: //! //! 1. the range constraints on `Limit` (at least 1), `Segment` (0 to 999999) //! and `TotalSegments` (1 to 1000000), each checked when present, whether or -//! not the other segment field is. A `Limit` below 1 inside the int32 range -//! answers `1 validation error detected: Value at 'Limit' failed to satisfy -//! constraint: Member must have value greater than or equal to 1`; below -//! int32 the service saturates the value and answers the older form -//! `Value '-2147483648' at 'limit' ...`. The service aggregates several -//! range faults into one message; this module reports the first in the -//! order `Limit`, `Segment`, `TotalSegments`, with the `Segment` and -//! `TotalSegments` texts the previous release used; -//! 2. the expression and non-expression parameter mix; -//! 3. the `ReturnConsumedCapacity` enum; -//! 4. every number in `ExpressionAttributeValues`, `NS` members and values +//! not the other segment field is. This module reports the first fault in +//! the order `Limit`, `Segment`, `TotalSegments`, with the `Limit` text +//! `Query` uses and the `Segment` and `TotalSegments` texts of the previous +//! release. The service reports every range fault in one message, and its +//! texts differ from these for `Segment` and `TotalSegments`, and for a +//! `Limit` outside the int32 range; +//! 2. the `ReturnConsumedCapacity` enum; +//! 3. the expression and non-expression parameter mix; +//! 4. the `ExpressionAttributeNames` checks (see `validate_names`); +//! 5. every number in `ExpressionAttributeValues`, `NS` members and values //! nested in `L` and `M` included, whether a `FilterExpression` reads the //! value, nothing reads it, or the request carries no expression at all; a //! Unicode decimal digit counts as the digit it stands for; -//! 5. the `Select` enum. Both enums invalid answers the `ReturnConsumedCapacity` -//! error alone, so the two are not aggregated. +//! 6. an empty set and a set with a duplicate member (see `validate_sets`); +//! 7. the `Select` enum. Both enums invalid answers the +//! `ReturnConsumedCapacity` error alone. //! -//! Each of these is reported ahead of the next one, ahead of the table lookup, -//! and ahead of the checks the handler makes after deserializing the body -//! (Segment without TotalSegments and the reverse, Segment not below -//! TotalSegments, the undefined placeholder, unused value, filter syntax, -//! IndexName, ConsistentRead, Select with ProjectionExpression and -//! ExclusiveStartKey checks). A field of the wrong JSON type anywhere in the -//! body is reported ahead of all of them, as a `SerializationException`. - -use std::collections::HashMap; +//! A body whose `ExpressionAttributeValues` holds a value the service cannot +//! read as one type (a null, no type descriptor, an unknown one, more than +//! one, a null payload) takes another order on the service. An invalid +//! `Select` and `ReturnConsumedCapacity` are reported together, with the +//! range faults in an older form, then the mix, the names and the values. +//! Here the range checks above come first, then `unreadable_value_checks`. +//! +//! On the service the undefined placeholder, unused value and filter syntax +//! checks also come ahead of the `Select` enum and the table lookup (measured +//! 2026-11-19 and 2026-11-23: `{"Select": "bad", "FilterExpression": "a = +//! :undef"}` answers the undefined placeholder text). Here those checks stay +//! in the handler, after the table lookup, beside the `Segment` pairing, +//! `IndexName`, `ConsistentRead`, `Select` with `ProjectionExpression` and +//! `ExclusiveStartKey` checks. +//! +//! A member of the wrong JSON type is reported ahead of all of these, as a +//! `SerializationException`; see `shape_fault_first`. use extenddb_core::error::DynamoDbError; use extenddb_core::types::{AttributeValue, ScanInput}; -use serde_json::Value; +use serde::Deserialize; +use serde_json::{Map, Value}; use crate::query_key_values::{ - non_empty, present, shape_fault_first, validate_expression_attribute_value_numbers, + LIMIT_BELOW_ONE, RETURN_CONSUMED_CAPACITY, SELECT, non_empty, present, + readable_for_shape_check, shape_fault_first, sorted_entries, unreadable, + unreadable_value_checks, validate_expression_attribute_value_numbers, validate_names, }; -/// The `Scan` checks that run on the raw request body, in the service's order: -/// the `Limit`, `Segment` and `TotalSegments` ranges, the expression and -/// non-expression parameter mix, the `ReturnConsumedCapacity` enum, every -/// number in `ExpressionAttributeValues`, then the `Select` enum. +/// The `Scan` checks that run on the raw request body, in the order the +/// module documentation gives. /// /// The checks read the raw body, so a field that does not deserialize (an /// invalid `Select`, for one) does not stop the ones before it. When a check -/// fails, the body is deserialized as a [`ScanInput`] and a -/// `SerializationException` from that (a field of the wrong JSON shape -/// anywhere in the body) is the answer instead, as the service reports a shape -/// fault ahead of every validation; see [`shape_fault_first`]. A body that -/// passes every check is not deserialized here. +/// fails, each member of the body is deserialized on its own as part of a +/// [`ScanInput`], and a `SerializationException` from that is the answer +/// instead, as the service reports a shape fault ahead of every validation; +/// see `shape_fault_first`. For that read the parts of an +/// `ExpressionAttributeValues` value that the service cannot read are +/// replaced (see `readable_for_shape_check`), so a null value is not a shape +/// fault. A body that passes every check is not deserialized here. +/// +/// The server runs the same function ahead of the IAM decision. /// /// # Errors /// /// Returns `DynamoDbError::ValidationException` with the service's text, or /// `DynamoDbError::SerializationException` for a body of the wrong shape. pub fn validate_scan_request_body(body: &Value) -> Result<(), DynamoDbError> { - scan_request_checks(body).map_err(|check| shape_fault_first::(body, check)) + scan_request_checks(body) + .map_err(|check| shape_fault_first::(&readable_for_shape_check(body), check)) } /// The `Scan` checks in the service's order; see @@ -69,75 +85,94 @@ pub fn validate_scan_request_body(body: &Value) -> Result<(), DynamoDbError> { fn scan_request_checks(body: &Value) -> Result<(), DynamoDbError> { validate_ranges(body)?; - extenddb_core::validation::validate_no_expression_param_mixing( - &[ - ("AttributesToGet", non_empty(body, "AttributesToGet")), - ("ScanFilter", non_empty(body, "ScanFilter")), - ("ConditionalOperator", present(body, "ConditionalOperator")), - ], - &[ - ( - "ProjectionExpression", - present(body, "ProjectionExpression"), - ), - ("FilterExpression", present(body, "FilterExpression")), - ], - )?; + let values = body + .get("ExpressionAttributeValues") + .and_then(Value::as_object); + if let Some(values) = values + && values.values().any(unreadable) + { + return unreadable_value_checks(body, values, validate_parameter_mix); + } crate::validate_enum_fields( body, &[crate::EnumField { json_name: "ReturnConsumedCapacity", - valid: &["INDEXES", "TOTAL", "NONE"], + valid: RETURN_CONSUMED_CAPACITY, clause: crate::EnumClause::Named("returnConsumedCapacity"), }], )?; - if let Some(raw) = body.get("ExpressionAttributeValues") - && let Ok(values) = serde_json::from_value::>(raw.clone()) - { - validate_expression_attribute_value_numbers(&values)?; + validate_parameter_mix(body)?; + validate_names(body)?; + + if let Some(values) = values { + validate_expression_attribute_value_numbers(values)?; + validate_sets(values)?; } crate::validate_enum_fields( body, &[crate::EnumField { json_name: "Select", - valid: &[ - "SPECIFIC_ATTRIBUTES", - "COUNT", - "ALL_ATTRIBUTES", - "ALL_PROJECTED_ATTRIBUTES", - ], + valid: SELECT, clause: crate::EnumClause::Named("select"), }], ) } +/// The expression and non-expression parameter mix check. +fn validate_parameter_mix(body: &Value) -> Result<(), DynamoDbError> { + extenddb_core::validation::validate_no_expression_param_mixing( + &[ + ("AttributesToGet", non_empty(body, "AttributesToGet")), + ("ScanFilter", non_empty(body, "ScanFilter")), + ("ConditionalOperator", present(body, "ConditionalOperator")), + ], + &[ + ( + "ProjectionExpression", + present(body, "ProjectionExpression"), + ), + ("FilterExpression", present(body, "FilterExpression")), + ], + ) +} + +/// The faults the `AttributeValue` deserializer reports as a +/// `ValidationException`, such as an empty set and a set with a duplicate +/// member, with the deserializer's text. The values are visited in +/// placeholder order. The service reports these after the +/// `ExpressionAttributeNames` checks and ahead of the `Select` enum (measured +/// 2026-11-19 and 2026-11-23: a duplicate or an empty `NS`, a duplicate `SS` +/// or `BS`, and a duplicate `NS` in an `L` beside `Select: "NOPE"` answer the +/// set text). Beside a number fault in another value, the service named +/// either value between two identical requests (measured 2026-11-19), and +/// this check comes after the numbers. A value of the wrong JSON type is left +/// to the shape fault check. +fn validate_sets(values: &Map) -> Result<(), DynamoDbError> { + match sorted_entries(values).into_iter().find_map(|(_, value)| { + match AttributeValue::deserialize(value).map_err(crate::deserialize_error) { + Err(fault @ DynamoDbError::ValidationException(_)) => Some(fault), + _ => None, + } + }) { + Some(fault) => Err(fault), + None => Ok(()), + } +} + /// The range constraints on `Limit`, `Segment` and `TotalSegments`, the first -/// fault in that order. -/// -/// `Limit` answers the service's text: inside the int32 range the field is -/// capitalised and the value is not echoed; below int32 the service saturates -/// the value and uses the older `Value '' at 'limit'` form (measured -/// 2026-10-25, `Limit: -2147483649`). `Segment` and `TotalSegments` keep the -/// texts of the previous release. +/// fault in that order. `Limit` answers [`LIMIT_BELOW_ONE`], the text `Query` +/// uses. `Segment` and `TotalSegments` keep the texts of the previous release. fn validate_ranges(body: &Value) -> Result<(), DynamoDbError> { let get = |field: &str| body.get(field).and_then(Value::as_i64); if let Some(limit) = get("Limit") && limit < 1 { - let text = if limit >= i64::from(i32::MIN) { - "Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1".to_owned() - } else { - format!( - "Value '{}' at 'limit' failed to satisfy constraint: Member must have value greater than or equal to 1", - i32::MIN - ) - }; - return Err(DynamoDbError::ValidationException(format!( - "1 validation error detected: {text}" - ))); + return Err(DynamoDbError::ValidationException( + LIMIT_BELOW_ONE.to_owned(), + )); } if let Some(segment) = get("Segment") { if segment < 0 { diff --git a/crates/engine/src/scan_request/tests.rs b/crates/engine/src/scan_request/tests.rs index 2ae845559..b998733c2 100644 --- a/crates/engine/src/scan_request/tests.rs +++ b/crates/engine/src/scan_request/tests.rs @@ -1,12 +1,12 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! The expected texts below were measured against the service on 2026-10-25 -//! (us-east-1, each request twice), except where a test says otherwise: the -//! `Segment` and `TotalSegments` range texts are the previous release's (the -//! service aggregates range faults into one message with a different form, a -//! separate issue), and the deserializer test pins this module's hand-off, not -//! a service text. +//! The expected texts below were measured against the service on 2026-10-25, +//! 2026-11-19 and 2026-11-23 (us-east-1, each request twice), except where a +//! test says otherwise: the `Segment` and `TotalSegments` range texts are the +//! previous release's, a `Limit` outside the int32 range gets the text +//! `Query` uses (the service's texts for both are #563), and the deserializer +//! test pins this module's hand-off, not a service text. use extenddb_core::error::DynamoDbError; use serde_json::{Value, json}; @@ -17,6 +17,8 @@ const NUMERIC_BOB: &str = "The parameter cannot be converted to a numeric value: const LIMIT_RANGE: &str = "Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1"; const RCC_ENUM: &str = "1 validation error detected: Value 'NOPE' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]"; const SELECT_ENUM: &str = "1 validation error detected: Value 'NOPE' at 'select' failed to satisfy constraint: Member must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]"; +const MIX_SCAN_FILTER: &str = "Can not use both expression and non-expression parameters in the same request: \ + Non-expression parameters: {ScanFilter} Expression parameters: {FilterExpression}"; fn message(result: Result<(), DynamoDbError>) -> Option { match result { @@ -93,6 +95,15 @@ fn nested_numbers_and_the_other_number_faults_are_reported_with_the_service_text json!({"N": "1e-200"}), "Number underflow. Attempting to store a number with magnitude smaller than supported range", ), + // An exponent outside the int32 range (measured 2026-11-23). + ( + json!({"N": "1e9999999999"}), + "Number overflow. Attempting to store a number with magnitude larger than supported range", + ), + ( + json!({"N": "1e-9999999999"}), + "Number underflow. Attempting to store a number with magnitude smaller than supported range", + ), ( json!({"N": "1".repeat(39)}), "Attempting to store more than 38 significant digits in a Number", @@ -136,18 +147,16 @@ fn limit_segment_and_total_segments_ranges_come_first() { check(&with(base.clone(), "Limit", json!(-1))).as_deref(), Some(&*format!("1 validation error detected: {LIMIT_RANGE}")) ); - // The int32 minimum itself gets the capitalised form; below it the service - // saturates the value and uses the older form (measured 2026-10-25). - assert_eq!( - check(&with(base.clone(), "Limit", json!(-2_147_483_648_i64))).as_deref(), - Some(&*format!("1 validation error detected: {LIMIT_RANGE}")) - ); - assert_eq!( - check(&with(base.clone(), "Limit", json!(-2_147_483_649_i64))).as_deref(), - Some( - "1 validation error detected: Value '-2147483648' at 'limit' failed to satisfy constraint: Member must have value greater than or equal to 1" - ) - ); + // The int32 minimum itself gets the capitalised form. Below it the service + // saturates the value and uses the older form, `Value '-2147483648' at + // 'limit'` (measured 2026-10-25); this check gives the text `Query` gives. + for limit in [-2_147_483_648_i64, -2_147_483_649_i64] { + assert_eq!( + check(&with(base.clone(), "Limit", json!(limit))).as_deref(), + Some(&*format!("1 validation error detected: {LIMIT_RANGE}")), + "{limit}" + ); + } // Each segment field is range checked when present, with or without the // other one (the service's position; the texts are the previous release's). for (field, value, text) in [ @@ -241,24 +250,36 @@ fn limit_segment_and_total_segments_ranges_come_first() { } #[test] -fn parameter_mix_beats_the_enum_and_the_numbers() { +fn return_consumed_capacity_beats_the_parameter_mix_and_the_mix_beats_the_numbers() { let scan_filter = json!({"a": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]}}); let mix = with(bad_number(), "ScanFilter", scan_filter.clone()); - assert_eq!( - check(&mix).as_deref(), - Some( - "Can not use both expression and non-expression parameters in the same request: \ - Non-expression parameters: {ScanFilter} Expression parameters: {FilterExpression}" - ) - ); - assert_eq!( - check(&with(mix, "ReturnConsumedCapacity", json!("NOPE"))).as_deref(), - Some( - "Can not use both expression and non-expression parameters in the same request: \ - Non-expression parameters: {ScanFilter} Expression parameters: {FilterExpression}" - ) - ); + assert_eq!(check(&mix).as_deref(), Some(MIX_SCAN_FILTER)); + // Measured 2026-11-19 and 2026-11-23: an invalid ReturnConsumedCapacity + // is reported ahead of each form of the mix. + for mix in [ + with( + with(bad_number(), "ScanFilter", scan_filter.clone()), + "ExpressionAttributeValues", + json!({":n": {"N": "1"}}), + ), + with( + json!({"TableName": "t", "AttributesToGet": ["a"]}), + "ProjectionExpression", + json!("a"), + ), + with( + with(bad_number(), "ConditionalOperator", json!("AND")), + "ExpressionAttributeValues", + json!({":n": {"N": "1"}}), + ), + ] { + assert_eq!( + check(&with(mix.clone(), "ReturnConsumedCapacity", json!("NOPE"))).as_deref(), + Some(RCC_ENUM), + "{mix}" + ); + } let atg = with( with(bad_number(), "AttributesToGet", json!(["a"])), "ProjectionExpression", @@ -352,6 +373,12 @@ fn a_shape_fault_anywhere_in_the_body_is_reported_first() { json!({"TableName": "t", "ScanFilter": [1], "FilterExpression": "a = :n", "ExpressionAttributeValues": {":n": {"N": "1"}}}), json!({"TableName": "t", "Limit": 0, "Select": 5}), + // Measured 2026-11-23: the shape fault after a value the service + // cannot read is still found, in either member order. + json!({"TableName": "t", "Limit": 0, "ExpressionAttributeValues": {":u": {"X": "1"}}, + "Select": 5}), + json!({"TableName": "t", "Select": 5, "ExpressionAttributeValues": {":u": {"X": "1"}}, + "Limit": 0}), ]; for body in shape_faults { assert!( @@ -383,13 +410,121 @@ fn a_shape_fault_anywhere_in_the_body_is_reported_first() { Some(&*format!("1 validation error detected: {LIMIT_RANGE}")) ); // A body that passes every check is left to the handler's deserializer: a - // string Limit and a malformed AttributeValue are not range or number - // faults here. + // string Limit is not a range fault here. assert!(check(&json!({"TableName": "t", "Limit": "0"})).is_none()); - assert!( - check(&json!({"TableName": "t", "ExpressionAttributeValues": {":n": {"X": "bob"}}})) - .is_none() - ); +} + +// The measured rows stay in one data table. +#[allow(clippy::too_many_lines)] +#[test] +fn names_sets_and_unreadable_values_are_reported_in_the_measured_order() { + let select_bad = "1 validation error detected: Value 'bad' at 'select' failed to satisfy \ + constraint: Member must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, \ + ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]"; + let null_beside_select = |value: Value| { + json!({"TableName": "t", "FilterExpression": "attribute_exists(a) OR a = :v", + "ExpressionAttributeValues": {":v": value}, "Select": "bad"}) + }; + // Measured 2026-11-19 and 2026-11-23 (us-east-1, each body twice), except + // where a row says otherwise. + let rows = [ + ( + "names key ahead of the number", + with(bad_number(), "ExpressionAttributeNames", json!({"a": "b"})), + "ExpressionAttributeNames contains invalid key: Syntax error; key: \"a\"", + ), + ( + "empty names map ahead of the number", + with(bad_number(), "ExpressionAttributeNames", json!({})), + "ExpressionAttributeNames must not be empty", + ), + ( + "empty name ahead of the number", + with(bad_number(), "ExpressionAttributeNames", json!({"#a": ""})), + "ExpressionAttributeNames contains invalid value: Empty attribute name for key #a", + ), + ( + "names key ahead of a duplicate NS member", + json!({"TableName": "t", "ExpressionAttributeNames": {"a": "b"}, + "ExpressionAttributeValues": {":d": {"NS": ["1", "1"]}}}), + "ExpressionAttributeNames contains invalid key: Syntax error; key: \"a\"", + ), + // The service answers `One or more parameter values were invalid: + // Input collection contains duplicates.` for an NS (#1360). + ( + "duplicate NS member ahead of Select", + json!({"TableName": "t", "Select": "NOPE", "FilterExpression": "a = :d", + "ExpressionAttributeValues": {":d": {"NS": ["1", "1"]}}}), + "One or more parameter values were invalid: Input collection [1, 1] contains duplicates.", + ), + ( + "empty NS ahead of Select", + json!({"TableName": "t", "Select": "NOPE", + "ExpressionAttributeValues": {":d": {"NS": []}}}), + "One or more parameter values were invalid: An number set may not be empty", + ), + ( + "null beside Select", + null_beside_select(Value::Null), + select_bad, + ), + ( + "L with a null beside Select", + null_beside_select(json!({"L": [null]})), + select_bad, + ), + ( + "S null beside Select", + null_beside_select(json!({"S": null})), + select_bad, + ), + ( + "both enums beside {}", + json!({"TableName": "t", "Select": "BAD", "ReturnConsumedCapacity": "BAD", + "FilterExpression": "a = :a", "ExpressionAttributeValues": {":a": {}}}), + "2 validation errors detected: Value 'BAD' at 'select' failed to satisfy \ + constraint: Member must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, \ + ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]; Value 'BAD' at \ + 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum \ + value set: [INDEXES, TOTAL, NONE]", + ), + ( + "ScanFilter mix beside {\"X\": \"1\"}", + json!({"TableName": "t", "ScanFilter": {"a": {"ComparisonOperator": "EQ", + "AttributeValueList": [{"S": "x"}]}}, "FilterExpression": "a = :x", + "ExpressionAttributeValues": {":x": {"X": "1"}}}), + MIX_SCAN_FILTER, + ), + // The service names `:n` here (`... numeric value: bob for key :n`); + // it picks among faulty values by an order of its own (#1013). + ( + "{} beside N bob", + json!({"TableName": "t", "FilterExpression": "a = :a OR a = :n", + "ExpressionAttributeValues": {":a": {}, ":n": {"N": "bob"}}}), + "ExpressionAttributeValues contains invalid value: Supplied AttributeValue is \ + empty, must contain exactly one of the supported datatypes for key :a", + ), + ( + "X 1 beside a filter that does not read it", + json!({"TableName": "t", "FilterExpression": "attribute_exists(a)", + "ExpressionAttributeValues": {":x": {"X": "1"}}}), + "ExpressionAttributeValues contains invalid value: Supplied AttributeValue is \ + empty, must contain exactly one of the supported datatypes for key :x", + ), + ( + "Segment 1.5 beside Select", + json!({"TableName": "t", "Segment": 1.5, "TotalSegments": 2, "Select": "NOPE"}), + SELECT_ENUM, + ), + ( + "TotalSegments 2.5 beside Select", + json!({"TableName": "t", "Segment": 0, "TotalSegments": 2.5, "Select": "NOPE"}), + SELECT_ENUM, + ), + ]; + for (row, body, expected) in rows { + assert_eq!(check(&body).as_deref(), Some(expected), "{row}"); + } } #[test] diff --git a/tests/test_scan_number_values.py b/tests/test_scan_number_values.py index 89ab066aa..5e6202d86 100644 --- a/tests/test_scan_number_values.py +++ b/tests/test_scan_number_values.py @@ -9,24 +9,29 @@ before any row is read, whether a ``FilterExpression`` reads the value, nothing reads it, or the request carries no expression at all. Every expected answer below was measured against the service on 2026-10-25 (09:23 to 09:28, -10:38, 10:55 and 11:31 UTC) with each request sent twice. A Unicode decimal -digit in an ``N`` value counts as the digit it stands for; a field of the -wrong JSON type anywhere in the body answers ``SerializationException`` ahead +10:38, 10:55 and 11:31 UTC), 2026-11-19 or 2026-11-23 with each request sent +twice. A Unicode decimal digit in an ``N`` value counts as the digit it stands +for; a field of the wrong JSON type answers ``SerializationException`` ahead of every check. The rows also pin where the check falls against the other early Scan checks: -after the ``Limit``, ``Segment`` and ``TotalSegments`` range constraints -(``Value at 'Limit'`` with no value echoed for a ``Limit`` inside the int32 -range; the ``Segment`` and ``TotalSegments`` rows assert the position of the -check, not its text), the expression and non-expression parameter mix and the -``ReturnConsumedCapacity`` enum; and -before the ``Select`` enum, the Segment pairing checks, the table lookup, the +after the ``Limit``, ``Segment`` and ``TotalSegments`` range constraints, the +``ReturnConsumedCapacity`` enum, the expression and non-expression parameter +mix and the ``ExpressionAttributeNames`` checks; and before the set checks, +the ``Select`` enum, the Segment pairing checks, the table lookup, the IndexName, ConsistentRead, Select with ProjectionExpression, ExclusiveStartKey, undefined placeholder, unused value and filter syntax -checks. - -Dual-target: runs against the service and against extenddb with the same -assertions. +checks. A value the service cannot read as one type (a null, ``{}``, an +unknown type descriptor) takes another order: an invalid ``Select`` and +``ReturnConsumedCapacity`` are reported together, ahead of the mix, the names +and the values. + +Dual-target: runs against the service and against extenddb. Where extenddb +gives another text than the service, the row names both, the issue that +tracks the difference, and asserts the one for the target: the ``Segment`` +and ``TotalSegments`` range texts and a ``Limit`` outside int32 (#563), the +duplicate set text (#1360), the value named among several faulty values +(#1013), and the Segment pairing text. Run: EXTENDDB_TEST_ENDPOINT=https://localhost:18443 \\ @@ -39,7 +44,7 @@ import pytest from botocore.exceptions import ClientError -from conftest import scoped_table +from conftest import _is_real_dynamodb, scoped_table NUMERIC = "The parameter cannot be converted to a numeric value: " OVERFLOW = ( @@ -64,6 +69,31 @@ "constraint: Member must satisfy enum value set: " "[SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]" ) +SELECT_BAD = SELECT_ENUM.replace("'NOPE'", "'bad'") +ONE_ERROR = "1 validation error detected: " +AT_LEAST_0 = "greater than or equal to 0" +AT_LEAST_1 = "greater than or equal to 1" +AT_MOST_999999 = "less than or equal to 999999" +AT_MOST_1000000 = "less than or equal to 1000000" +TOTAL_BELOW_ONE = "The parameter TotalSegments should be greater than or equal to 1" +PAIRING = "The Segment parameter is zero-based and must be less than parameter TotalSegments" +MIX = ( + "Can not use both expression and non-expression parameters in the same request: " + "Non-expression parameters: {ScanFilter} Expression parameters: {FilterExpression}" +) +EAN_KEY = 'ExpressionAttributeNames contains invalid key: Syntax error; key: "a"' +INVALID_VALUE = "ExpressionAttributeValues contains invalid value: " +EMPTY_AV = "Supplied AttributeValue is empty, must contain exactly one of the supported datatypes" + + +def _newer(field: str, bound: str) -> str: + """The range text that names the field and not the value.""" + return f"{ONE_ERROR}Value at '{field}' failed to satisfy constraint: Member must have value {bound}" + + +def _older(value: int, field: str, bound: str) -> str: + """The range text that names the value and the field in lower camel case.""" + return f"{ONE_ERROR}Value '{value}' at '{field}' failed to satisfy constraint: Member must have value {bound}" S = {"AttributeType": "S"} SX = {"S": "x"} @@ -121,6 +151,9 @@ class TestNumberValues: pytest.param({"M": {"a": {"L": [{"M": {"b": NB}}]}}}, NUMERIC + "bob", id="M-L-M-N-bob"), pytest.param({"N": "1e200"}, OVERFLOW, id="overflow"), pytest.param({"N": "1e-200"}, UNDERFLOW, id="underflow"), + # Measured 2026-11-23 16:34 UTC: an exponent outside int32. + pytest.param({"N": "1e9999999999"}, OVERFLOW, id="exponent-above-int32"), + pytest.param({"N": "1e-9999999999"}, UNDERFLOW, id="exponent-below-int32"), pytest.param({"N": "1" * 39}, TOO_MANY_DIGITS, id="39-digits"), pytest.param({"N": ""}, NUMERIC, id="empty"), pytest.param({"N": " 1"}, NUMERIC + " 1", id="leading-space"), @@ -173,7 +206,9 @@ def test_with_conditional_operator_and_no_filter(self, dynamodb_client, table): ) == ("ValidationException", NUMERIC + "bob") def test_two_bad_numbers_report_one_of_them(self, dynamodb_client, table): - """The service's choice between two bad values varied between two runs; either is accepted.""" + """The service's choice between two bad values varied between two runs + (2026-10-25), and extenddb names the first by placeholder. The order the + service follows is #1013, so either value is accepted until that lands.""" code, msg = _scan_error( dynamodb_client, TableName=table, FilterExpression="a = :a", ExpressionAttributeValues={":a": {"N": "one"}, ":b": {"N": "two"}}, @@ -199,45 +234,59 @@ def test_limit_range(self, dynamodb_client_no_validation, table, limit): dynamodb_client_no_validation, TableName=table, Limit=limit, **NB_FILTER, ) == ("ValidationException", "1 validation error detected: " + LIMIT_RANGE) - @pytest.mark.parametrize("kwargs, field", [ - pytest.param({"Segment": 0, "TotalSegments": 0}, "totalsegments", id="TotalSegments-0"), - pytest.param({"Segment": 0, "TotalSegments": 1_000_001}, "totalsegments", id="TotalSegments-1000001"), - pytest.param({"Segment": -1, "TotalSegments": 2}, "segment", id="Segment-minus-1"), - pytest.param({"Segment": 1_000_000, "TotalSegments": 1_000_000}, "segment", id="Segment-1000000"), - pytest.param({"Segment": -1}, "segment", id="Segment-minus-1-alone"), - pytest.param({"TotalSegments": 0}, "totalsegments", id="TotalSegments-0-alone"), + @pytest.mark.parametrize("kwargs, service, extenddb", [ + pytest.param({"Segment": 0, "TotalSegments": 0}, _newer("TotalSegments", AT_LEAST_1), + TOTAL_BELOW_ONE, id="TotalSegments-0"), + pytest.param({"Segment": 0, "TotalSegments": 1_000_001}, + _newer("TotalSegments", AT_MOST_1000000), + _older(1_000_001, "totalSegments", AT_MOST_1000000), id="TotalSegments-1000001"), + pytest.param({"Segment": -1, "TotalSegments": 2}, _newer("Segment", AT_LEAST_0), + _older(-1, "segment", AT_LEAST_0), id="Segment-minus-1"), + pytest.param({"Segment": 1_000_000, "TotalSegments": 1_000_000}, + _newer("Segment", AT_MOST_999999), + _older(1_000_000, "segment", AT_MOST_999999), id="Segment-1000000"), + pytest.param({"Segment": -1}, _newer("Segment", AT_LEAST_0), + _older(-1, "segment", AT_LEAST_0), id="Segment-minus-1-alone"), + pytest.param({"TotalSegments": 0}, _newer("TotalSegments", AT_LEAST_1), + TOTAL_BELOW_ONE, id="TotalSegments-0-alone"), ]) - def test_segment_ranges(self, dynamodb_client_no_validation, table, kwargs, field): - # The range fault names the field and is reported ahead of the number; - # the text itself differs between the service and extenddb. - code, msg = _scan_error(dynamodb_client_no_validation, TableName=table, **kwargs, **NB_FILTER) - assert code == "ValidationException" - assert field in msg.lower().replace("'", "") - assert "bob" not in msg + def test_segment_ranges(self, dynamodb_client_no_validation, table, kwargs, service, extenddb): + # Measured 2026-11-23 13:59 and 16:47 UTC with the bad number beside + # each row: the range fault comes first. extenddb keeps the previous + # release's texts (#563). + expected = service if _is_real_dynamodb() else extenddb + assert _scan_error( + dynamodb_client_no_validation, TableName=table, **kwargs, **NB_FILTER, + ) == ("ValidationException", expected) def test_limit_range_is_reported_ahead_of_the_segment_ranges_and_the_number( self, dynamodb_client_no_validation, table, ): - code, msg = _scan_error( + # Measured 2026-11-19 16:15 UTC: the service reports the three range + # faults in one message; extenddb reports the first (#563). + service = ( + "3 validation errors detected: Value at 'Limit' failed to satisfy constraint: " + f"Member must have value {AT_LEAST_1}; Value at 'Segment' failed to satisfy " + f"constraint: Member must have value {AT_LEAST_0}; Value at 'TotalSegments' " + f"failed to satisfy constraint: Member must have value {AT_MOST_1000000}" + ) + expected = service if _is_real_dynamodb() else ONE_ERROR + LIMIT_RANGE + assert _scan_error( dynamodb_client_no_validation, TableName=table, Limit=0, Segment=-1, TotalSegments=1_000_001, **NB_FILTER, - ) - assert code == "ValidationException" - assert msg.endswith(LIMIT_RANGE) or msg.startswith("3 validation errors detected: " + LIMIT_RANGE) - assert "bob" not in msg + ) == ("ValidationException", expected) - def test_limit_below_int32_answers_the_saturated_value(self, dynamodb_client_no_validation, table): + def test_limit_at_and_below_the_int32_minimum(self, dynamodb_client_no_validation, table): # Measured 2026-10-25 10:38 and 10:55 UTC: outside int32 the service # echoes the saturated value in the older form, and beats the number. + # extenddb gives the text Query gives (#563). + service = _older(-2_147_483_648, "limit", AT_LEAST_1) assert _scan_error( dynamodb_client_no_validation, TableName=table, Limit=-2_147_483_649, **NB_FILTER, - ) == ("ValidationException", ( - "1 validation error detected: Value '-2147483648' at 'limit' failed to " - "satisfy constraint: Member must have value greater than or equal to 1" - )) + ) == ("ValidationException", service if _is_real_dynamodb() else ONE_ERROR + LIMIT_RANGE) assert _scan_error( dynamodb_client_no_validation, TableName=table, Limit=-2_147_483_648, **NB_FILTER, - ) == ("ValidationException", "1 validation error detected: " + LIMIT_RANGE) + ) == ("ValidationException", ONE_ERROR + LIMIT_RANGE) def test_limit_range_beats_the_missing_table(self, dynamodb_client_no_validation): assert _scan_error( @@ -258,14 +307,19 @@ def test_parameter_mix(self, dynamodb_client, table, extra, non_expression, expr f"Non-expression parameters: {{{non_expression}}} Expression parameters: {{{expression}}}", ) - def test_parameter_mix_beats_return_consumed_capacity(self, dynamodb_client_no_validation, table): + @pytest.mark.parametrize("extra", [ + pytest.param({"ScanFilter": SCAN_FILTER, **OK_FILTER}, id="ScanFilter"), + pytest.param({"AttributesToGet": ["a"], "ProjectionExpression": "a"}, id="AttributesToGet"), + pytest.param({"ConditionalOperator": "AND", **OK_FILTER}, id="ConditionalOperator"), + ]) + def test_return_consumed_capacity_beats_parameter_mix( + self, dynamodb_client_no_validation, table, extra, + ): + # Measured 2026-11-19 16:14 UTC and, for the ScanFilter form, + # 2026-11-23 13:59 UTC. assert _scan_error( - dynamodb_client_no_validation, TableName=table, ScanFilter=SCAN_FILTER, - ReturnConsumedCapacity="NOPE", **OK_FILTER, - ) == ("ValidationException", ( - "Can not use both expression and non-expression parameters in the same request: " - "Non-expression parameters: {ScanFilter} Expression parameters: {FilterExpression}" - )) + dynamodb_client_no_validation, TableName=table, ReturnConsumedCapacity="NOPE", **extra, + ) == ("ValidationException", RCC_ENUM) def test_limit_range_beats_parameter_mix(self, dynamodb_client_no_validation, table): assert _scan_error( @@ -336,6 +390,23 @@ def test_filter_syntax_error(self, dynamodb_client, table): ) == ("ValidationException", NUMERIC + "bob") +class TestSegmentPairing: + """Segment not below TotalSegments, and the smallest pair the service + accepts (measured 2026-11-19 16:15 UTC and 2026-11-23 16:34 UTC). extenddb + adds the two values after the service's text.""" + + def test_segment_not_below_total_segments(self, dynamodb_client, table): + expected = PAIRING if _is_real_dynamodb() else ( + PAIRING + ": Segment: 5 is not less than TotalSegments: 2") + assert _scan_error( + dynamodb_client, TableName=table, Segment=5, TotalSegments=2, + ) == ("ValidationException", expected) + + def test_total_segments_1_is_accepted(self, dynamodb_client, table): + resp = dynamodb_client.scan(TableName=table, Segment=0, TotalSegments=1) + assert (resp["Count"], resp["ScannedCount"]) == (2, 2) + + FW_ONE = "\uff11" # fullwidth digit one FW_SEVEN = "\uff17" # fullwidth digit seven AR_ONE = "\u0661" # Arabic-Indic digit one @@ -410,6 +481,9 @@ def _raw_scan(client, body: dict): ("ExpressionAttributeNames string with N bob", {"ExpressionAttributeNames": "x", **NB_FILTER}), ("AttributesToGet object with ProjectionExpression", {"AttributesToGet": {"a": 1}, "ProjectionExpression": "a"}), + # Measured 2026-11-23 13:59 UTC: NUMBER_VALUE cannot be converted to String. + ("Select 5 after an unknown type descriptor beside Limit 0", + {"Limit": 0, "ExpressionAttributeValues": {":u": {"X": "1"}}, "Select": 5}), ] @@ -430,3 +504,65 @@ def test_control_without_a_shape_fault_answers_the_check(self, dynamodb_client, assert status == 400 assert payload.get("__type", "").endswith("ValidationException") assert payload.get("message", payload.get("Message")) == "1 validation error detected: " + LIMIT_RANGE + + +NULL_BESIDE_SELECT = {"FilterExpression": "attribute_exists(a) OR a = :v", "Select": "bad"} +X1 = {"X": "1"} + +# (row, body, the service's message, extenddb's message when it differs). +# Measured 2026-11-19 16:14 to 16:19 UTC and 2026-11-23 13:59 to 16:47 UTC, +# each body twice on a table that does not exist. +ORDER_ROWS = [ + ("names key ahead of N bob", + {"ExpressionAttributeValues": {":n": NB}, "ExpressionAttributeNames": {"a": "b"}}, EAN_KEY, None), + ("empty names map ahead of N bob", + {"ExpressionAttributeValues": {":n": NB}, "ExpressionAttributeNames": {}}, + "ExpressionAttributeNames must not be empty", None), + ("empty name ahead of N bob", + {"ExpressionAttributeValues": {":n": NB}, "ExpressionAttributeNames": {"#a": ""}}, + "ExpressionAttributeNames contains invalid value: Empty attribute name for key #a", None), + # extenddb lists the members in the duplicates text (#1360). + ("duplicate NS member ahead of Select", + {"Select": "NOPE", "FilterExpression": "a = :d", "ExpressionAttributeValues": {":d": {"NS": ["1", "1"]}}}, + "One or more parameter values were invalid: Input collection contains duplicates.", + "One or more parameter values were invalid: Input collection [1, 1] contains duplicates."), + ("empty NS ahead of Select", + {"Select": "NOPE", "ExpressionAttributeValues": {":d": {"NS": []}}}, + "One or more parameter values were invalid: An number set may not be empty", None), + ("null beside Select", {**NULL_BESIDE_SELECT, "ExpressionAttributeValues": {":v": None}}, SELECT_BAD, None), + ("L with a null beside Select", + {**NULL_BESIDE_SELECT, "ExpressionAttributeValues": {":v": {"L": [None]}}}, SELECT_BAD, None), + ("S null beside Select", + {**NULL_BESIDE_SELECT, "ExpressionAttributeValues": {":v": {"S": None}}}, SELECT_BAD, None), + ("both enums beside {}", + {"Select": "BAD", "ReturnConsumedCapacity": "BAD", "FilterExpression": "a = :a", + "ExpressionAttributeValues": {":a": {}}}, + "2 validation errors detected: Value 'BAD' at 'select' failed to satisfy constraint: Member must " + "satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]; " + "Value 'BAD' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum " + "value set: [INDEXES, TOTAL, NONE]", None), + ("ScanFilter mix beside an unknown type descriptor", + {"ScanFilter": SCAN_FILTER, "FilterExpression": "a = :x", "ExpressionAttributeValues": {":x": X1}}, + MIX, None), + # The service names :n by an order of its own; extenddb names the value it + # cannot read first (#1013). + ("{} beside N bob", + {"FilterExpression": "a = :a OR a = :n", "ExpressionAttributeValues": {":a": {}, ":n": NB}}, + INVALID_VALUE + NUMERIC + "bob for key :n", INVALID_VALUE + EMPTY_AV + " for key :a"), + ("Segment 1.5 beside Select", {"Segment": 1.5, "TotalSegments": 2, "Select": "NOPE"}, SELECT_ENUM, None), + ("TotalSegments 2.5 beside Select", {"Segment": 0, "TotalSegments": 2.5, "Select": "NOPE"}, + SELECT_ENUM, None), +] + + +class TestRequestOrder: + """The names, set, unreadable value and float range rows, each against the + check it is reported ahead of.""" + + @pytest.mark.parametrize("row,body,service,extenddb", ORDER_ROWS, ids=[r[0] for r in ORDER_ROWS]) + def test_rows(self, dynamodb_client, table, row, body, service, extenddb): + status, payload = _raw_scan(dynamodb_client, {"TableName": table, **body}) + expected = service if _is_real_dynamodb() or extenddb is None else extenddb + assert (status, payload.get("__type", "").rsplit("#", 1)[-1], + payload.get("message", payload.get("Message"))) == (400, "ValidationException", expected) + From 6f722f7d7e9affa3d764a8980741fdacc4d19aa6 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:57:13 +0000 Subject: [PATCH 27/30] fix(server): run the Scan request checks before the IAM decision A Scan with a malformed body from a principal that may not Scan the table answered AccessDeniedException. The service answers the request's ValidationException to that principal (measured 2026-11-19 with a role allowed only DescribeTable, each request twice). So the Scan request-time checks now run beside the Query ones, after the cross-account refusal and before the IAM decision. The account and user setup of the LeadingKeys test moves to a base class, and the new Scan test uses it. --- crates/server/src/request_helpers.rs | 18 ++-- tests/test_query_leading_keys_values.py | 20 +++-- .../test_scan_checks_before_authorization.py | 82 +++++++++++++++++++ 3 files changed, 108 insertions(+), 12 deletions(-) create mode 100644 tests/test_scan_checks_before_authorization.py diff --git a/crates/server/src/request_helpers.rs b/crates/server/src/request_helpers.rs index 6c205c5eb..30db51297 100755 --- a/crates/server/src/request_helpers.rs +++ b/crates/server/src/request_helpers.rs @@ -245,11 +245,19 @@ pub(crate) async fn authorize_request( authz_resource::validate_tag_resource_arn_shape(arn)?; } - // A Query's request-time checks run before the IAM decision, after the - // cross-account refusal above; see - // `extenddb_engine::query_key_values::validate_query_request_body`. - if operation == "Query" { - extenddb_engine::query_key_values::validate_query_request_body(input)?; + // A Query's and a Scan's request-time checks run before the IAM decision, + // after the cross-account refusal above; see + // `extenddb_engine::query_key_values::validate_query_request_body` and + // `extenddb_engine::scan_request::validate_scan_request_body`. The service + // answers a malformed Scan with its ValidationException for a principal + // that may not Scan the table (measured 2026-11-19 with a role allowed + // only DescribeTable: an `N` value that is not a number, a `Limit` of 0 + // and a `Segment` of -1 each answer ValidationException). The checks read + // only the request body. + match operation { + "Query" => extenddb_engine::query_key_values::validate_query_request_body(input)?, + "Scan" => extenddb_engine::scan_request::validate_scan_request_body(input)?, + _ => {} } // A StreamArn (DescribeStream, GetShardIterator) or BackupArn diff --git a/tests/test_query_leading_keys_values.py b/tests/test_query_leading_keys_values.py index 5c0524de2..536684d8b 100644 --- a/tests/test_query_leading_keys_values.py +++ b/tests/test_query_leading_keys_values.py @@ -27,12 +27,10 @@ from test_query_value_shapes import EMPTY_AV, INVALID_VALUE, X1, _raw_query -class TestLeadingKeysWithAnInvalidKeyValue: - """A principal under each LeadingKeys fence form gets ValidationException and - no items for a Query whose ExpressionAttributeValues carries an N value that - is not a number, whether the key condition, the filter or nothing reads it. - - extenddb only: the fences need users created through the management API.""" +class ManagementPrincipals: + """A fresh account per test, and `_client` for a user in it with a given + policy. extenddb only: the users are created through the management API, + so a test class built on this one is skipped against the service.""" @pytest.fixture(autouse=True) def setup(self): @@ -40,7 +38,7 @@ def setup(self): admin_user = os.environ.get("EXTENDDB_ADMIN_USER", "").strip() admin_pass = os.environ.get("EXTENDDB_ADMIN_PASSWORD", "").strip() if not endpoint: - pytest.skip("LeadingKeys fences need the extenddb management API") + pytest.skip("the users need the extenddb management API") if not admin_user or not admin_pass: pytest.fail("MISCONFIGURED: EXTENDDB_ADMIN_USER and EXTENDDB_ADMIN_PASSWORD are required") from management_helpers import ManagementClient @@ -78,6 +76,14 @@ def _client(self, policy: dict | None) -> Any: verify=False, config=BotoConfig(retries={"max_attempts": 0}, parameter_validation=False)) + +class TestLeadingKeysWithAnInvalidKeyValue(ManagementPrincipals): + """A principal under each LeadingKeys fence form gets ValidationException and + no items for a Query whose ExpressionAttributeValues carries an N value that + is not a number, whether the key condition, the filter or nothing reads it. + + extenddb only: the fences need users created through the management API.""" + def _fence(self, condition: dict, table: str) -> dict: arn = f"arn:aws:dynamodb:{self.region}:{self.account_id}:table/{table}" return { diff --git a/tests/test_scan_checks_before_authorization.py b/tests/test_scan_checks_before_authorization.py new file mode 100644 index 000000000..0984fc0f0 --- /dev/null +++ b/tests/test_scan_checks_before_authorization.py @@ -0,0 +1,82 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""A malformed Scan from a principal that may not Scan the table answers the +request's ValidationException, not AccessDeniedException. The principal is a +user created through the extenddb management API, so this file is skipped +against the service. + +Run: + EXTENDDB_TEST_ENDPOINT=https://localhost:18443 \\ + EXTENDDB_ADMIN_USER=admin EXTENDDB_ADMIN_PASSWORD= \\ + pytest tests/test_scan_checks_before_authorization.py -v +""" + +from __future__ import annotations + +from conftest import scoped_table +from test_query_leading_keys_values import ManagementPrincipals +from test_scan_number_values import ( + EAN_KEY, + EMPTY_AV, + INVALID_VALUE, + LIMIT_RANGE, + MIX, + NB_FILTER, + NULL_BESIDE_SELECT, + NUMERIC, + OK_FILTER, + ONE_ERROR, + OVERFLOW, + RCC_ENUM, + SCAN_FILTER, + SELECT_BAD, + SELECT_ENUM, + X1, + _raw_scan, +) + +# Measured 2026-11-19 16:34 UTC with a role allowed only dynamodb:DescribeTable +# on the table, each body twice: the service answers each with the text below, +# and the valid body with AccessDeniedException. +ROWS = [ + ("N bob", NB_FILTER, NUMERIC + "bob"), + ("Limit 0", {"Limit": 0}, ONE_ERROR + LIMIT_RANGE), + ("ReturnConsumedCapacity", {"ReturnConsumedCapacity": "NOPE"}, RCC_ENUM), + ("mix", {"ScanFilter": SCAN_FILTER, "FilterExpression": "attribute_exists(a)"}, MIX), + ("Select", {"Select": "NOPE"}, SELECT_ENUM), + ("names", {"ExpressionAttributeNames": {"a": "b"}, "FilterExpression": "attribute_exists(a)"}, EAN_KEY), + ("unknown type descriptor", {"FilterExpression": "a = :x", "ExpressionAttributeValues": {":x": X1}}, + INVALID_VALUE + EMPTY_AV + " for key :x"), + ("null beside Select", {**NULL_BESIDE_SELECT, "ExpressionAttributeValues": {":v": None}}, SELECT_BAD), + ("exponent above int32", + {"FilterExpression": "a = :n", "ExpressionAttributeValues": {":n": {"N": "1e9999999999"}}}, OVERFLOW), +] + + +class TestChecksBeforeAuthorization(ManagementPrincipals): + """extenddb only: the principal needs a user created through the + management API.""" + + def test_a_principal_that_may_not_scan_gets_the_validation_exception(self): + owner = self._client({ + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"}], + }) + with scoped_table(owner) as name: + arn = f"arn:aws:dynamodb:{self.region}:{self.account_id}:table/{name}" + describe_only = self._client({ + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "dynamodb:DescribeTable", "Resource": arn}], + }) + failures = [] + for row, body, message in ROWS: + status, payload = _raw_scan(describe_only, {"TableName": name, **body}) + got = (status, payload.get("__type", "").rsplit("#", 1)[-1], + payload.get("message", payload.get("Message"))) + if got != (400, "ValidationException", message): + failures.append(f"{row}: {got}") + status, payload = _raw_scan(describe_only, {"TableName": name, **OK_FILTER}) + if (status, payload.get("__type", "").rsplit("#", 1)[-1]) != (400, "AccessDeniedException"): + failures.append(f"valid body: {status} {payload}") + assert not failures, "\n".join(failures) From 0e0f07817820f08e724d41024b92e49152a3090b Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:52:01 +0000 Subject: [PATCH 28/30] fix(query): leave the check's answer beside a null member or name When a request-time check fails, shape_fault_first deserializes each member on its own. It reports a member of the wrong JSON type ahead of the check, as the service does. It counted two nulls as such a member. ScanIndexForward: null beside Select: "NOPE" answered SerializationException here, where the service and main answer the Select text. ExpressionAttributeNames: {"#a": null} beside an invalid Select or ReturnConsumedCapacity did the same. The service reads a null member as an absent one and a null name as an empty name, which it reports after these checks. shape_fault_first now skips a null member, with the rule present() already applies to the parameter mix, and reads ExpressionAttributeNames without its null names. The handler's deserializer still refuses both nulls. I measured the service answers on 2026-11-24, each body twice. On d7e6ff35b, the 3 new unit rows fail, and the 3 new rows in tests/test_query_value_shapes.py fail. --- crates/engine/src/query_key_values.rs | 28 ++++++++++++++++-- .../query_key_values/request_order_tests.rs | 29 +++++++++++++++++-- tests/test_query_value_shapes.py | 17 +++++++++-- 3 files changed, 67 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index 2405c3418..06162a7a1 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -157,7 +157,18 @@ pub fn validate_query_request_body(body: &Value) -> Result<(), DynamoDbError> { /// `SerializationException: Unexpected token received from parser`, and /// `ConsistentRead: 1` `SerializationException: NUMBER_VALUE cannot be /// converted to Boolean`. The handler's own deserialization still refuses -/// every string in these members. +/// every string in these members; +/// - a null member, which the service reads as an absent one (see +/// [`present`]), and a null name in `ExpressionAttributeNames`, which it +/// reads as an empty name and reports after these checks. Measured +/// 2026-11-24, each body twice: `ScanIndexForward: null` beside `Select: +/// "NOPE"` answers the `Select` text, and alone, with a table that does not +/// exist, `ResourceNotFoundException`; `ExpressionAttributeNames: {"#a": +/// null}` beside `Select: "NOPE"` or `ReturnConsumedCapacity: "NOPE"` +/// answers that enum's text, beside `{"N": "bob"}` the numeric text in the +/// `ExpressionAttributeValues contains invalid value` form, and alone +/// `ExpressionAttributeNames contains invalid value: Empty attribute name +/// for key #a`. The handler's own deserialization still refuses both. pub(crate) fn shape_fault_first( body: &Value, check: DynamoDbError, @@ -174,6 +185,7 @@ pub(crate) fn shape_fault_first( body.as_object() .into_iter() .flatten() + .filter(|(name, _)| present(body, name)) .find_map(|(name, value)| match (name.as_str(), value) { ("ConsistentRead" | "ScanIndexForward", Value::String(text)) if BOOLEAN_TEXTS @@ -183,6 +195,16 @@ pub(crate) fn shape_fault_first( None } ("Limit", Value::Number(_)) => None, + ("ExpressionAttributeNames", Value::Object(names)) => read( + name, + Value::Object( + names + .iter() + .filter(|(_, alias)| !alias.is_null()) + .map(|(key, alias)| (key.clone(), alias.clone())) + .collect(), + ), + ), ("ExpressionAttributeValues", Value::Object(entries)) => { entries.iter().find_map(|(key, entry)| { read( @@ -301,7 +323,9 @@ fn validate_no_parameter_mix(body: &Value) -> Result<(), DynamoDbError> { /// The checks the `ExpressionAttributeNames` deserializer makes, on the raw /// body: an empty map, a key that is not `#` and a name, a key over 255 bytes, /// and an empty name, with the deserializer's text. A map or name of another -/// JSON type is a shape fault, which this leaves to the shape fault check. +/// JSON type is a shape fault, which this leaves to the shape fault check, and +/// a null name is left to the handler's deserializer (see +/// [`shape_fault_first`]). /// /// # Errors /// diff --git a/crates/engine/src/query_key_values/request_order_tests.rs b/crates/engine/src/query_key_values/request_order_tests.rs index 75b1b04fe..bf7bbbba4 100644 --- a/crates/engine/src/query_key_values/request_order_tests.rs +++ b/crates/engine/src/query_key_values/request_order_tests.rs @@ -176,8 +176,9 @@ fn each_member_and_value_is_read_on_its_own_for_a_shape_fault() { // A shape fault is reported past an unknown descriptor or an empty set in // another member or value, a number or an `"on"` in `ConsistentRead` is a // shape fault, and a member the service reads from a JSON type the typed - // input refuses leaves the check's answer. Each row holds the values, the - // other members and the answer. + // input refuses leaves the check's answer. Measured 2026-11-24 the same + // way: a null member and a null name leave the check's answer too. Each + // row holds the values, the other members and the answer. let shape = |text: &str| { ( "SerializationException", @@ -241,7 +242,29 @@ fn each_member_and_value_is_read_on_its_own_for_a_shape_fault() { json!({"ScanIndexForward": "0", "Select": "NOPE"}), select_nope.clone(), ), - (sx, json!({"Limit": 1.5, "Select": "NOPE"}), select_nope), + ( + sx.clone(), + json!({"Limit": 1.5, "Select": "NOPE"}), + select_nope.clone(), + ), + ( + sx.clone(), + json!({"ScanIndexForward": null, "Select": "NOPE"}), + select_nope.clone(), + ), + ( + sx.clone(), + json!({"ExpressionAttributeNames": {"#a": null}, "Select": "NOPE"}), + select_nope, + ), + ( + sx, + json!({"ExpressionAttributeNames": {"#a": null}, "ReturnConsumedCapacity": "NOPE"}), + ( + "ValidationException", + one_error(&RCC_BAD.replace("'bad'", "'NOPE'")), + ), + ), ]; let mismatches: Vec = rows .into_iter() diff --git a/tests/test_query_value_shapes.py b/tests/test_query_value_shapes.py index f2f005286..9428731ae 100644 --- a/tests/test_query_value_shapes.py +++ b/tests/test_query_value_shapes.py @@ -7,7 +7,7 @@ ExpressionAttributeNames map the service refuses, in both member orders. boto3 refuses or reshapes these bodies, so they go out as written. Every expected answer below was measured against the service on 2026-10-25 (11:31 UTC), -2026-11-11, 2026-11-19 and 2026-11-23. +2026-11-11, 2026-11-19, 2026-11-23 and 2026-11-24. Dual-target: runs against the service and against extenddb with the same assertions. @@ -264,6 +264,17 @@ def test_the_value_the_service_cannot_read_is_named_beside_n_bob(self, dynamodb_ ("Limit 1.5 with an invalid Select", {"Limit": 1.5, "Select": "NOPE", "KeyConditionExpression": "pk = :p", "ExpressionAttributeValues": {":p": SX}}, SELECT_NOPE), + # A null member and a null name (measured 2026-11-24). + ("ScanIndexForward null with an invalid Select", + {"ScanIndexForward": None, "Select": "NOPE", "KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": {":p": SX}}, SELECT_NOPE), + ("null name with an invalid Select", + {"ExpressionAttributeNames": {"#a": None}, "Select": "NOPE", + "KeyConditionExpression": "pk = :p", "ExpressionAttributeValues": {":p": SX}}, SELECT_NOPE), + ("null name with an invalid ReturnConsumedCapacity", + {"ExpressionAttributeNames": {"#a": None}, "ReturnConsumedCapacity": "NOPE", + "KeyConditionExpression": "pk = :p", "ExpressionAttributeValues": {":p": SX}}, + RCC_MSG.replace("'bad'", "'NOPE'")), ] @@ -273,7 +284,9 @@ class TestMembersTheServiceReadsAreNotShapeFaults: an unknown descriptor is a value it cannot read as one type. So none of them answers SerializationException, and the check's answer stands (measured 2026-11-23). A string such as "on" is a shape fault (see - SHAPE_FAULTS).""" + SHAPE_FAULTS). The service reads a null member as an absent one and a null + name as an empty name, which it reports after these checks, so the + check's answer stands there too (measured 2026-11-24).""" @pytest.mark.parametrize("row,body,expected", NO_SHAPE_FAULT, ids=[r[0] for r in NO_SHAPE_FAULT]) From 35910e977762edbff77102f0ede918caec355df6 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:10:27 +0000 Subject: [PATCH 29/30] fix(query): name a set fault beside a second type descriptor For an ExpressionAttributeValues value with two type descriptors, first_fault reads each payload and names the first fault ahead of the more than one datatypes text. It read the numbers only. The service also refuses an empty set and a set with a duplicate member there. {"SS": ["a", "a"], "N": "1"} answered the more than one datatypes text here, where the service answers "Input collection [a, a] contains duplicates." for :z, and {"NS": ["1", "1"], "S": "x"} answers "Input collection contains duplicates". first_fault now takes these set faults too, on this path only. It reads SS ahead of the numbers, so {"SS": ["a", "a"], "N": "bob"} answers the duplicate text. It reads NS after its own numbers, so {"NS": ["1", "1"], "N": "bob"} answers the numeric text. The SS and BS texts come from the AttributeValue deserializer. The NS text and its check move from core's partiql module to validation::number, so a build without the partiql feature has them. The deserializer still reports a set with a duplicate member and no second descriptor, as before. I measured the service answers on 2026-11-24, each body twice. On 0e0f07817, 12 of the 15 new unit rows fail, and 12 of the 15 new rows in tests/test_query_value_shapes.py fail. The 3 rows that answer the numeric text pass there and pin what does not change. --- crates/core/src/partiql/params.rs | 19 +---- crates/core/src/validation/number.rs | 21 +++++ crates/engine/src/query_key_values.rs | 77 +++++++++++++++---- .../engine/src/query_key_values/unreadable.rs | 10 ++- .../src/query_key_values/unreadable_tests.rs | 37 ++++++++- tests/test_query_value_shapes.py | 40 +++++++++- 6 files changed, 165 insertions(+), 39 deletions(-) diff --git a/crates/core/src/partiql/params.rs b/crates/core/src/partiql/params.rs index 751127e58..94f148127 100644 --- a/crates/core/src/partiql/params.rs +++ b/crates/core/src/partiql/params.rs @@ -45,8 +45,6 @@ //! reported can differ from the service's, which walks the request's order //! (measured 2026-11-02). -use std::collections::HashSet; - use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64; use serde::Deserialize; @@ -55,13 +53,8 @@ use serde_json::{Map, Value}; use super::number::{check_number, parameter_message}; use crate::types::AttributeValue; use crate::validation::MAX_ITEM_NESTING_DEPTH; -use crate::validation::number::validate_and_normalize_number; - -/// The refusal of a number set parameter two of whose members have one -/// value, the same at any depth and for members written alike (measured -/// 2026-11-06: `{"NS": ["1", "1.0"]}`, `{"NS": ["1", "1"]}`, and inside a -/// map and a list). -pub const NUMBER_SET_DUPLICATES: &str = "Input collection contains duplicates"; +pub use crate::validation::number::NUMBER_SET_DUPLICATES; +use crate::validation::number::has_equal_numbers; /// The service's nesting-depth message, the same for parameters as for items. pub const NESTING_MESSAGE: &str = "Nesting Levels have exceeded supported limits: \ @@ -298,14 +291,6 @@ fn content_refusal(tag: &str, payload: &Value) -> Result<(), String> { .map_err(|e| e.to_string()) } -/// Whether two members of a number set have one value. -fn has_equal_numbers(items: &[Value]) -> bool { - let mut values = HashSet::with_capacity(items.len()); - items.iter().filter_map(Value::as_str).any(|text| { - !values.insert(validate_and_normalize_number(text).unwrap_or_else(|_| text.to_owned())) - }) -} - fn enter(depth: usize) -> Result { let next = depth + 1; if next > MAX_ITEM_NESTING_DEPTH { diff --git a/crates/core/src/validation/number.rs b/crates/core/src/validation/number.rs index e042f8a4a..2042018b7 100644 --- a/crates/core/src/validation/number.rs +++ b/crates/core/src/validation/number.rs @@ -1,6 +1,8 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 +use std::collections::HashSet; + use crate::error::DynamoDbError; pub mod operations; @@ -19,6 +21,25 @@ pub(super) const MIN_MAGNITUDE: i64 = MIN_EXPONENT as i64 + 1; /// is named after a colon; an empty one is not. pub const NOT_A_NUMBER: &str = "The parameter cannot be converted to a numeric value"; +/// The service's refusal of a number set two of whose members have one +/// value, the same at any depth and for members written alike. Measured +/// 2026-11-06 on a statement parameter (`{"NS": ["1", "1.0"]}`, `{"NS": +/// ["1", "1"]}`, and inside a map and a list), and 2026-11-24 on a `Query` +/// `ExpressionAttributeValues` entry beside a second type descriptor, as +/// `ExpressionAttributeValues contains invalid value: ... for key :z`. +pub const NUMBER_SET_DUPLICATES: &str = "Input collection contains duplicates"; + +/// Whether two members of a number set have one value: `1` and `1.0` do. +/// A member that is not a string is skipped. +#[must_use] +pub fn has_equal_numbers(items: &[serde_json::Value]) -> bool { + let mut values = HashSet::with_capacity(items.len()); + items + .iter() + .filter_map(serde_json::Value::as_str) + .any(|text| !values.insert(normalize_number(text).unwrap_or_else(|_| text.to_owned()))) +} + /// Why a string is not a number `DynamoDB` can store, as /// [`normalize_number`] reports it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index 06162a7a1..8dd925af3 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -31,9 +31,9 @@ use extenddb_core::expression::{ Expr, ExpressionMaps, KeyCondition, PathElement, SortKeyCondition, }; use extenddb_core::types::{ - AttributeDefinition, EMPTY_ATTRIBUTE_VALUE, MULTI_ATTRIBUTE_VALUE, QueryInput, + AttributeDefinition, AttributeValue, EMPTY_ATTRIBUTE_VALUE, MULTI_ATTRIBUTE_VALUE, QueryInput, }; -use extenddb_core::validation::number::NOT_A_NUMBER; +use extenddb_core::validation::number::{NOT_A_NUMBER, NUMBER_SET_DUPLICATES, has_equal_numbers}; use serde::de::DeserializeOwned; use serde_json::{Map, Value}; @@ -52,11 +52,13 @@ pub const LIMIT_BELOW_ONE: &str = "1 validation error detected: Value at 'Limit' /// out. const NULL_VALUE: &str = "The supplied Item contains a null AttributeValue"; -/// The type descriptors of an AttributeValue, in the order the service reads +/// The type descriptors of an AttributeValue, in the order the service checks /// the payloads of a value with several type descriptors (see -/// [`first_fault`]). Core's list is a private constant of its `partiql` -/// module, as for [`NULL_VALUE`]. -const TYPE_DESCRIPTORS: [&str; 10] = ["S", "N", "B", "SS", "NS", "BS", "M", "L", "NULL", "BOOL"]; +/// [`first_fault`]): a duplicate `SS` member ahead of the numbers (measured +/// 2026-11-24), `N` ahead of `NS`, `NS` ahead of `BS`, and `NS` and `M` ahead +/// of `L`. Core's list is a private constant of its `partiql` module, as for +/// [`NULL_VALUE`]. +const TYPE_DESCRIPTORS: [&str; 10] = ["SS", "S", "N", "B", "NS", "BS", "M", "L", "NULL", "BOOL"]; /// The members of the two enums the request-time checks read. const RETURN_CONSUMED_CAPACITY: &[&str] = &["INDEXES", "TOTAL", "NONE"]; @@ -398,6 +400,9 @@ enum Fault<'a> { /// A number the number rules refuse for its magnitude or precision, with /// their text. Refused(String), + /// An empty set, or a set two of whose members have one value, beside a + /// second type descriptor, with the text of that path (see [`set_fault`]). + Set(String), } impl Fault<'_> { @@ -425,14 +430,19 @@ impl Fault<'_> { Fault::SeveralTypes => MULTI_ATTRIBUTE_VALUE.to_owned(), Fault::NotANumber("") => NOT_A_NUMBER.to_owned(), Fault::NotANumber(text) => format!("{NOT_A_NUMBER}: {text}"), - Fault::Refused(msg) => msg, + Fault::Refused(msg) | Fault::Set(msg) => msg, } } } /// The first fault in `value` (`member` is its name when it is the value of an -/// `M` member): a null or no type descriptor, then the numbers in `N`, `NS` -/// and every value an `L` or `M` holds, then more than one type descriptor. +/// `M` member): a null or no type descriptor, then the payloads in the order +/// of [`TYPE_DESCRIPTORS`] (the numbers in `N` and `NS`, and every value an +/// `L` or `M` holds), then more than one type descriptor. With `sets`, an +/// empty set and a set two of whose members have one value are faults too, +/// `SS` ahead of the numbers and `NS` after its own numbers (see +/// [`set_fault`]); without it, the deserializer reports them after the +/// request-time checks. /// `L` items are visited in document order and `M` members in the map's /// iteration order: sorted by key without the `preserve_order` feature of /// `serde_json`, in document order with it, as in the MongoDB build (bson @@ -449,8 +459,11 @@ impl Fault<'_> { /// (measured 2026-11-19: `{"N": "bob", "S": "x"}` and `{"S": "x", "N": "bob"}` /// answer the numeric text for `bob`, `{"N": "1", "S": "x"}` the more than one /// datatypes text, `{"S": "x", "L": [null]}` the null text, and `N` is read -/// ahead of `NS`, `NS` and `M` ahead of `L`). -fn first_fault<'a>(value: &'a Value, member: Option<&'a str>) -> Option> { +/// ahead of `NS`, `NS` and `M` ahead of `L`; measured 2026-11-24: `{"SS": +/// ["a", "a"], "N": "bob"}` answers the duplicate text, `{"NS": ["1", "1"], +/// "N": "bob"}` the numeric text, and `{"NS": ["1", "1"], "L": [{"N": +/// "bob"}]}` the duplicate text). +fn first_fault<'a>(value: &'a Value, member: Option<&'a str>, sets: bool) -> Option> { let Value::Object(map) = value else { return value.is_null().then_some(Fault::Null(member)); }; @@ -465,11 +478,15 @@ fn first_fault<'a>(value: &'a Value, member: Option<&'a str>) -> Option members .iter() .filter_map(Value::as_str) - .find_map(number_fault), - ("L", Value::Array(items)) => items.iter().find_map(|item| first_fault(item, None)), + .find_map(number_fault) + .or_else(|| sets.then(|| set_fault(descriptor, members)).flatten()), + ("SS" | "BS", Value::Array(members)) if sets => set_fault(descriptor, members), + ("L", Value::Array(items)) => { + items.iter().find_map(|item| first_fault(item, None, sets)) + } ("M", Value::Object(members)) => members .iter() - .find_map(|(name, inner)| first_fault(inner, Some(name))), + .find_map(|(name, inner)| first_fault(inner, Some(name), sets)), _ => None, }); match payloads.len() { @@ -479,6 +496,36 @@ fn first_fault<'a>(value: &'a Value, member: Option<&'a str>) -> Option(descriptor: &str, members: &[Value]) -> Option> { + if !members.iter().all(Value::is_string) { + return None; + } + if descriptor == "NS" && has_equal_numbers(members) { + return Some(Fault::Set(NUMBER_SET_DUPLICATES.to_owned())); + } + let set = Value::Object(Map::from_iter([( + descriptor.to_owned(), + Value::Array(members.to_vec()), + )])); + match serde_json::from_value::(set).map_err(crate::deserialize_error) { + Err(DynamoDbError::ValidationException(msg)) => Some(Fault::Set(msg)), + _ => None, + } +} + /// `text` against the number rules, with Unicode decimal digits folded for the /// check; see [`crate::decimal_digits`]. fn number_fault(text: &str) -> Option> { @@ -520,7 +567,7 @@ fn validate_expression_attribute_value_numbers( ) -> Result<(), DynamoDbError> { match sorted_entries(values) .into_iter() - .find_map(|(_, value)| first_fault(value, None)) + .find_map(|(_, value)| first_fault(value, None, false)) { Some(fault) => Err(DynamoDbError::ValidationException( fault.request_time_text(), diff --git a/crates/engine/src/query_key_values/unreadable.rs b/crates/engine/src/query_key_values/unreadable.rs index 385b56218..6c301697f 100644 --- a/crates/engine/src/query_key_values/unreadable.rs +++ b/crates/engine/src/query_key_values/unreadable.rs @@ -141,9 +141,11 @@ fn null_value() -> Value { /// `ExpressionAttributeValues contains invalid value: for key /// `: a null (`The supplied Item contains a null /// AttributeValue`, with `: is null` when it is the value of an -/// `M` member), no type descriptor, more than one, or an `N` that is not a -/// number. Such an `N` is echoed as written, and an empty one has no colon -/// after the message. No `M` with more than one member was measured; +/// `M` member), no type descriptor, more than one, an `N` that is not a +/// number, or an empty set or a set with a duplicate member beside a second +/// type descriptor (measured 2026-11-24; see `set_fault`). Such an `N` is +/// echoed as written, and an empty one has no colon after the message. No +/// `M` with more than one member was measured; /// 5. an empty name in `ExpressionAttributeNames` (measured 2026-11-19 in /// either member order). `{"#a": ""}` beside `{"X": "1"}`, `{}`, `{"N": /// "1", "S": "x"}`, a null or `{"S": null}` answers that value's text. @@ -203,7 +205,7 @@ pub(super) fn unreadable_value_checks( let mut entries = sorted_entries(values); entries.sort_by_key(|(_, value)| !unreadable(value)); for (key, value) in entries { - if let Some(fault) = first_fault(value, None) { + if let Some(fault) = first_fault(value, None, true) { return Err(DynamoDbError::ValidationException(format!( "ExpressionAttributeValues contains invalid value: {} for key {key}", fault.reason() diff --git a/crates/engine/src/query_key_values/unreadable_tests.rs b/crates/engine/src/query_key_values/unreadable_tests.rs index ec6006678..1249336e4 100644 --- a/crates/engine/src/query_key_values/unreadable_tests.rs +++ b/crates/engine/src/query_key_values/unreadable_tests.rs @@ -58,9 +58,14 @@ fn a_number_fault_in_a_value_with_several_types_is_named_ahead_of_the_several_ty // Measured 2026-11-19, each value beside `:p = {"S": "x"}`: the service // reads every payload, N ahead of NS, NS and M ahead of L, whatever order // the request wrote them in, and answers the more than one datatypes text - // only when no payload has a fault. + // only when no payload has a fault. Measured 2026-11-24 the same way: an + // empty set and a set with a duplicate member are faults too, SS ahead + // of the numbers, NS after its own numbers and ahead of BS and L. let numeric = |text: &str| format!("The parameter cannot be converted to a numeric value: {text}"); + let invalid = |text: &str| format!("One or more parameter values were invalid: {text}"); + let ss_dup = invalid("Input collection [a, a] contains duplicates."); + let ns_dup = "Input collection contains duplicates".to_owned(); for (value, reason) in [ (json!({"N": "bob", "S": "x"}), numeric("bob")), (json!({"N": "1", "S": "x"}), SEVERAL.to_owned()), @@ -89,6 +94,36 @@ fn a_number_fault_in_a_value_with_several_types_is_named_ahead_of_the_several_ty json!({"M": {"k": {"N": "aaa"}}, "L": [{"N": "bbb"}]}), numeric("aaa"), ), + (json!({"SS": ["a", "a"], "N": "1"}), ss_dup.clone()), + (json!({"SS": ["a", "a"], "N": "bob"}), ss_dup.clone()), + (json!({"SS": ["a", "a"], "X": "1"}), ss_dup.clone()), + (json!({"SS": ["a", "a"], "L": [null]}), ss_dup.clone()), + (json!({"S": "x", "L": [{"SS": ["a", "a"]}]}), ss_dup), + (json!({"NS": ["1", "1"], "S": "x"}), ns_dup.clone()), + (json!({"NS": ["1", "1"], "N": "bob"}), numeric("bob")), + ( + json!({"NS": ["1", "1"], "L": [{"N": "bob"}]}), + ns_dup.clone(), + ), + (json!({"NS": ["bob", "bob"], "S": "x"}), numeric("bob")), + (json!({"NS": ["1", "1"], "BS": ["YQ==", "YQ=="]}), ns_dup), + ( + json!({"BS": ["YQ==", "YQ=="], "N": "1"}), + invalid("Input collection [YQ==, YQ==]of type BS contains duplicates."), + ), + (json!({"BS": ["YQ==", "YQ=="], "N": "bob"}), numeric("bob")), + ( + json!({"SS": [], "N": "1"}), + invalid("An string set may not be empty"), + ), + ( + json!({"NS": [], "S": "x"}), + invalid("An number set may not be empty"), + ), + ( + json!({"BS": [], "N": "1"}), + invalid("Binary sets should not be empty"), + ), ] { let body = body_with(json!({":p": {"S": "x"}, ":z": value}), json!({})); assert_eq!( diff --git a/tests/test_query_value_shapes.py b/tests/test_query_value_shapes.py index 9428731ae..639965bd2 100644 --- a/tests/test_query_value_shapes.py +++ b/tests/test_query_value_shapes.py @@ -151,6 +151,9 @@ def test_control_without_a_shape_fault_answers_the_check(self, dynamodb_client, X1 = {"X": "1"} # An S with an unknown descriptor beside it, which the service reads as an S. S_PLUS_X = {"S": "a", "X": "1"} +INVALID = "One or more parameter values were invalid: " +SS_DUP = INVALID + "Input collection [a, a] contains duplicates." +NS_DUP = "Input collection contains duplicates" LIMIT_0_AT = ("Value '0' at 'limit' failed to satisfy constraint: " "Member must have value greater than or equal to 1") SELECT_MSG = ("1 validation error detected: Value 'bad' at 'select' failed to satisfy constraint: " @@ -193,6 +196,37 @@ def test_control_without_a_shape_fault_answers_the_check(self, dynamodb_client, INVALID_VALUE + NUMERIC + "aaa for key :z"), ("N bob then S with Limit 0", {":z": {"N": "bob", "S": "x"}}, {"Limit": 0}, "1 validation error detected: " + LIMIT_0_AT), + # Beside a second type descriptor, an empty set and a set with a duplicate + # member are faults too: SS ahead of the numbers, NS after its own numbers + # and ahead of BS and L (measured 2026-11-24). + ("SS dup then N 1", {":z": {"SS": ["a", "a"], "N": "1"}}, {}, INVALID_VALUE + SS_DUP + " for key :z"), + ("SS dup then N bob", {":z": {"SS": ["a", "a"], "N": "bob"}}, {}, + INVALID_VALUE + SS_DUP + " for key :z"), + ("SS dup then X", {":z": {"SS": ["a", "a"], "X": "1"}}, {}, INVALID_VALUE + SS_DUP + " for key :z"), + ("SS dup then L with null", {":z": {"SS": ["a", "a"], "L": [None]}}, {}, + INVALID_VALUE + SS_DUP + " for key :z"), + ("S then L with SS dup", {":z": {"S": "x", "L": [{"SS": ["a", "a"]}]}}, {}, + INVALID_VALUE + SS_DUP + " for key :z"), + ("NS dup then S", {":z": {"NS": ["1", "1"], "S": "x"}}, {}, INVALID_VALUE + NS_DUP + " for key :z"), + ("NS dup then N bob", {":z": {"NS": ["1", "1"], "N": "bob"}}, {}, + INVALID_VALUE + NUMERIC + "bob for key :z"), + ("NS dup then L with N bob", {":z": {"NS": ["1", "1"], "L": [{"N": "bob"}]}}, {}, + INVALID_VALUE + NS_DUP + " for key :z"), + ("NS bob bob then S", {":z": {"NS": ["bob", "bob"], "S": "x"}}, {}, + INVALID_VALUE + NUMERIC + "bob for key :z"), + ("NS dup then BS dup", {":z": {"NS": ["1", "1"], "BS": ["YQ==", "YQ=="]}}, {}, + INVALID_VALUE + NS_DUP + " for key :z"), + ("BS dup then N 1", {":z": {"BS": ["YQ==", "YQ=="], "N": "1"}}, {}, + INVALID_VALUE + INVALID + "Input collection [YQ==, YQ==]of type BS contains duplicates." + + " for key :z"), + ("BS dup then N bob", {":z": {"BS": ["YQ==", "YQ=="], "N": "bob"}}, {}, + INVALID_VALUE + NUMERIC + "bob for key :z"), + ("empty SS then N 1", {":z": {"SS": [], "N": "1"}}, {}, + INVALID_VALUE + INVALID + "An string set may not be empty for key :z"), + ("empty NS then S", {":z": {"NS": [], "S": "x"}}, {}, + INVALID_VALUE + INVALID + "An number set may not be empty for key :z"), + ("empty BS then N 1", {":z": {"BS": [], "N": "1"}}, {}, + INVALID_VALUE + INVALID + "Binary sets should not be empty for key :z"), # A type descriptor with a null payload reads as no payload (measured # 2026-11-19). ("S null", {":z": {"S": None}}, {}, INVALID_VALUE + EMPTY_AV + " for key :z"), @@ -216,8 +250,10 @@ class TestValuesTheServiceCannotReadAsOneType: beside a known one, or a known one with a null payload) is named with its placeholder, and beside such a value Select, ReturnConsumedCapacity and Limit are reported together, ahead of the parameter mix (measured - 2026-11-11 and 2026-11-19). boto3 cannot send an unknown descriptor or a - null, so the bodies go out as written.""" + 2026-11-11 and 2026-11-19). Beside a second type descriptor, an empty set + and a set with a duplicate member are named ahead of the more than one + datatypes text (measured 2026-11-24). boto3 cannot send an unknown + descriptor or a null, so the bodies go out as written.""" @pytest.mark.parametrize("row,values,extra,expected", UNREADABLE, ids=[r[0] for r in UNREADABLE]) def test_rows(self, dynamodb_client, ss_table, row, values, extra, expected): From 4c08c0985c55c4cd8b600141515134fb0a272e89 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:43:22 +0000 Subject: [PATCH 30/30] docs(upgrade): add the v1.2.0 entry for the Scan value checks The breaking changes of this branch had no entry in the upgrade manual. The new v1.2.0 entry comes after the three v1.2.0 entries of main. It lists: - the number check on the values of ExpressionAttributeValues, with the 1.1.0 answers that it replaces - the order of the checks before the table lookup, and the Limit text - the checks before the IAM decision, which answer ValidationException where 1.1.0 answered AccessDeniedException --- docs/manuals/07-upgrade-manual.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index feeabbd76..bcf563b6e 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -416,6 +416,25 @@ deployment, even when no catalog migration is required. **Who is affected.** PostgreSQL deployments that disable TTL on tables with long readers. No catalog migration or configuration change is required. The other backends are not affected. +### v1.2.0: `Scan` checks its values against the number rules, before the table lookup and the IAM decision + +**What changed** (#562, fixes #545). `Scan` checks the values of `ExpressionAttributeValues` before it looks the table up, as `Query` does from 1.1.0. On every backend: + +- An `N` value that is not a number answers 400 `ValidationException` `The parameter cannot be converted to a numeric value: `, or the overflow, underflow or 38-digit text. The check reads every value of the map, `NS` members and values inside `L` and `M` included. It also reads a value that the `FilterExpression` does not read, and the values of a request with no expression. DynamoDB gives the same texts (measured in us-east-1 on 2026-10-24, 2026-11-23 and 2026-12-03, each request twice). 1.1.0 did not check these values: `a = :n` with `:n` set to `{"N": "bob"}` matched no item and answered 200 with `Count: 0`. The same request on a table that does not exist answered `ResourceNotFoundException`. 1.1.0 answered a value that the `FilterExpression` does not read with `Value provided in ExpressionAttributeValues unused in expressions: keys: {:n}`, and a request with no expression with `ExpressionAttributeValues can only be specified when using expressions`. The [v1.1.0 `Query` entry](#v110-query-checks-its-values-against-the-number-rules-and-the-key-schema) says that Scan inputs are not checked. In 1.2.0, Scan still does not check the numbers in a legacy `ScanFilter` or in `ExclusiveStartKey` (#564). +- These checks run before the table lookup, in the order that DynamoDB uses for a request whose values it can read (measured 2026-11-19 and 2026-11-23): + 1. the `Limit`, `Segment` and `TotalSegments` ranges + 2. `ReturnConsumedCapacity` + 3. the mix of expression and non-expression parameters + 4. `ExpressionAttributeNames` + 5. the numbers + 6. an empty set or a set with a duplicate member + 7. `Select` + + So a Scan with more than one fault can get another `ValidationException` than in 1.1.0. 1.1.0 checked the ranges after the table lookup. `Limit` 0 now answers `1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1`, the text that `Query` and DynamoDB give. 1.1.0 answered the same text with `Value '0' at 'limit'` in place of `Value at 'Limit'`, or `ResourceNotFoundException` on a table that does not exist. The `Segment` and `TotalSegments` texts do not change, and they differ from DynamoDB's (#563). +- The server runs the same checks before the IAM decision, as for `Query`. A request that fails one of the checks gets its answer also when the caller may not Scan the table. That answer is the check's `ValidationException`, or the `SerializationException` of a member of the wrong JSON type. 1.1.0 answered such a caller with `AccessDeniedException`. DynamoDB made the checks ahead of the IAM decision for a role allowed only `dynamodb:DescribeTable` (measured 2026-11-19). + +**Who is affected.** A client, a test or an alarm that matches the 1.1.0 status codes or texts of these Scan requests. A client that relied on 1.1.0 to serve a Scan with a malformed number. No catalog migration or configuration change is required. After a rollback to 1.1.0, these requests get the 1.1.0 answers again. + ### v1.1.0: latency `segments` are summed into time buckets **What changed** (#398). The latency `segments` that `/metrics` and the console's `/console/metrics-data` return come from time buckets per account and operation. 1.0.0 kept one record per request for 24 hours. Each operation's count and means are still exact over the requests that the window covers. Four things change: