diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 56fcf97e5..3f256b5f7 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -67,6 +67,7 @@ pub mod query_key_values; mod read_helpers; mod request_limits; mod scan; +pub mod scan_request; mod search_vectors; mod search_vectors_extended; mod search_vectors_params; @@ -302,8 +303,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/DeleteItem/Scan aggregate; UpdateItem and Query 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 8dd925af3..a205eeddf 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"; @@ -61,8 +61,8 @@ const NULL_VALUE: &str = "The supplied Item contains a null AttributeValue"; 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"]; -const SELECT: &[&str] = &[ +pub(crate) const RETURN_CONSUMED_CAPACITY: &[&str] = &["INDEXES", "TOTAL", "NONE"]; +pub(crate) const SELECT: &[&str] = &[ "SPECIFIC_ATTRIBUTES", "COUNT", "ALL_ATTRIBUTES", @@ -150,10 +150,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 @@ -196,7 +198,7 @@ pub(crate) fn shape_fault_first( { None } - ("Limit", Value::Number(_)) => None, + ("Limit" | "Segment" | "TotalSegments", Value::Number(_)) => None, ("ExpressionAttributeNames", Value::Object(names)) => read( name, Value::Object( @@ -256,7 +258,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) @@ -365,12 +367,12 @@ fn validate_name_keys(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(), @@ -380,7 +382,7 @@ 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 @@ -562,7 +564,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 6c301697f..65e167eb3 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 @@ -164,9 +165,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), @@ -197,7 +206,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 28911a95f..7f57d85f3 100755 --- a/crates/engine/src/scan.rs +++ b/crates/engine/src/scan.rs @@ -41,58 +41,21 @@ 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 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)?; // 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(), @@ -300,7 +263,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( @@ -315,26 +280,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: \ @@ -345,14 +290,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..d72c35973 --- /dev/null +++ b/crates/engine/src/scan_request.rs @@ -0,0 +1,205 @@ +// 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. +//! +//! 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. 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; +//! 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. +//! +//! 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::Deserialize; +use serde_json::{Map, Value}; + +use crate::query_key_values::{ + 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 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, 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::(&readable_for_shape_check(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)?; + + 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: RETURN_CONSUMED_CAPACITY, + clause: crate::EnumClause::Named("returnConsumedCapacity"), + }], + )?; + + 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: 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 [`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 + { + return Err(DynamoDbError::ValidationException( + LIMIT_BELOW_ONE.to_owned(), + )); + } + 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(), + )); + } + 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" + ))); + } + } + Ok(()) +} + +#[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..b998733c2 --- /dev/null +++ b/crates/engine/src/scan_request/tests.rs @@ -0,0 +1,575 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! 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}; + +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]"; +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 { + 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", + ), + // 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", + ), + ( + 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() { + 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}")) + ); + // 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 [ + ( + "Segment", + -1, + "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, + "1 validation error detected: Value '1000000' at 'segment' failed to satisfy constraint: Member must have value less than or equal to 999999", + ), + ( + "TotalSegments", + 0, + "The parameter TotalSegments should be greater than or equal to 1", + ), + ( + "TotalSegments", + 1_000_001, + "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(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(text), + "{field} {value} with {}", + partner.0 + ); + } + // Several range faults: the first in the order Limit, Segment, + // TotalSegments is reported. + 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(&*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( + &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("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 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(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", + 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 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": {}, + "ExpressionAttributeValues": {":n": {"N": "bob"}}, + })) + .as_deref(), + Some(NUMERIC_BOB) + ); +} + +#[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 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}), + // 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!( + 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 is not a range fault here. + assert!(check(&json!({"TableName": "t", "Limit": "0"})).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] +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/crates/server/src/request_helpers.rs b/crates/server/src/request_helpers.rs index b8be4db8e..149d2d87f 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/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 7d8775966..c8df356f6 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -431,6 +431,25 @@ deployment, even when no catalog migration is required. **Who is affected.** A client that pages a parallel Scan of a SQLite deployment across the upgrade. The start keys that 1.1.0 returned follow the old rule. ExtendDB can refuse such a key as a key from another segment. When ExtendDB accepts it, the later pages follow the new rule, so the client can miss items or get items twice. Start such a Scan again after the upgrade. A Scan that pages across a rollback to 1.1.0 can get the same answers. PostgreSQL, MongoDB and Cassandra are not affected. No catalog migration or configuration change is required. +### 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: 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) diff --git a/tests/test_scan_number_values.py b/tests/test_scan_number_values.py new file mode 100644 index 000000000..5e6202d86 --- /dev/null +++ b/tests/test_scan_number_values.py @@ -0,0 +1,568 @@ +# 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, +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, 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. 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 \\ + 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 _is_real_dynamodb, 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]" +) +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"} +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"), + # 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"), + ]) + 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 + (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"}}, + ) + 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, 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, 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, + ): + # 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, + ) == ("ValidationException", expected) + + 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", 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", ONE_ERROR + LIMIT_RANGE) + + 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}}}", + ) + + @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, ReturnConsumedCapacity="NOPE", **extra, + ) == ("ValidationException", RCC_ENUM) + + 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") + + +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 +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"}), + # 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}), +] + + +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 + + +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) +