diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 4d461356e..50fe9dad0 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -15,6 +15,7 @@ use super::ast::{CompareOp, Expr, PathElement}; use super::parser_common; +use super::resolver::{ExpressionMaps, check_begins_with_operand}; use super::tokenizer::Token; use crate::error::DynamoDbError; use crate::types::{ @@ -81,12 +82,10 @@ impl KeyCondition { let pk_name = match self.pk_path.first() { Some(PathElement::Attribute(name)) => { if let Some(ref_name) = name.strip_prefix('#') { - names.get(ref_name).map(String::as_str).ok_or_else(|| { - DynamoDbError::ValidationException(format!( - "Invalid KeyConditionExpression: An expression attribute name used in \ - the document path is not defined; attribute name: #{ref_name}" - )) - })? + names + .get(ref_name) + .map(String::as_str) + .ok_or_else(|| undefined_name_err(ref_name))? } else { name.as_str() } @@ -128,8 +127,6 @@ impl KeyCondition { /// /// The rules the service applies: /// - /// - Each key attribute may carry one condition; a second one is refused - /// as `KeyConditionExpressions must only contain one condition per key`. /// - Every HASH attribute needs an equality condition. Every one without /// it is named, in key-schema order, in `HASH key attributes ... must /// have equality conditions specified in the query`. @@ -171,8 +168,8 @@ impl KeyCondition { /// [`Self::resolve_multipart`] with a check on every clause's value, /// called with the clause's path and value after the structural rules - /// (one condition per key, condition count, HASH coverage, RANGE gap) and - /// before the non-key rule. That is where the service reports a value of + /// (condition count, HASH coverage, RANGE gap) and before the non-key + /// rule. That is where the service reports a value of /// the wrong type (measured 2026-10-21: a wrong-typed value loses to a /// duplicate, a count overflow, a missing HASH attribute and a RANGE gap, /// and wins over a condition on a non-key attribute). @@ -241,22 +238,10 @@ impl KeyCondition { .as_deref() .and_then(|a| hash_attrs.iter().position(|h| *h == a)); - // One condition per key attribute. A second condition on one HASH or - // RANGE attribute, equality or not, is refused before any coverage - // check (measured on the service, 2026-10-21). + // Key-schema order: the first HASH equality becomes `pk_path`, and the + // RANGE equalities keep this order below. hash_eqs.sort_by_key(|(pos, _, _)| *pos); range_eqs.sort_by_key(|(pos, _, _)| *pos); - let duplicated = hash_eqs.windows(2).any(|w| w[0].0 == w[1].0) - || range_eqs.windows(2).any(|w| w[0].0 == w[1].0) - || non_eq_pos.is_some_and(|p| range_eqs.iter().any(|(q, _, _)| *q == p)) - || non_eq_hash_pos.is_some_and(|p| hash_eqs.iter().any(|(q, _, _)| *q == p)); - if duplicated { - return Err(DynamoDbError::ValidationException( - "Invalid KeyConditionExpression: KeyConditionExpressions must only contain \ - one condition per key" - .to_string(), - )); - } // More conditions than key attributes (measured 2026-10-21: the count // is reported ahead of which attribute is missing). @@ -392,7 +377,10 @@ impl KeyCondition { /// authorization when it finds the partition key value for /// `dynamodb:LeadingKeys`, so both read the same clause as the partition /// key. On a multi-attribute key schema `pk_path` then names the first - /// HASH attribute. + /// HASH attribute. The engine parses with + /// [`parse_key_condition_with_maps`], which refuses a second condition on + /// one key attribute before this runs, so a duplicate is reported ahead of + /// `value_check`. /// /// # Errors /// @@ -465,6 +453,87 @@ impl KeyCondition { } } +/// The service's message when a `KeyConditionExpression` carries more than one +/// condition on the same key attribute. Measured 2026-10-24 (us-east-1). +const ONE_CONDITION_PER_KEY_ERR: &str = "Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key"; + +/// The service's message for a `#name` reference that +/// `ExpressionAttributeNames` does not define. +fn undefined_name_err(reference: &str) -> DynamoDbError { + validation_err(&format!( + "Invalid KeyConditionExpression: An expression attribute name used in the document \ + path is not defined; attribute name: #{reference}" + )) +} + +/// Refuse the first `#name` or `:value` reference that `maps` does not define, +/// in the order the expression is written, names and values alike. +/// +/// Measured 2026-11-10 and 2026-11-11 (us-east-1): the service names the +/// first undefined reference in text order (`pk = :q AND #u = :c` with no +/// maps answers `:q`; `#u = :a AND #u = :b` answers `#u`), with or without a +/// second condition on one key attribute, and ahead of an unused name or +/// value. +fn check_references(tokens: &[Token], maps: &ExpressionMaps) -> Result<(), DynamoDbError> { + for token in tokens { + match token { + Token::NameRef(name) if !maps.names.contains_key(name) => { + return Err(undefined_name_err(name)); + } + Token::Placeholder(placeholder) => { + maps.resolve_value_for(placeholder, "KeyConditionExpression")?; + } + _ => {} + } + } + Ok(()) +} + +/// Refuse a `begins_with` operand that is not a string or a binary value. +/// +/// Measured 2026-11-11 (us-east-1): `pk = :a AND begins_with(sk, :n) AND +/// sk = :b` with `:n` a number answers this ahead of the one-condition-per-key +/// message. +fn check_begins_with_operands( + clauses: &[Clause], + maps: &ExpressionMaps, +) -> Result<(), DynamoDbError> { + for clause in clauses { + if let Clause::Supported(RawClause::BeginsWith(_, operand)) = clause { + check_begins_with_operand(operand, maps, "Invalid KeyConditionExpression: ")?; + } + } + Ok(()) +} + +/// Refuse a key condition with more than one condition on one key attribute. +/// +/// Two clauses name the same attribute when their paths resolve to the same +/// name through `names`, whether each is written as a plain name or as a +/// `#name` reference. DynamoDB allows one condition per key attribute, on the +/// partition key and on the sort key alike, whatever the operators are +/// (measured 2026-10-24, and 2026-11-11 for `<>` and `contains`). +fn reject_duplicate_key_attrs( + clauses: &[Clause], + names: &std::collections::HashMap, +) -> Result<(), DynamoDbError> { + let mut seen: Vec<&str> = Vec::with_capacity(clauses.len()); + for clause in clauses { + let Some(PathElement::Attribute(name)) = raw_clause_path(clause).first() else { + continue; + }; + let attr = match name.strip_prefix('#') { + Some(reference) => names.get(reference).map_or(name.as_str(), String::as_str), + None => name.as_str(), + }; + if seen.contains(&attr) { + return Err(validation_err(ONE_CONDITION_PER_KEY_ERR)); + } + seen.push(attr); + } + Ok(()) +} + /// Resolve a path's top-level attribute name, handling `#name` references. fn resolve_path_attr( path: &[PathElement], @@ -473,12 +542,10 @@ fn resolve_path_attr( match path.first() { Some(PathElement::Attribute(name)) => { if let Some(ref_name) = name.strip_prefix('#') { - names.get(ref_name).cloned().ok_or_else(|| { - DynamoDbError::ValidationException(format!( - "Invalid KeyConditionExpression: An expression attribute name used in \ - the document path is not defined; attribute name: #{ref_name}" - )) - }) + names + .get(ref_name) + .cloned() + .ok_or_else(|| undefined_name_err(ref_name)) } else { Ok(name.clone()) } @@ -529,12 +596,61 @@ impl SortKeyCondition { /// Supports multi-part keys: up to 8 AND-ed clauses (4 HASH + 4 RANGE). /// Rejects OR, NOT, and unsupported functions. /// +/// This does not refuse a second condition on one key attribute, which needs +/// the request's `ExpressionAttributeNames` and `ExpressionAttributeValues`. +/// The engine parses a request's key condition with +/// [`parse_key_condition_with_maps`]. Authorization refuses a second condition +/// on one key attribute first ([`has_duplicate_key_condition`]), and parses +/// with this when it finds the partition key value for `dynamodb:LeadingKeys`. +/// /// # Errors /// /// Returns `ValidationException` for syntax errors or unsupported constructs. pub fn parse_key_condition(tokens: &[Token]) -> Result { - let mut clauses = parse_clauses(tokens)?; + classify_clauses(refuse_unsupported_clauses(parse_clauses(tokens)?)?) +} + +/// Whether the key condition in `tokens` names one attribute twice, reading +/// `#name` references through `names`. `false` when the clauses do not parse. +#[must_use] +pub fn has_duplicate_key_condition( + tokens: &[Token], + names: &std::collections::HashMap, +) -> bool { + parse_clauses(tokens).is_ok_and(|clauses| reject_duplicate_key_attrs(&clauses, names).is_err()) +} +/// [`parse_key_condition`] with the request's `ExpressionAttributeNames` and +/// `ExpressionAttributeValues`. +/// +/// After the parser's own checks, and before any clause is read as the +/// partition or the sort key condition, this refuses, in this order: the first +/// undefined `#name` or `:value` reference in the order the expression is +/// written, a `begins_with` operand that is not a string or a binary value, +/// and a key condition with more than one condition on one key attribute, +/// written with plain names or through `#name` references. An operator a key +/// condition does not support (`<>`, `contains`) is refused after these. The +/// engine reads a `Query` key condition through this. +/// +/// # Errors +/// +/// As [`parse_key_condition`], plus `ValidationException` for each of the +/// faults above. A fault in the key condition's shape, such as no equality +/// on the partition key, is the `Err` inside `Ok`: the engine answers it +/// after the table checks, where the service does. +pub fn parse_key_condition_with_maps( + tokens: &[Token], + maps: &ExpressionMaps, +) -> Result, DynamoDbError> { + let clauses = parse_clauses(tokens)?; + check_references(tokens, maps)?; + check_begins_with_operands(&clauses, maps)?; + reject_duplicate_key_attrs(&clauses, &maps.names)?; + Ok(classify_clauses(refuse_unsupported_clauses(clauses)?)) +} + +/// Read the clauses as a partition key condition and sort key conditions. +fn classify_clauses(mut clauses: Vec) -> Result { match clauses.len() { 1 => classify_single(clauses.remove(0)), 2 => classify_pair(clauses.remove(0), clauses.remove(0)), @@ -542,6 +658,18 @@ pub fn parse_key_condition(tokens: &[Token]) -> Result) -> Result, DynamoDbError> { + clauses + .into_iter() + .map(|clause| match clause { + Clause::Supported(raw) => Ok(raw), + Clause::Unsupported(_, message) => Err(validation_err(message)), + }) + .collect() +} + /// The attribute path and single value operand of each clause of a /// `KeyConditionExpression`, and whether the clause compares by equality. /// @@ -551,6 +679,10 @@ pub fn parse_key_condition(tokens: &[Token]) -> Result Result Result, DynamoDbError> { - Ok(parse_clauses(tokens)? + Ok(refuse_unsupported_clauses(parse_clauses(tokens)?)? .into_iter() .filter_map(|clause| match clause { RawClause::Eq(path, value) => Some(KeyClauseOperand { @@ -592,7 +724,7 @@ pub struct KeyClauseOperand { /// Parse a `KeyConditionExpression` token stream into its AND-ed clauses, /// before any of them is read as the partition or the sort key condition. -fn parse_clauses(tokens: &[Token]) -> Result, DynamoDbError> { +fn parse_clauses(tokens: &[Token]) -> Result, DynamoDbError> { parser_common::check_redundant_parens(tokens) .map_err(|body| validation_err(&format!("Invalid KeyConditionExpression: {body}")))?; @@ -639,12 +771,15 @@ fn parse_clauses(tokens: &[Token]) -> Result, DynamoDbError> { } /// The attribute-side path of a raw clause. -fn raw_clause_path(clause: &RawClause) -> &[PathElement] { +fn raw_clause_path(clause: &Clause) -> &[PathElement] { match clause { - RawClause::Eq(path, _) - | RawClause::Compare(path, _, _) - | RawClause::Between(path, _, _) - | RawClause::BeginsWith(path, _) => path, + Clause::Supported( + RawClause::Eq(path, _) + | RawClause::Compare(path, _, _) + | RawClause::Between(path, _, _) + | RawClause::BeginsWith(path, _), + ) + | Clause::Unsupported(path, _) => path, } } @@ -670,6 +805,15 @@ enum RawClause { BeginsWith(Vec, Expr), } +/// A parsed clause. A clause whose operator a key condition does not support +/// keeps its path and the message it is refused with until a second +/// condition on its attribute has been looked for, which the service reports +/// first. +enum Clause { + Supported(RawClause), + Unsupported(Vec, &'static str), +} + enum KeyOperand { Path(Vec), Value(Expr), @@ -780,7 +924,7 @@ fn raw_to_sk(clause: RawClause) -> SortKeyCondition { } } -fn parse_key_clause(tokens: &[Token], pos: &mut usize) -> Result { +fn parse_key_clause(tokens: &[Token], pos: &mut usize) -> Result { if *pos >= tokens.len() { return Err(validation_err( "Invalid KeyConditionExpression: unexpected end of expression", @@ -803,7 +947,7 @@ fn parse_key_clause(tokens: &[Token], pos: &mut usize) -> Result Result { +fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result { if *pos >= tokens.len() { return Err(validation_err( "Invalid KeyConditionExpression: unexpected end of expression", @@ -822,7 +966,28 @@ fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result { + single_attribute_path(attr) + } + _ => None, + }; + let Some(path) = path else { + return Err(validation_err(EXPECTED_COMPARISON_OPERATOR)); + }; + *pos += 6; + return Ok(Clause::Unsupported(path, EXPECTED_COMPARISON_OPERATOR)); } // path op :value | :value op path | path BETWEEN :lo AND :hi @@ -837,27 +1002,28 @@ fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result path, KeyOperand::Value(value) => { - let op = try_comparator(&tokens[*pos]).ok_or_else(|| { - validation_err("Invalid KeyConditionExpression: expected comparison operator") - })?; - // DynamoDB rejects <> in KeyConditionExpression — only =, <, <=, >, >= - // are valid key condition operators. - if op == CompareOp::Ne { - return Err(validation_err( - "Invalid KeyConditionExpression: Unsupported operator on KeyCondition: NE", - )); - } + let op = try_comparator(&tokens[*pos]) + .ok_or_else(|| validation_err(EXPECTED_COMPARISON_OPERATOR))?; *pos += 1; + // `:value <> name` with one top-level attribute is refused once a + // second condition on that attribute has been looked for. Any + // other `<>` clause is refused here, as before. + if op == CompareOp::Ne { + return match parse_key_operand_path(tokens, pos) { + Ok(path) if path.len() == 1 => Ok(Clause::Unsupported(path, NE_UNSUPPORTED)), + _ => Err(validation_err(NE_UNSUPPORTED)), + }; + } let path = parse_key_operand_path(tokens, pos)?; // Key conditions are stored path-first, so reverse the operator when // the source expression puts the value placeholder on the left. let op = reverse_comparator(op); return if op == CompareOp::Eq { - Ok(RawClause::Eq(path, value)) + Ok(Clause::Supported(RawClause::Eq(path, value))) } else { - Ok(RawClause::Compare(path, op, value)) + Ok(Clause::Supported(RawClause::Compare(path, op, value))) }; } }; @@ -868,31 +1034,60 @@ fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result in KeyConditionExpression — only =, <, <=, >, >= - // are valid key condition operators. + let op = try_comparator(&tokens[*pos]) + .ok_or_else(|| validation_err(EXPECTED_COMPARISON_OPERATOR))?; + *pos += 1; + + // `name <> :value` with one top-level attribute is refused once a second + // condition on that attribute has been looked for. Any other `<>` clause + // is refused here, as before. if op == CompareOp::Ne { - return Err(validation_err( - "Invalid KeyConditionExpression: Unsupported operator on KeyCondition: NE", - )); + return match tokens.get(*pos) { + Some(Token::Placeholder(_)) if path.len() == 1 => { + *pos += 1; + Ok(Clause::Unsupported(path, NE_UNSUPPORTED)) + } + _ => Err(validation_err(NE_UNSUPPORTED)), + }; } - *pos += 1; let value = parse_key_value(tokens, pos)?; if op == CompareOp::Eq { - Ok(RawClause::Eq(path, value)) + Ok(Clause::Supported(RawClause::Eq(path, value))) } else { - Ok(RawClause::Compare(path, op, value)) + Ok(Clause::Supported(RawClause::Compare(path, op, value))) } } +/// The path of a `#name` or plain attribute token, or `None` for any other +/// token. +fn single_attribute_path(token: &Token) -> Option> { + match token { + Token::Ident(name) => Some(vec![PathElement::Attribute(name.clone())]), + Token::NameRef(name) => Some(vec![PathElement::Attribute(format!("#{name}"))]), + _ => None, + } +} + +/// A key condition allows `=`, `<`, `<=`, `>` and `>=`, and refuses `<>` with +/// this. A second condition on the same attribute is reported first +/// (measured 2026-11-11: `pk = :a AND pk <> :b` answers the +/// one-condition-per-key message). +const NE_UNSUPPORTED: &str = + "Invalid KeyConditionExpression: Unsupported operator on KeyCondition: NE"; + +/// The refusal of a clause with no comparison operator, and of a `contains` +/// clause. A second condition on the same attribute is reported ahead of +/// `contains` (measured 2026-11-11: `pk = :a AND contains(pk, :b)` answers +/// the one-condition-per-key message). +const EXPECTED_COMPARISON_OPERATOR: &str = + "Invalid KeyConditionExpression: expected comparison operator"; + fn parse_key_operand(tokens: &[Token], pos: &mut usize) -> Result { if *pos >= tokens.len() { return Err(validation_err( @@ -1001,6 +1196,7 @@ fn validation_err(msg: &str) -> DynamoDbError { mod tests { use super::*; use crate::expression::tokenize; + use crate::types::AttributeValue; use std::collections::HashMap; #[test] @@ -1635,41 +1831,6 @@ mod tests { assert!(classify_two_hash("h1 = :x AND h2 = :y AND r > :z").is_ok()); } - #[test] - fn a_second_condition_on_one_key_attribute_is_refused() { - const WANT: &str = "Invalid KeyConditionExpression: KeyConditionExpressions must only \ - contain one condition per key"; - for expr in [ - "h = :x AND h = :y", - "h = :x AND h = :y AND a = :z", - "h = :x AND a = :y AND a = :z", - "h = :h AND a = :a AND a > :x", - "h = :h AND a > :x AND a = :a", - "h = :h AND a = :a AND b = :n AND b > :lo", - "h = :h AND h > :x", - "h = :h AND h = :y AND c = :c", - "a = :a AND a = :y", - ] { - let err = classify_one_hash(expr).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if msg == WANT), - "expr {expr}: got {err:?}" - ); - } - for expr in [ - "h1 = :x AND h1 = :y AND h2 = :z", - "h1 = :x AND h1 = :y", - "h1 = :x AND h2 = :n AND r = :r AND r > :y", - "h1 = :x AND r = :r AND r = :y", - ] { - let err = classify_two_hash(expr).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if msg == WANT), - "expr {expr}: got {err:?}" - ); - } - } - #[test] fn a_condition_on_a_non_key_attribute_names_the_first_uncovered_range_attribute() { for (expr, missing) in [ @@ -1905,4 +2066,375 @@ mod tests { kc.resolve_key_schema(&schema, &HashMap::new()).unwrap(); assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); } + + const TYPE_ERR: &str = "One or more parameter values were invalid: Condition parameter \ + type does not match schema type"; + + /// No `ExpressionAttributeValues`. + fn no_values() -> HashMap { + HashMap::new() + } + + /// `ExpressionAttributeValues` that define every placeholder of `expr`, + /// keyed without the leading `:`. + fn values_of(expr: &str) -> HashMap { + tokenize(expr) + .unwrap() + .into_iter() + .filter_map(|token| match token { + Token::Placeholder(name) => Some((name, AttributeValue::S("v".to_owned()))), + _ => None, + }) + .collect() + } + + /// `ExpressionAttributeNames` from `(reference, attribute)` pairs, keyed + /// without the leading `#`. + fn names_of(pairs: &[(&str, &str)]) -> HashMap { + pairs + .iter() + .map(|(reference, attr)| ((*reference).to_owned(), (*attr).to_owned())) + .collect() + } + + /// Parse `expr` as the engine parses a request's key condition. + fn parse_with( + expr: &str, + names: &HashMap, + values: &HashMap, + ) -> Result { + let tokens = tokenize(expr).unwrap(); + parse_key_condition_with_maps(&tokens, &ExpressionMaps::new(names.clone(), values.clone()))? + } + + /// [`parse_with`] with every placeholder of `expr` defined. + fn parse_request( + expr: &str, + names: &HashMap, + ) -> Result { + parse_with(expr, names, &values_of(expr)) + } + + fn undefined_value(value: &str) -> String { + format!( + "Invalid KeyConditionExpression: An expression attribute value used in \ + expression is not defined; attribute value: :{value}" + ) + } + fn assert_refused( + result: Result, + want: &str, + expr: &str, + ) { + match result { + Err(DynamoDbError::ValidationException(msg)) => assert_eq!(msg, want, "expr {expr}"), + other => panic!("expr {expr}: got {other:?}"), + } + } + + /// A second condition on one key attribute, on the partition key or the + /// sort key, written with plain names or through `#name` references and + /// whatever the operators, answers the one-condition-per-key message; a + /// nested path and redundant parentheses keep their own (measured + /// 2026-10-24, us-east-1). The multi-attribute shapes are not measured. + #[test] + fn duplicate_condition_on_one_key_attribute_rejected() { + const REDUNDANT_PARENS: &str = + "Invalid KeyConditionExpression: The expression has redundant parentheses;"; + let dup = ONE_CONDITION_PER_KEY_ERR; + // The expression, its `#name` definitions and the answer. + type Case<'a> = (&'a str, &'a [(&'a str, &'a str)], &'a str); + let cases: &[Case<'_>] = &[ + ("pk = :a AND pk = :b", &[], dup), + ("pk = :a AND pk = :a", &[], dup), + ("pk = :a AND pk = :b AND sk = :c", &[], dup), + ("pk = :a AND pk > :b", &[], dup), + ("pk > :b AND pk = :a", &[], dup), + (":a = pk AND pk = :b", &[], dup), + ("(pk = :a) AND (pk = :b)", &[], dup), + ("pk = :a AND sk = :b AND sk = :c", &[], dup), + ("pk = :a AND sk = :b AND sk = :b", &[], dup), + ("pk = :a AND sk BETWEEN :b AND :c AND sk = :b", &[], dup), + ( + "pk = :a AND sk BETWEEN :b AND :c AND begins_with(sk, :b)", + &[], + dup, + ), + ("pk = :a AND begins_with(sk, :b) AND sk = :c", &[], dup), + ("pk = :a AND sk > :b AND sk < :c", &[], dup), + ( + "pk = :a AND begins_with(sk, :b) AND begins_with(sk, :c)", + &[], + dup, + ), + ("pk = :a AND pk = :b AND sk = :b AND sk = :c", &[], dup), + ("sk = :b AND sk = :c", &[], dup), + // `#p` and `pk` name one attribute once `#p` is resolved, on a + // single-attribute key schema and a multi-attribute one alike. + ("#p = :a AND pk = :b", &[("p", "pk")], dup), + ("#hh = :x AND h = :y AND a = :z", &[("hh", "h")], dup), + ("#p = :a AND #q = :b", &[("p", "pk"), ("q", "pk")], dup), + ("pk = :a AND #s = :b AND sk = :c", &[("s", "sk")], dup), + // The shapes of a multi-attribute key schema: `h` with the RANGE + // attributes `a, b, c, d`, and `h1, h2` with `r`. The check reads + // attribute names, so it needs no key schema. + ("h = :x AND h = :y", &[], dup), + ("h = :x AND h = :y AND a = :z", &[], dup), + ("h = :x AND a = :y AND a = :z", &[], dup), + ("h = :h AND a = :a AND a > :x", &[], dup), + ("h = :h AND a > :x AND a = :a", &[], dup), + ("h = :h AND a = :a AND b = :n AND b > :lo", &[], dup), + ("h = :h AND h > :x", &[], dup), + ("h = :h AND h = :y AND c = :c", &[], dup), + ("a = :a AND a = :y", &[], dup), + ("h1 = :x AND h1 = :y AND h2 = :z", &[], dup), + ("h1 = :x AND h1 = :y", &[], dup), + ("h1 = :x AND h2 = :n AND r = :r AND r > :y", &[], dup), + ("h1 = :x AND r = :r AND r = :y", &[], dup), + ("pk = :a AND pk.foo = :b", &[], NESTED_KEY_ERR), + ("((pk = :a)) AND (pk = :b)", &[], REDUNDANT_PARENS), + ]; + for (expr, names, want) in cases { + assert_refused(parse_request(expr, &names_of(names)), want, expr); + } + } + + /// The first undefined reference in the order the expression is written is + /// reported, a `#name` or a `:value`, with or without a duplicate. + /// Measured 2026-10-24 for `#u = :a AND #u = :b`, 2026-10-31 for the + /// duplicates with `#u` the only undefined reference, and 2026-11-11 for + /// the rest (us-east-1, two sends each). The multi-attribute form is not + /// measured. + #[test] + fn first_undefined_reference_in_text_order_is_reported() { + let none = HashMap::new(); + for (expr, values, want) in [ + // Every placeholder defined, `#u` the only undefined reference. + ( + "#u = :a AND #u = :b", + values_of("#u = :a AND #u = :b"), + "#u", + ), + ( + "#u = :a AND #u > :b", + values_of("#u = :a AND #u > :b"), + "#u", + ), + ( + "#u = :a AND sk = :b AND sk = :c", + values_of("#u = :a AND sk = :b AND sk = :c"), + "#u", + ), + ( + "pk = :a AND pk = :b AND #u = :c", + values_of("pk = :a AND pk = :b AND #u = :c"), + "#u", + ), + ( + "h = :a AND h = :b AND #u = :c", + values_of("h = :a AND h = :b AND #u = :c"), + "#u", + ), + // No maps, or only some values: the first in text order. + ("#u = :a AND #u = :b", no_values(), "#u"), + ("pk = :q AND #u = :c", no_values(), ":q"), + ("sk = :b AND pk = :a", no_values(), ":b"), + ("pk = :b AND pk = :a", no_values(), ":b"), + ("pk = :a AND pk = :b AND #u = :c", no_values(), ":a"), + ("pk = :q AND pk = :b AND #u = :c", values_of(":b :c"), ":q"), + ("pk = :a AND pk = :missing", values_of(":a"), ":missing"), + ("#k = :v", no_values(), "#k"), + ("pk = :v", no_values(), ":v"), + ] { + let want = match want.strip_prefix('#') { + Some(name) => format!( + "Invalid KeyConditionExpression: An expression attribute name used in the \ + document path is not defined; attribute name: #{name}" + ), + None => undefined_value(&want[1..]), + }; + assert_refused(parse_with(expr, &none, &values), &want, expr); + } + } + /// The duplicate is reported by the parse, so it comes ahead of the key + /// value type check that `resolve_key_schema_with` runs and of the engine's + /// unused-value check, whichever way it is spelled (measured 2026-10-31: + /// `pk = :a AND pk = :n`, `#p = :a AND pk = :n` and + /// `pk = :a AND #s = :b AND sk = :n` with `:n` a number on an S key, and + /// `pk = :a AND pk = :b` with an unused `:z`, answer the + /// one-condition-per-key message; `pk = :n` alone answers the type). + #[test] + fn duplicate_reported_ahead_of_type_and_unused_value_checks() { + let schema = [key("pk", KeyType::Hash), key("sk", KeyType::Range)]; + let names = names_of(&[("p", "pk"), ("s", "sk")]); + let values: HashMap = [ + ("a", AttributeValue::S("alice".to_owned())), + ("b", AttributeValue::S("bob".to_owned())), + ("n", AttributeValue::N("1".to_owned())), + ("z", AttributeValue::S("zed".to_owned())), + ] + .into_iter() + .map(|(k, v)| (k.to_owned(), v)) + .collect(); + for expr in [ + "pk = :a AND pk = :n", + "#p = :a AND pk = :n", + "pk = :a AND #s = :b AND sk = :n", + "pk = :a AND pk = :b", + ] { + assert_refused( + parse_with(expr, &names, &values), + ONE_CONDITION_PER_KEY_ERR, + expr, + ); + } + let mut kc = parse_with("pk = :n", &names, &values).unwrap(); + assert_refused( + kc.resolve_key_schema_with(&schema, &names, |_, value| match value { + Expr::Placeholder(name) if name == "n" => Err(validation_err(TYPE_ERR)), + _ => Ok(()), + }), + TYPE_ERR, + "pk = :n", + ); + } + + /// `<>` and `contains` are refused after the duplicate check, and a + /// `begins_with` operand that is not a string or a binary value before it + /// (measured 2026-11-11, us-east-1, two sends each). Without a duplicate, + /// `<>` and `contains` keep the messages they had. + #[test] + fn operators_and_operands_around_the_duplicate_check() { + const BEGINS_WITH_N: &str = "Invalid KeyConditionExpression: Incorrect operand type \ + for operator or function; operator or function: \ + begins_with, operand type: N"; + let mut values = values_of(":a :b :c"); + values.insert("n".to_owned(), AttributeValue::N("1".to_owned())); + let none = HashMap::new(); + for (expr, want) in [ + ("pk = :a AND pk <> :b", ONE_CONDITION_PER_KEY_ERR), + ("pk = :a AND contains(pk, :b)", ONE_CONDITION_PER_KEY_ERR), + ("pk = :a AND begins_with(sk, :n) AND sk = :b", BEGINS_WITH_N), + ("pk = :a AND sk <> :b", NE_UNSUPPORTED), + ("pk = :a AND :b <> sk", NE_UNSUPPORTED), + ("pk = :a AND contains(sk, :b)", EXPECTED_COMPARISON_OPERATOR), + ] { + assert_refused(parse_with(expr, &none, &values), want, expr); + } + // The map-less parse authorization reads refuses them too. + for expr in ["pk = :a AND pk <> :b", "pk = :a AND contains(pk, :b)"] { + let tokens = tokenize(expr).unwrap(); + assert!(parse_key_condition(&tokens).is_err(), "expr {expr}"); + assert!( + key_condition_clause_operands(&tokens).is_err(), + "expr {expr}" + ); + } + } + + /// Only `name <> :value`, `:value <> name` and `contains(name, :value)`, + /// with one top-level attribute, wait for the duplicate check. Any other + /// `<>` or `contains` clause is refused where the parser meets it, with + /// the message it gave before, ahead of a duplicate. The service's text + /// for these shapes differs and is not changed here (measured 2026-11-11 + /// for `pk = :a AND contains(sk)`). + #[test] + fn other_ne_and_contains_clauses_keep_their_refusal() { + let values = values_of(":a :b :c"); + let none = HashMap::new(); + for (expr, want) in [ + ("pk = :a AND contains(sk)", EXPECTED_COMPARISON_OPERATOR), + ("pk = :a AND contains(pk)", EXPECTED_COMPARISON_OPERATOR), + ( + "pk = :a AND contains(sk, :b, :c)", + EXPECTED_COMPARISON_OPERATOR, + ), + ("pk = :a AND contains(:b, sk)", EXPECTED_COMPARISON_OPERATOR), + ("pk = :a AND contains(sk, sk)", EXPECTED_COMPARISON_OPERATOR), + ( + "pk = :a AND contains(pk.x, :b)", + EXPECTED_COMPARISON_OPERATOR, + ), + ("pk = :a AND CONTAINS(pk, :b)", EXPECTED_COMPARISON_OPERATOR), + ("pk = :a AND pk <> pk", NE_UNSUPPORTED), + ("pk = :a AND pk.x <> :b", NE_UNSUPPORTED), + ("pk = :a AND :b <> pk.x", NE_UNSUPPORTED), + ("pk = :a AND :b <> :c", NE_UNSUPPORTED), + ] { + assert_refused(parse_with(expr, &none, &values), want, expr); + } + // A `<>` with nothing after it. + let tokens = tokenize("pk = :a AND pk <>").unwrap(); + assert_refused( + parse_key_condition_with_maps(&tokens, &ExpressionMaps::new(none, values)), + NE_UNSUPPORTED, + "pk = :a AND pk <>", + ); + } + + /// A key condition whose only fault is its shape passes the checks, and + /// its refusal comes inside `Ok`, for the engine to answer after the + /// table checks. + #[test] + fn the_shape_is_refused_after_the_checks() { + for (expr, want) in [ + ("pk > :a", "partition key condition must use equality (=)"), + ( + "pk > :a AND sk > :b", + "one condition must be an equality on the partition key", + ), + ( + "pk = :a AND sk > :b AND zz < :c", + "at most one non-equality condition is allowed", + ), + ] { + let tokens = tokenize(expr).unwrap(); + let maps = ExpressionMaps::new(HashMap::new(), values_of(expr)); + let shape = parse_key_condition_with_maps(&tokens, &maps) + .unwrap_or_else(|err| panic!("expr {expr} should pass the checks: {err:?}")); + assert_refused( + shape, + &format!("Invalid KeyConditionExpression: {want}"), + expr, + ); + } + } + + #[test] + fn distinct_key_attributes_accepted_after_duplicate_check() { + // One condition per key attribute passes the check and resolves under + // the key schema the engine reads it with: the check is per attribute + // name, not per clause count. + let names = names_of(&[("p", "pk"), ("s", "sk")]); + let pk_sk = [key("pk", KeyType::Hash), key("sk", KeyType::Range)]; + let two_hash = [ + key("pk1", KeyType::Hash), + key("pk2", KeyType::Hash), + key("sk", KeyType::Range), + ]; + let two_by_two = [ + key("pk1", KeyType::Hash), + key("pk2", KeyType::Hash), + key("sk1", KeyType::Range), + key("sk2", KeyType::Range), + ]; + for (schema, expr) in [ + (&pk_sk[..], "pk = :a"), + (&pk_sk[..], "pk = :a AND sk = :b"), + (&pk_sk[..], "sk = :b AND pk = :a"), + (&pk_sk[..], "pk = :a AND sk BETWEEN :b AND :c"), + (&pk_sk[..], "pk = :a AND begins_with(sk, :b)"), + (&pk_sk[..], "#p = :a AND #s = :b"), + (&two_hash[..], "pk1 = :a AND pk2 = :b AND sk = :c"), + ( + &two_by_two[..], + "pk1 = :a AND pk2 = :b AND sk1 = :c AND sk2 = :d", + ), + ] { + let mut kc = parse_request(expr, &names) + .unwrap_or_else(|err| panic!("expr {expr} should parse: {err:?}")); + kc.resolve_key_schema(schema, &names) + .unwrap_or_else(|err| panic!("expr {expr} should resolve: {err:?}")); + } + } } diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index 629a03617..0302e1bad 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -29,8 +29,8 @@ mod update_parser; pub use ast::{ArithOp, CompareOp, Expr, PathElement, UpdateAction, removes_only}; pub use evaluator::evaluate_condition; pub use key_condition::{ - KeyClauseOperand, KeyCondition, SortKeyCondition, key_condition_clause_operands, - parse_key_condition, + KeyClauseOperand, KeyCondition, SortKeyCondition, has_duplicate_key_condition, + key_condition_clause_operands, parse_key_condition, parse_key_condition_with_maps, }; pub use kind::ExpressionKind; pub use parser::{parse_condition, parse_condition_with_depth_limit}; diff --git a/crates/core/src/expression/resolver.rs b/crates/core/src/expression/resolver.rs index c9fdf29f0..feab76519 100755 --- a/crates/core/src/expression/resolver.rs +++ b/crates/core/src/expression/resolver.rs @@ -507,18 +507,8 @@ pub fn validate_begins_with_operands( maps: &ExpressionMaps, ) -> Result<(), DynamoDbError> { match expr { - Expr::Function { name, args } if name == "begins_with" => { - if args.len() == 2 - && let Expr::Placeholder(ref placeholder) = args[1] - && let Some(val) = maps.values.get(placeholder) - && !matches!(val, AttributeValue::S(_) | AttributeValue::B(_)) - { - let type_code = attribute_type_code(val); - return Err(DynamoDbError::ValidationException(format!( - "Incorrect operand type for operator or function; operator or function: begins_with, operand type: {type_code}" - ))); - } - Ok(()) + Expr::Function { name, args } if name == "begins_with" && args.len() == 2 => { + check_begins_with_operand(&args[1], maps, "") } Expr::And(left, right) | Expr::Or(left, right) => { validate_begins_with_operands(left, maps)?; @@ -529,6 +519,25 @@ pub fn validate_begins_with_operands( } } +/// Refuse a `begins_with` operand that is a `:value` other than a string or a +/// binary value, with `prefix` ahead of the message. +pub(crate) fn check_begins_with_operand( + operand: &Expr, + maps: &ExpressionMaps, + prefix: &str, +) -> Result<(), DynamoDbError> { + if let Expr::Placeholder(placeholder) = operand + && let Some(val) = maps.values.get(placeholder) + && !matches!(val, AttributeValue::S(_) | AttributeValue::B(_)) + { + let type_code = attribute_type_code(val); + return Err(DynamoDbError::ValidationException(format!( + "{prefix}Incorrect operand type for operator or function; operator or function: begins_with, operand type: {type_code}" + ))); + } + Ok(()) +} + /// Return the DynamoDB type code for an AttributeValue (S, N, B, BOOL, NULL, /// L, M, SS, NS, BS). Used in operand-type validation messages. pub(crate) fn attribute_type_code(val: &AttributeValue) -> &'static str { diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index 22f51019c..03b393ebb 100755 --- a/crates/engine/src/expression_helpers.rs +++ b/crates/engine/src/expression_helpers.rs @@ -8,8 +8,9 @@ use std::collections::HashMap; use extenddb_core::error::DynamoDbError; use extenddb_core::expression::{ Expr, ExpressionKind, ExpressionMaps, KeyCondition, PathElement, Token, UpdateAction, - parse_condition_with_depth_limit, parse_key_condition, parse_projection, parse_update_from, - tokenize_for, tokenize_with_limit, validate_no_reserved_words, validate_ordering_operand_types, + parse_condition_with_depth_limit, parse_key_condition_with_maps, parse_projection, + parse_update_from, tokenize_for, tokenize_with_limit, validate_no_reserved_words, + validate_ordering_operand_types, }; use extenddb_core::limits::LimitsConfig; use extenddb_core::types::{AttributeValue, ConditionalOperator, ExpectedAttributeValue}; @@ -237,16 +238,24 @@ pub fn parse_projection_expr( /// Size-check, tokenize, reserved-word check, and parse a `KeyConditionExpression`. /// +/// `maps` holds the request's `ExpressionAttributeNames` and +/// `ExpressionAttributeValues`. The parse reads them to refuse an undefined +/// reference, a `begins_with` operand of the wrong type and a second +/// condition on one key attribute. +/// /// Errors carry the `KeyConditionExpression` prefix, matching Amazon `DynamoDB`. /// /// # Errors /// /// Returns `DynamoDbError::ValidationException` for over-size, syntax, or -/// reserved-word errors. +/// reserved-word errors, and for the faults above. A fault in the key +/// condition's shape is the `Err` inside `Ok`, as +/// [`parse_key_condition_with_maps`] returns it. pub fn parse_key_condition_expr( expr: &str, + maps: &ExpressionMaps, limits: &LimitsConfig, -) -> Result { +) -> Result, DynamoDbError> { check_expression_size(expr, ExpressionKind::KeyCondition, limits)?; tokenize_for( expr, @@ -257,7 +266,7 @@ pub fn parse_key_condition_expr( if limits.enforce_reserved_keywords { validate_no_reserved_words(&tokens)?; } - parse_key_condition(&tokens) + parse_key_condition_with_maps(&tokens, maps) }) .map_err(|e| prefix_expression_error(e, ExpressionKind::KeyCondition)) } @@ -408,6 +417,39 @@ mod tests { ); } + /// `parse_key_condition_expr` reads the request's `ExpressionAttributeNames` + /// and `ExpressionAttributeValues`, keyed with `#` and `:` as a request + /// carries them: a duplicate written through `#p` and an undefined `#u` + /// each answer the service's message. The core tests cover the other + /// rows. + #[test] + fn key_condition_parse_reads_the_request_maps() { + let names: HashMap = [("#p".to_owned(), "pk".to_owned())].into(); + let values: HashMap = [":a", ":b", ":c"] + .into_iter() + .map(|k| (k.to_owned(), AttributeValue::S("v".to_owned()))) + .collect(); + let maps = build_expression_maps(Some(&names), Some(&values)); + for (expr, want) in [ + ( + "#p = :a AND pk = :b", + "Invalid KeyConditionExpression: KeyConditionExpressions must only contain \ + one condition per key", + ), + ( + "pk = :a AND pk = :b AND #u = :c", + "Invalid KeyConditionExpression: An expression attribute name used in the \ + document path is not defined; attribute name: #u", + ), + ] { + let got = parse_key_condition_expr(expr, &maps, &LimitsConfig::default()); + assert!( + matches!(&got, Err(DynamoDbError::ValidationException(msg)) if msg == want), + "expr {expr}: got {got:?}" + ); + } + } + /// Size and token limits raised so only the depth limit refuses the /// expressions below. fn raised() -> LimitsConfig { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4fe89b969..07e9fcb96 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -94,7 +94,7 @@ pub use import_export::{handle_export_table, handle_import_table}; pub use item_authorizer::{ItemAccess, ItemAuthorization, ItemAuthorizer}; pub use list_tables::handle_list_tables; pub use put_item::handle_put_item; -pub use query::handle_query; +pub use query::{handle_query, refuse_duplicate_key_condition}; pub use request_limits::check_request_item_counts; pub use scan::handle_scan; pub use search_vectors::handle_search_vectors; diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index ce1cb2cdc..a0ca9fb76 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -19,7 +19,7 @@ use extenddb_storage::error::StorageError; use crate::OperationContext; use crate::capacity_helpers; use crate::create_table::storage_err_to_dynamo; -use crate::expression_helpers::{build_expression_maps, parse_optional_filter}; +use crate::expression_helpers::parse_optional_filter; use crate::index_helpers::{ VectorIndexReadRefusal, classify_unresolved_index_read, combined_lek_key_schema, validate_query_select_index_support, @@ -33,6 +33,11 @@ use crate::start_key::{ }; use crate::{DispatchMetrics, DispatchResult}; +mod request_checks; + +use request_checks::CheckedRequest; +pub use request_checks::refuse_duplicate_key_condition; + /// Handle a `Query` request. /// /// Parses `KeyConditionExpression`, queries the storage layer, applies @@ -47,10 +52,12 @@ pub async fn handle_query( body: Value, ctx: &OperationContext, ) -> Result { - // 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)?; + let CheckedRequest { + input, + maps, + filter_expression, + key_condition_expression, + } = request_checks::check_request(body, &ctx.limits)?; // P118: Fetch key_info first so we can use table_id for index lookup. let key_info = ctx @@ -114,8 +121,6 @@ pub async fn handle_query( validate_query_select_index_support(input.select, index_info.as_ref())?; } - // 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. let query_key_info = if let Some(ref idx) = index_info { @@ -136,54 +141,12 @@ pub async fn handle_query( key_info.clone() }; - // The legacy versus expression mutual exclusivity check runs at request - // time in validate_query_request_body. - let has_cond_op = input.conditional_operator.is_some(); - - // 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())?; - - // Build expression maps from request (used for expression-based parameters) - let maps = build_expression_maps( - input.expression_attribute_names.as_ref(), - input.expression_attribute_values.as_ref(), - ); - - // Reject EAN/EAV supplied with no expression that references them. Legacy - // KeyConditions does not count as an expression. Query emits no values suffix. - let has_kce = input - .key_condition_expression - .as_ref() - .is_some_and(|s| !s.is_empty()); - let has_filter_expr = input - .filter_expression - .as_ref() - .is_some_and(|s| !s.is_empty()); - let has_proj_expr = input - .projection_expression - .as_ref() - .is_some_and(|s| !s.is_empty()); - extenddb_core::expression::validate_expression_param_usage( - input.expression_attribute_names.as_ref(), - has_kce || has_filter_expr || has_proj_expr, - input.expression_attribute_values.as_ref(), - has_kce || has_filter_expr, - &[], - )?; - - // ConditionalOperator requires a QueryFilter with two or more conditions. - extenddb_core::validation::validate_conditional_operator_usage( - has_cond_op, - input.query_filter.as_ref().map_or(0, HashMap::len), - )?; - // Parse KeyConditionExpression or desugar legacy KeyConditions - let (mut key_condition, legacy_kc_maps) = if let Some(kce_str) = - input.key_condition_expression.as_deref() - { - let parsed = crate::expression_helpers::parse_key_condition_expr(kce_str, &ctx.limits)?; - (parsed, None) + let (mut key_condition, legacy_kc_maps) = if let Some(parsed) = key_condition_expression { + // Parsed and checked above. A fault in its shape answers here, after + // the table checks (measured 2026-11-23: `pk > :a` on a table that does + // not exist answers ResourceNotFoundException). + (parsed?, None) } else if let Some(ref kc) = input.key_conditions { let key_schema_pairs: Vec<(String, bool)> = query_key_info .key_schema @@ -280,7 +243,10 @@ pub async fn handle_query( } }, )?; - refuse_begins_with_on_number(&key_condition, effective_maps)?; + // The parse checked a KeyConditionExpression's begins_with value. + if legacy_kc_maps.is_some() { + 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. @@ -293,29 +259,22 @@ pub async fn handle_query( } } - // Parse FilterExpression or desugar legacy QueryFilter - let (filter, filter_maps) = if let Some(ref qf) = input.query_filter { - if qf.is_empty() { - ( - parse_optional_filter(input.filter_expression.as_deref(), &ctx.limits)?, - None, - ) - } else { + // Desugar a legacy QueryFilter. A FilterExpression was parsed and checked + // above; the parameter mixing check refuses a request with both. + let (filter, filter_maps) = match input.query_filter { + Some(ref qf) if !qf.is_empty() => { let cond_op = input.conditional_operator.unwrap_or_default(); let (expr, fmaps) = desugar_filter(qf, cond_op)?; (Some(expr), Some(fmaps)) } - } else { - ( - parse_optional_filter(input.filter_expression.as_deref(), &ctx.limits)?, - None, - ) + _ => (filter_expression, None), }; - // Validate #name references in filter are defined in ExpressionAttributeNames - if let Some(ref filter_expr) = filter { + // A desugared QueryFilter's paths: a legacy attribute name that starts with + // `#` reads as a reference. A FilterExpression's were checked when parsed. + if let (Some(f), Some(_)) = (&filter, &filter_maps) { let names = input.expression_attribute_names.as_ref(); - validate_name_refs_in_expr(filter_expr, names, ExpressionKind::Filter)?; + validate_name_refs_in_expr(f, names, ExpressionKind::Filter)?; } // Parse ProjectionExpression or desugar legacy AttributesToGet @@ -436,14 +395,12 @@ pub async fn handle_query( ExpressionMaps::new(names, values) }; - // Validate begins_with operand types upfront (before any rows are read). - if let Some(ref f) = filter { - extenddb_core::expression::validate_begins_with_operands(f, &combined_maps).map_err( - |e| crate::expression_helpers::prefix_expression_error(e, ExpressionKind::Filter), - )?; - extenddb_core::expression::validate_ordering_operand_types(f, &combined_maps).map_err( - |e| crate::expression_helpers::prefix_expression_error(e, ExpressionKind::Filter), - )?; + // A desugared QueryFilter's operand types, against the values it adds. A + // FilterExpression was checked against the request's values when parsed. + if let Some(f) = &filter + && filter_maps.is_some() + { + check_filter_operand_types(f, &combined_maps)?; } // A key condition value whose type is not the key attribute's type is @@ -651,7 +608,10 @@ pub(crate) fn check_key_value_type( /// 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. +/// existing checks report it. A `KeyConditionExpression` gets this refusal +/// when it is parsed, before the table is read (see +/// `extenddb_core::expression::parse_key_condition_with_maps`), so +/// `handle_query` calls this for a legacy `KeyConditions` request only. fn refuse_begins_with_on_number( key_condition: &extenddb_core::expression::KeyCondition, maps: &ExpressionMaps, @@ -671,6 +631,81 @@ fn refuse_begins_with_on_number( }) } +/// The checks of a request's parameters that follow the raw-body checks of +/// `query_key_values::validate_query_request_body`, in this order: an empty +/// `KeyConditionExpression`, `ExpressionAttributeNames` and +/// `ExpressionAttributeValues` with no expression that uses them, and +/// `ConditionalOperator` without a `QueryFilter` of two or more conditions. +/// +/// `check_request` runs these after the `Limit`, enum, parameter mix, names +/// and number checks and ahead of every other check (measured 2026-11-11). +fn check_request_parameters(input: &QueryInput) -> Result<(), DynamoDbError> { + // 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())?; + + // Reject EAN/EAV supplied with no expression that references them. Legacy + // KeyConditions does not count as an expression. Query emits no values suffix. + let has_kce = input + .key_condition_expression + .as_ref() + .is_some_and(|s| !s.is_empty()); + let has_filter_expr = input + .filter_expression + .as_ref() + .is_some_and(|s| !s.is_empty()); + let has_proj_expr = input + .projection_expression + .as_ref() + .is_some_and(|s| !s.is_empty()); + extenddb_core::expression::validate_expression_param_usage( + input.expression_attribute_names.as_ref(), + has_kce || has_filter_expr || has_proj_expr, + input.expression_attribute_values.as_ref(), + has_kce || has_filter_expr, + &[], + )?; + + // ConditionalOperator requires a QueryFilter with two or more conditions. + extenddb_core::validation::validate_conditional_operator_usage( + input.conditional_operator.is_some(), + input.query_filter.as_ref().map_or(0, HashMap::len), + ) +} + +/// Parse the request's `FilterExpression` and refuse its faults before the key +/// condition is parsed and the table is read: grammar and reserved words, +/// undefined `#name` references, operand types, then undefined `:value` +/// references (measured 2026-11-11, us-east-1). +fn parse_filter_expression( + input: &QueryInput, + maps: &ExpressionMaps, + limits: &extenddb_core::limits::LimitsConfig, +) -> Result, DynamoDbError> { + let Some(filter) = parse_optional_filter(input.filter_expression.as_deref(), limits)? else { + return Ok(None); + }; + let names = input.expression_attribute_names.as_ref(); + validate_name_refs_in_expr(&filter, names, ExpressionKind::Filter)?; + check_filter_operand_types(&filter, maps)?; + let mut placeholders = Vec::new(); + extenddb_core::expression::collect_value_placeholders(&filter, &mut placeholders); + for placeholder in &placeholders { + maps.resolve_value_for(placeholder, ExpressionKind::Filter.as_str())?; + } + Ok(Some(filter)) +} + +/// Refuse a `begins_with` or ordering operand of the wrong type in a filter. +fn check_filter_operand_types( + filter: &extenddb_core::expression::Expr, + maps: &ExpressionMaps, +) -> Result<(), DynamoDbError> { + extenddb_core::expression::validate_begins_with_operands(filter, maps) + .and_then(|()| extenddb_core::expression::validate_ordering_operand_types(filter, maps)) + .map_err(|e| crate::expression_helpers::prefix_expression_error(e, ExpressionKind::Filter)) +} + /// Validate that all `#name` references in an expression AST are defined. fn validate_name_refs_in_expr( expr: &extenddb_core::expression::Expr, diff --git a/crates/engine/src/query/request_checks.rs b/crates/engine/src/query/request_checks.rs new file mode 100644 index 000000000..bfa78489d --- /dev/null +++ b/crates/engine/src/query/request_checks.rs @@ -0,0 +1,213 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The checks `handle_query` makes on a request before it reads the table, +//! and the refusal authorization makes with them for a key condition with two +//! conditions on one key attribute. + +use std::collections::HashMap; + +use serde_json::Value; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::expression::{ + Expr, ExpressionKind, ExpressionMaps, KeyCondition, has_duplicate_key_condition, tokenize_for, +}; +use extenddb_core::limits::LimitsConfig; +use extenddb_core::types::QueryInput; + +use super::{check_request_parameters, parse_filter_expression}; +use crate::expression_helpers::build_expression_maps; + +/// A `Query` request read from its body, with its expressions parsed. +pub(super) struct CheckedRequest { + pub(super) input: QueryInput, + pub(super) maps: ExpressionMaps, + pub(super) filter_expression: Option, + /// The key condition, or the fault of its shape, which `handle_query` + /// answers after the table checks. + pub(super) key_condition_expression: Option>, +} + +/// Read a `Query` body and refuse its faults that come before the table is +/// read, in the order the service reports them. +pub(super) fn check_request( + mut body: Value, + limits: &LimitsConfig, +) -> Result { + crate::query_key_values::validate_query_request_body(&body)?; + // The service checks Select after Limit, the request's parameters, the + // FilterExpression and the KeyConditionExpression checks below (measured + // 2026-11-11), so an invalid Select is left out of the typed input and its + // error waits for those checks. A shape fault elsewhere in the body is + // reported ahead of it (see `validate_query_select`). + let select_check = crate::query_key_values::validate_query_select(&body); + if select_check.is_err() + && let Some(fields) = body.as_object_mut() + { + fields.remove("Select"); + } + // An invalid Select still comes ahead of a body that does not + // deserialize, as it did when it was checked before deserialization. + let input: QueryInput = match serde_json::from_value(body) { + Ok(input) => input, + Err(err) => { + select_check?; + return Err(crate::deserialize_error(err)); + } + }; + + // Build expression maps from request (used for expression-based parameters) + let maps = build_expression_maps( + input.expression_attribute_names.as_ref(), + input.expression_attribute_values.as_ref(), + ); + + // The service checks a Query in this order (measured 2026-11-11 and + // 2026-11-23 in us-east-1): Limit, then the request's parameters, then + // every FilterExpression fault, then every KeyConditionExpression fault + // except its shape, then Select, the table, the index and ConsistentRead. + check_request_parameters(&input)?; + let filter_expression = parse_filter_expression(&input, &maps, limits)?; + let key_condition_expression = input + .key_condition_expression + .as_deref() + .map(|kce| crate::expression_helpers::parse_key_condition_expr(kce, &maps, limits)) + .transpose()?; + select_check?; + Ok(CheckedRequest { + input, + maps, + filter_expression, + key_condition_expression, + }) +} + +/// Refuse a `Query` body whose `KeyConditionExpression` has two conditions on +/// one attribute, or whose `Select` is invalid, with the first fault +/// [`check_request`] finds in it. `names` is the body's +/// `ExpressionAttributeNames` without the `#`. Authorization calls this before +/// the IAM decision. The service refuses a duplicate for every principal +/// (measured 2026-11-19, us-east-1). For an invalid `Select`, every principal +/// gets the `Select` text or a fault that `check_request` reports ahead of it. +/// That answer is not measured for a principal the policy denies. +/// +/// # Errors +/// +/// The error [`check_request`] returns for the body. +pub fn refuse_duplicate_key_condition( + body: &Value, + names: &HashMap, + limits: &LimitsConfig, +) -> Result<(), DynamoDbError> { + let duplicate = body + .get("KeyConditionExpression") + .and_then(Value::as_str) + .is_some_and(|kce| { + tokenize_for( + kce, + limits.max_expression_tokens, + ExpressionKind::KeyCondition, + ) + .is_ok_and(|tokens| has_duplicate_key_condition(&tokens, names)) + }); + if duplicate || crate::query_key_values::validate_query_select(body).is_err() { + check_request(body.clone(), limits)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::{HashMap, refuse_duplicate_key_condition}; + use extenddb_core::error::DynamoDbError; + use extenddb_core::limits::LimitsConfig; + use serde_json::{Value, json}; + + fn refuse(kce: &str, extra: Value) -> Result<(), DynamoDbError> { + let mut body = json!({ + "TableName": "t", + "KeyConditionExpression": kce, + "ExpressionAttributeValues": { + ":own": {"S": "alice"}, ":other": {"S": "bob"}, ":b": {"S": "x"}, ":c": {"S": "y"}, + }, + }); + if let (Some(body), Value::Object(extra)) = (body.as_object_mut(), extra) { + body.extend(extra); + } + refuse_duplicate_key_condition(&body, &HashMap::new(), &LimitsConfig::default()) + } + + /// The service gave each answer below to the table's owner and to every + /// fenced, unallowed and denied principal (us-east-1, 2026-11-19). + #[test] + fn a_duplicate_gets_the_answer_of_the_table_owner() { + let one_per_key = "Invalid KeyConditionExpression: KeyConditionExpressions must only \ + contain one condition per key"; + let rows = [ + ("pk = :own AND sk = :b AND sk = :c", json!({}), one_per_key), + ( + "pk = :own AND pk = :other", + json!({"FilterExpression": "#q = :own"}), + "Invalid FilterExpression: An expression attribute name used in the document \ + path is not defined; attribute name: #q", + ), + ( + "pk = :other AND pk = :own AND #u = :c", + json!({}), + "Invalid KeyConditionExpression: An expression attribute name used in the \ + document path is not defined; attribute name: #u", + ), + ( + "pk = :other AND pk = :own", + json!({"Limit": 0}), + "1 validation error detected: Value at 'Limit' failed to satisfy constraint: \ + Member must have value greater than or equal to 1", + ), + ]; + for (kce, extra, want) in rows { + let label = format!("{kce} {extra}"); + let got = refuse(kce, extra); + assert!( + matches!(&got, Err(DynamoDbError::ValidationException(msg)) if msg == want), + "{label}: {got:?}" + ); + } + } + + /// The service authorizes these first: a principal fenced away from + /// `alice` gets AccessDeniedException for both (us-east-1, 2026-11-19). + #[test] + fn a_key_condition_without_a_duplicate_goes_on_to_authorization() { + for kce in ["pk = :own AND sk = :b", "pk > :own"] { + assert!(refuse(kce, json!({})).is_ok(), "{kce}"); + } + } + + /// An invalid `Select` is refused before authorization, after the filter + /// fault the service reports ahead of it (H3). + #[test] + fn an_invalid_select_is_refused_before_authorization() { + let select = "1 validation error detected: Value 'BOGUS' at 'select' failed to satisfy \ + constraint: Member must satisfy enum value set: [SPECIFIC_ATTRIBUTES, \ + COUNT, ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]"; + let rows = [ + ("pk = :own", json!({"Select": "BOGUS"}), select), + ("pk > :own", json!({"Select": "BOGUS"}), select), + ( + "pk = :own", + json!({"Select": "BOGUS", "FilterExpression": "#q = :own"}), + "Invalid FilterExpression: An expression attribute name used in the document \ + path is not defined; attribute name: #q", + ), + ]; + for (kce, extra, want) in rows { + let label = format!("{kce} {extra}"); + let got = refuse(kce, extra); + assert!( + matches!(&got, Err(DynamoDbError::ValidationException(msg)) if msg == want), + "{label}: {got:?}" + ); + } + } +} diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index 8dd925af3..eec7f17cd 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -73,8 +73,10 @@ const SELECT: &[&str] = &[ /// deserialized and before the table is looked up, in the service's order: /// `Limit`, the `ReturnConsumedCapacity` enum, the expression and /// 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 +/// `validate_names`), then every number in `ExpressionAttributeValues`. The +/// `Select` enum comes after them and after the `FilterExpression` and +/// `KeyConditionExpression` checks of `handle_query`; see +/// [`validate_query_select`] (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` @@ -121,8 +123,43 @@ const SELECT: &[&str] = &[ /// 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::(&readable_for_shape_check(body), check)) + shape_fault_ahead_of(body, query_request_checks(body)) +} + +/// The `Select` enum check, with the shape fault rule of +/// [`validate_query_request_body`]. `handle_query` runs it after that +/// function's checks and after the `FilterExpression` and +/// `KeyConditionExpression` checks, ahead of the table (measured 2026-11-11: +/// an undefined filter name and a second key condition on one key attribute +/// are reported ahead of an invalid `Select`). A body the service cannot read +/// as one type reports `Select` with `ReturnConsumedCapacity` and `Limit` +/// instead; see `unreadable_value_checks`. +/// +/// # Errors +/// +/// Returns `DynamoDbError::ValidationException` with the service's text, or +/// `DynamoDbError::SerializationException` for a body of the wrong shape. +pub fn validate_query_select(body: &Value) -> Result<(), DynamoDbError> { + shape_fault_ahead_of( + body, + crate::validate_enum_fields( + body, + &[crate::EnumField { + json_name: "Select", + valid: SELECT, + clause: crate::EnumClause::Named("select"), + }], + ), + ) +} + +/// `checked`, with a failed check replaced by the shape fault `body` holds, if +/// any; see [`shape_fault_first`]. +fn shape_fault_ahead_of( + body: &Value, + checked: Result<(), DynamoDbError>, +) -> Result<(), DynamoDbError> { + checked.map_err(|check| shape_fault_first::(&readable_for_shape_check(body), check)) } /// When a request-time check has failed with `check`, the deserializer's @@ -268,8 +305,8 @@ 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). + // the parameter mix, Select after the numbers and the expression checks + // (measured 2026-08-24 and 2026-11-11; see `validate_query_select`). crate::validate_enum_fields( body, &[crate::EnumField { @@ -285,15 +322,7 @@ fn query_request_checks(body: &Value) -> Result<(), DynamoDbError> { 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"), - }], - ) + Ok(()) } /// The expression and non-expression parameter mix check. 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 bf7bbbba4..b005ac566 100644 --- a/crates/engine/src/query_key_values/request_order_tests.rs +++ b/crates/engine/src/query_key_values/request_order_tests.rs @@ -7,7 +7,7 @@ use extenddb_core::error::DynamoDbError; use serde_json::json; use super::tests::{LIMIT_ZERO, NUMERIC_BOB, RCC_BAD, message, one_error}; -use super::{LIMIT_BELOW_ONE, validate_query_request_body}; +use super::{LIMIT_BELOW_ONE, validate_query_request_body, validate_query_select}; #[test] fn request_time_checks_run_limit_then_mix_then_numbers() { @@ -107,15 +107,17 @@ fn enum_checks_sit_on_either_side_of_the_numbers() { "{field}" ); } - // With the numbers valid, an invalid Select is still reported. + // With the numbers valid, an invalid Select is still reported, by the + // check that runs after the expression checks. let mut only_select = serde_json::json!({ "TableName": "t", "KeyConditionExpression": "pk = :u", "ExpressionAttributeValues": {":u": {"S": "bob"}}, }); only_select["Select"] = serde_json::json!("bad"); + assert!(validate_query_request_body(&only_select).is_ok()); assert!( - message(validate_query_request_body(&only_select)) + message(validate_query_select(&only_select)) .is_some_and(|m| m.contains("at 'select' failed to satisfy constraint")) ); } @@ -270,7 +272,11 @@ fn each_member_and_value_is_read_on_its_own_for_a_shape_fault() { .into_iter() .filter_map(|(values, extra, expected)| { let body = super::tests::body_with(values, extra); - let answer = match validate_query_request_body(&body) { + // The raw-body checks, then the Select check, as handle_query runs + // them before it deserializes the body. + let checked = + validate_query_request_body(&body).and_then(|()| validate_query_select(&body)); + let answer = match checked { Err(DynamoDbError::SerializationException(msg)) => ("SerializationException", msg), Err(DynamoDbError::ValidationException(msg)) => ("ValidationException", msg), other => panic!("{body}: unexpected answer {other:?}"), diff --git a/crates/server/src/leading_keys.rs b/crates/server/src/leading_keys.rs index f7f83b84b..6de728eb3 100644 --- a/crates/server/src/leading_keys.rs +++ b/crates/server/src/leading_keys.rs @@ -369,7 +369,7 @@ fn index_name(input: &Value) -> Option { /// `ExpressionAttributeNames` with the leading `#` stripped from each key, /// matching how the engine builds its name map. -fn names_map(input: &Value) -> HashMap { +pub(crate) fn names_map(input: &Value) -> HashMap { let mut out = HashMap::new(); if let Some(m) = input .get("ExpressionAttributeNames") diff --git a/crates/server/src/request_attributes.rs b/crates/server/src/request_attributes.rs index 3404240e6..66717eef9 100644 --- a/crates/server/src/request_attributes.rs +++ b/crates/server/src/request_attributes.rs @@ -355,12 +355,12 @@ impl<'a> Names<'a> { } } - /// The paths in a `KeyConditionExpression`, read as the engine's key - /// condition parser reads it (`parse_key_condition_expr` in - /// `crates/engine/src/expression_helpers.rs`): under the size and token + /// The paths in a `KeyConditionExpression`, under the size and token /// limits, with the reserved-word check when `enforce_reserved_keywords` - /// is set, then `parse_key_condition`. A key condition the key condition - /// parser refuses gives none. + /// is set, then the map-less `parse_key_condition`, which accepts key + /// conditions the engine refuses for an undefined reference, a + /// `begins_with` operand type or a second condition on one key attribute. + /// A key condition `parse_key_condition` refuses gives none. fn key_condition(&mut self, value: Option<&Value>) { let Some(text) = self.text(value) else { return; diff --git a/crates/server/src/request_helpers.rs b/crates/server/src/request_helpers.rs index 6c205c5eb..b2833a383 100755 --- a/crates/server/src/request_helpers.rs +++ b/crates/server/src/request_helpers.rs @@ -473,6 +473,14 @@ pub(crate) async fn authorize_request( return Ok(authorized_key_info); } + if operation == "Query" { + extenddb_engine::refuse_duplicate_key_condition( + input, + &crate::leading_keys::names_map(input), + &state.limits, + )?; + } + // Derive the targets the service authorizes this operation against. The // resource comes from the field the operation actually carries it in // (ResourceArn, StreamArn, BackupArn, TableArn, IndexName, or a table ARN diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 2596ba457..aae7a2061 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -399,6 +399,16 @@ deployment, even when no catalog migration is required. No catalog migration or configuration change is required. +### v1.1.0: `Query` refuses a second condition on one key attribute + +**What changed** (#484). Some `Query` requests that 1.0.0 ran now get `ValidationException`, as DynamoDB answers them: + +- a `KeyConditionExpression` with two conditions on one key attribute, such as `pk = :a AND pk = :b`: `Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key` +- a `FilterExpression` that names a `:value` the request does not define, on a partition with no items +- a `FilterExpression` beside `KeyConditions` that names `:_kc_pk` when the request does not define it. ExtendDB uses that name for the `KeyConditions` partition value, and 1.0.0 compared the filter with that value. + +ExtendDB refuses a key condition with two conditions on one key attribute before the IAM decision. A principal whose policy does not allow such a request got `AccessDeniedException` from 1.0.0 and now gets the `ValidationException`. The 0.1.15 LeadingKeys entry below says that an equality on the partition key decides `dynamodb:LeadingKeys`. That no longer holds for a key condition with two conditions on one key attribute. No catalog migration is required. + ### v1.0.0: Cassandra reads and writes at `LOCAL_QUORUM` **What changed.** The Cassandra backend runs its reads and writes at `LOCAL_QUORUM`. 0.1.15 ran many of them at `ONE`, the driver's default, in each area: items (the reads of GetItem, Query and Scan among them), transactions, TTL, streams, the catalog, IAM and `init`. A read with `ConsistentRead` `false` also runs at `LOCAL_QUORUM`. A lightweight transaction runs Paxos at `LOCAL_SERIAL` and commits at `LOCAL_QUORUM`. 0.1.15 ran many of its lightweight transactions at those levels already, and others, among them the admin user creation and most IAM writes, at the driver's defaults, `SERIAL` and `ONE`. Batches ran at `LOCAL_QUORUM` before and still do. No setting changes these levels (#945). diff --git a/tests/test_fgac_leading_keys.py b/tests/test_fgac_leading_keys.py index 905fcd1f1..302eb07b4 100644 --- a/tests/test_fgac_leading_keys.py +++ b/tests/test_fgac_leading_keys.py @@ -96,6 +96,12 @@ def _denied(exc: ClientError) -> bool: return exc.value.response["Error"]["Code"] == "AccessDeniedException" +ONE_PER_KEY = ( + "Invalid KeyConditionExpression: " + "KeyConditionExpressions must only contain one condition per key" +) + + # The values a Query on the multi-attribute key table may name; each query # carries only the ones its key condition uses. _MK_VALUES = {":v": {"S": OWN}, ":g": {"S": "blue"}, ":x": {"S": "x1"}, @@ -371,12 +377,26 @@ def test_scan_denied_under_for_any_value(self, table): c.scan(TableName=table) assert _denied(e) - # -- An equality on the partition key decides the key ------------------ + # -- A second clause on the partition key ------------------------------ - def test_unreadable_partition_equality_does_not_bind_another_clause(self, table): - # An equality on the partition key decides the key. When its value - # cannot be read (`:u = {"N": "bob"}`), a second clause naming the - # fenced value must not be bound in its place. + def test_partition_equality_does_not_bind_another_clause(self, table): + # Two clauses on the partition key are refused before + # dynamodb:LeadingKeys is evaluated, so no clause is bound. A principal + # allowed everything and principals fenced to `:v`'s value get the + # same ValidationException (measured 2026-11-12 and 2026-11-19). + kces = ("pk = :u AND pk > :v", "pk > :v AND pk = :u") + values = {":u": {"S": OTHER}, ":v": {"S": OWN}} + owner = self._user_client([("all", { + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"}], + })]) + for kce in kces: + with pytest.raises(ClientError) as e: + owner.query(TableName=table, KeyConditionExpression=kce, + ExpressionAttributeValues=values) + err = e.value.response["Error"] + assert err["Code"] == "ValidationException", kce + assert err["Message"] == ONE_PER_KEY, kce for form in ("ForAnyValue", "ForAllValues+Null"): if form == "ForAnyValue": policy = self._leading_keys_policy("ForAnyValue", [OWN], table) @@ -385,15 +405,61 @@ def test_unreadable_partition_equality_does_not_bind_another_clause(self, table) stmt = policy["Statement"][0] stmt["Condition"]["Null"] = {"dynamodb:LeadingKeys": "false"} c = self._user_client([("lk", policy)]) - for kce in ("pk = :u AND pk > :v", "pk > :v AND pk = :u"): - try: - got = c.query( - TableName=table, KeyConditionExpression=kce, - ExpressionAttributeValues={":u": {"N": OTHER}, ":v": {"S": OWN}}) - except ClientError: - continue - parts = {it["pk"]["S"] for it in got["Items"]} - assert OTHER not in parts, (form, kce, parts) + for kce in kces: + with pytest.raises(ClientError) as e: + c.query(TableName=table, KeyConditionExpression=kce, + ExpressionAttributeValues=values) + err = e.value.response["Error"] + assert (err["Code"], err["Message"]) == ( + "ValidationException", ONE_PER_KEY), (form, kce) + + def test_duplicate_key_condition_is_refused_before_leading_keys(self, table): + # A key condition with two conditions on one key attribute is refused + # before the IAM decision. Principals fenced to `own`, fenced away from + # every value in the request, allowed no Query or denied Query all get + # the one-condition-per-key error (measured 2026-11-12 and 2026-11-19, + # us-east-1). + values = {":own": {"S": OWN}, ":other": {"S": OTHER}, ":b": {"S": "x"}, + ":c": {"S": "y"}} + names = {"ExpressionAttributeNames": {"#p": "pk"}} + gsi = {"IndexName": "gsi1"} + shapes = [ + ("pk = :own AND sk = :b AND sk = :c", {}), + ("pk = :own AND pk = :other", {}), + ("pk = :other AND pk = :own", {}), + ("pk = :own AND pk > :other", {}), + ("pk > :other AND pk = :own", {}), + ("#p = :own AND pk = :other", names), + ("pk = :other AND #p = :own", names), + ("gpk = :own AND gpk = :other", gsi), + ("gpk = :own AND pk = :b AND pk = :c", gsi), + ] + guarded = self._leading_keys_policy("ForAllValues", [OWN], table) + guarded["Statement"][0]["Condition"]["Null"] = {"dynamodb:LeadingKeys": "false"} + arn = f"arn:aws:dynamodb:{self.region}:{self.account_id}:table/{table}" + resources = [arn, arn + "/index/*"] + policies = { + "ForAnyValue own": self._leading_keys_policy("ForAnyValue", [OWN], table), + "ForAnyValue other": self._leading_keys_policy("ForAnyValue", [OTHER], table), + "ForAllValues away": self._leading_keys_policy("ForAllValues", ["away"], table), + "ForAllValues own, Null guard": guarded, + "no Query": {"Version": "2012-10-17", "Statement": [{ + "Effect": "Allow", "Action": "dynamodb:DescribeTable", + "Resource": resources}]}, + "Query denied": {"Version": "2012-10-17", "Statement": [ + {"Effect": "Allow", "Action": "dynamodb:*", "Resource": resources}, + {"Effect": "Deny", "Action": "dynamodb:Query", "Resource": resources}]}, + } + for label, policy in policies.items(): + c = self._user_client([("lk", policy)]) + for kce, extra in shapes: + used = {k: values[k] for k in re.findall(r":\w+", kce)} + with pytest.raises(ClientError) as e: + c.query(TableName=table, KeyConditionExpression=kce, + ExpressionAttributeValues=used, **extra) + err = e.value.response["Error"] + assert (err["Code"], err["Message"]) == ( + "ValidationException", ONE_PER_KEY), (label, kce) def test_non_equality_partition_with_sort_clause_is_refused(self, table): # The fix binds the partition operand of these shapes; the engine still diff --git a/tests/test_query_key_condition_one_per_key.py b/tests/test_query_key_condition_one_per_key.py new file mode 100644 index 000000000..bef5bbec0 --- /dev/null +++ b/tests/test_query_key_condition_one_per_key.py @@ -0,0 +1,428 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""A KeyConditionExpression carries one condition per key attribute. + +Amazon DynamoDB refuses a key condition that names the same key attribute +twice, on the partition key and on the sort key alike, whatever the operators +are: + + ValidationException: Invalid KeyConditionExpression: KeyConditionExpressions + must only contain one condition per key + +Every row below is a request and the answer the service gave it in us-east-1, +on the date in its class's docstring. The 2026-10-24 and 2026-10-31 rows ran on +a table with pk (S) HASH and sk (S) RANGE, and the 2026-11-11 rows from 09:43Z +to 12:44Z on such a table with a KEYS_ONLY global secondary index on g (S). The +2026-11-10 rows and J2 ran on a table keyed on pk (S) alone. Where the +service's text differs from extenddb's by wording alone (syntax errors), the +row compares the prefix. + +Dual-target against Amazon DynamoDB and extenddb. +""" + +from __future__ import annotations + +import pytest +from botocore.exceptions import ClientError + +from conftest import scoped_table + +ONE_PER_KEY = ( + "Invalid KeyConditionExpression: " + "KeyConditionExpressions must only contain one condition per key" +) +NESTED = ( + "Invalid KeyConditionExpression: " + "KeyConditionExpressions cannot have conditions on nested attributes" +) +REDUNDANT_PARENS = "Invalid KeyConditionExpression: The expression has redundant parentheses;" +BEGINS_WITH_N = ( + "Invalid KeyConditionExpression: Incorrect operand type for operator or " + "function; operator or function: begins_with, operand type: N" +) +FILTER_BEGINS_WITH_N = ( + "Invalid FilterExpression: Incorrect operand type for operator or " + "function; operator or function: begins_with, operand type: N" +) +FILTER_RESERVED_NAME = ( + "Invalid FilterExpression: Attribute name is a reserved keyword; reserved keyword: name" +) +LIMIT_ZERO = ( + "1 validation error detected: Value at 'Limit' failed to satisfy constraint: " + "Member must have value greater than or equal to 1" +) +# A prefix match: the service words its syntax errors differently from extenddb. +KCE_PREFIX = "Invalid KeyConditionExpression: " +FILTER_PREFIX = "Invalid FilterExpression: " + +A = {"S": "alice"} +B = {"S": "bob"} +C = {"S": "carol"} +N1 = {"N": "1"} +VALUES = {"a": A, "b": B, "c": C, "n": N1, "z": {"S": "zed"}, "v": A, "w": B, "extra": B} +GSI = "g-keys" +HASH = "hash-table" # stands for the hash_table fixture in a row's TableName +MISSING_TABLE = "extenddb-test-484-no-such-table" +NOT_FOUND = ("ResourceNotFoundException", "Requested resource not found") +LEGACY_PK = {"pk": {"ComparisonOperator": "EQ", "AttributeValueList": [A]}} + + +def _undefined(reference: str, expression: str = "KeyConditionExpression") -> str: + """The service's message for an undefined `#name` or `:value`.""" + if reference.startswith("#"): + return ( + f"Invalid {expression}: An expression attribute name used in the " + f"document path is not defined; attribute name: {reference}" + ) + return ( + f"Invalid {expression}: An expression attribute value used in " + f"expression is not defined; attribute value: {reference}" + ) + + +def _mixing(non_expression: str, *expression: str) -> str: + return ( + "Can not use both expression and non-expression parameters in the same " + f"request: Non-expression parameters: {{{non_expression}}} Expression " + f"parameters: {{{', '.join(expression)}}}" + ) + + +def _q(kce: str | None = None, values=None, names: dict | None = None, **kwargs) -> dict: + """A Query's parameters. `values` names the entries of VALUES to define, + as "a b n", or is the ExpressionAttributeValues dict itself.""" + request = dict(kwargs) + if kce is not None: + request["KeyConditionExpression"] = kce + if isinstance(values, str): + values = {f":{k}": VALUES[k] for k in values.split()} + if values: + request["ExpressionAttributeValues"] = values + if names: + request["ExpressionAttributeNames"] = names + return request + + +def _refused(client, table: str, request: dict, want) -> None: + """Send the Query against `table` and compare the ValidationException's + text with `want`, or its prefix when `want` is one. A (code, text) pair + names another error. With KCE_PREFIX the text must also not contain + "operator".""" + request = {"TableName": table, **request} + code, want = want if isinstance(want, tuple) else ("ValidationException", want) + with pytest.raises(ClientError) as exc_info: + client.query(**request) + err = exc_info.value.response["Error"] + assert err["Code"] == code, err + if want in (KCE_PREFIX, FILTER_PREFIX): + assert err["Message"].startswith(want), err["Message"] + if want == KCE_PREFIX: + assert "operator" not in err["Message"], err["Message"] + else: + assert err["Message"] == want + + +@pytest.fixture(scope="class") +def range_table(dynamodb_client): + """pk (S) HASH, sk (S) RANGE, holding alice/bob and alice/carol, with a + KEYS_ONLY global secondary index on g (S).""" + with scoped_table( + dynamodb_client, + attribute_definitions=[ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "sk", "AttributeType": "S"}, + {"AttributeName": "g", "AttributeType": "S"}, + ], + key_schema=[ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"}, + ], + GlobalSecondaryIndexes=[ + { + "IndexName": GSI, + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "KEYS_ONLY"}, + } + ], + ) as name: + for sk in ("bob", "carol"): + dynamodb_client.put_item(TableName=name, Item={"pk": {"S": "alice"}, "sk": {"S": sk}}) + yield name + + +@pytest.fixture(scope="class") +def hash_table(dynamodb_client): + """pk (S) HASH and no sort key.""" + with scoped_table(dynamodb_client) as name: + yield name + + +class TestOneConditionPerKey: + """The duplicate shapes of 2026-10-24 except the reserved word row, J1 and + J2 (2026-11-11), the shapes that keep their own error, and the distinct + conditions that are served.""" + + ROWS = [ + ("pk = :a AND pk = :b", _q("pk = :a AND pk = :b", "a b"), ONE_PER_KEY), + ("pk = :a AND pk = :a", _q("pk = :a AND pk = :a", "a"), ONE_PER_KEY), + ("pk twice, sk", _q("pk = :a AND pk = :b AND sk = :c", "a b c"), ONE_PER_KEY), + ("pk = :a AND pk > :b", _q("pk = :a AND pk > :b", "a b"), ONE_PER_KEY), + ("pk > :b AND pk = :a", _q("pk > :b AND pk = :a", "a b"), ONE_PER_KEY), + (":a = pk AND pk = :b", _q(":a = pk AND pk = :b", "a b"), ONE_PER_KEY), + ("(pk = :a) AND (pk = :b)", _q("(pk = :a) AND (pk = :b)", "a b"), ONE_PER_KEY), + ("sk = :b AND sk = :c", _q("pk = :a AND sk = :b AND sk = :c", "a b c"), ONE_PER_KEY), + ("sk = :b AND sk = :b", _q("pk = :a AND sk = :b AND sk = :b", "a b"), ONE_PER_KEY), + ("BETWEEN and =", _q("pk = :a AND sk BETWEEN :b AND :c AND sk = :b", "a b c"), ONE_PER_KEY), + ( + "BETWEEN and begins_with", + _q("pk = :a AND sk BETWEEN :b AND :c AND begins_with(sk, :b)", "a b c"), + ONE_PER_KEY, + ), + ( + "begins_with and =", + _q("pk = :a AND begins_with(sk, :b) AND sk = :c", "a b c"), + ONE_PER_KEY, + ), + ("> and <", _q("pk = :a AND sk > :b AND sk < :c", "a b c"), ONE_PER_KEY), + ( + "begins_with twice", + _q("pk = :a AND begins_with(sk, :b) AND begins_with(sk, :c)", "a b c"), + ONE_PER_KEY, + ), + ( + "pk twice, sk twice", + _q("pk = :a AND pk = :b AND sk = :b AND sk = :c", "a b c"), + ONE_PER_KEY, + ), + # No partition key condition: the duplicate comes ahead of the missing key. + ("sk twice, no pk", _q("sk = :b AND sk = :c", "b c"), ONE_PER_KEY), + ("#p = :a AND pk = :b", _q("#p = :a AND pk = :b", "a b", {"#p": "pk"}), ONE_PER_KEY), + ("#p and #q", _q("#p = :a AND #q = :b", "a b", {"#p": "pk", "#q": "pk"}), ONE_PER_KEY), + ("#s and sk", _q("pk = :a AND #s = :b AND sk = :c", "a b c", {"#s": "sk"}), ONE_PER_KEY), + ("J1 non-key attribute twice", _q("pk = :a AND zz = :b AND zz = :c", "a b c"), ONE_PER_KEY), + ("J2 hash-only table", _q("pk = :a AND pk = :b", "a b", TableName=HASH), ONE_PER_KEY), + ("nested path first", _q("pk = :a AND pk.foo = :b", "a b"), NESTED), + ("redundant parentheses first", _q("((pk = :a)) AND (pk = :b)", "a b"), REDUNDANT_PARENS), + ("undefined #u first", _q("#u = :a AND #u = :b", "a b"), _undefined("#u")), + ] + + @pytest.mark.parametrize("row", ROWS, ids=[r[0] for r in ROWS]) + def test_refused(self, dynamodb_client, range_table, hash_table, row): + _, request, want = row + if request.get("TableName") == HASH: + request = {**request, "TableName": hash_table} + _refused(dynamodb_client, range_table, request, want) + + @pytest.mark.parametrize( + ("kce", "values", "count"), + [ + ("pk = :a", "a", 2), + ("pk = :a AND sk = :b", "a b", 1), + ("sk = :b AND pk = :a", "a b", 1), + ("pk = :a AND sk BETWEEN :b AND :c", "a b c", 2), + ], + ) + def test_distinct_key_conditions_still_served( + self, dynamodb_client, range_table, kce, values, count + ): + got = dynamodb_client.query(TableName=range_table, **_q(kce, values)) + assert got["Count"] == count + + +class TestDuplicateCheckOrder: + """The duplicate against undefined references, the key value type check + and an unused value (2026-10-31).""" + + ROWS = [ + ("#u in clause 1", _q("#u = :a AND sk = :b AND sk = :c", "a b c"), _undefined("#u")), + ("#u in clause 3", _q("pk = :a AND pk = :b AND #u = :c", "a b c"), _undefined("#u")), + ("#u twice, >", _q("#u = :a AND #u > :b", "a b"), _undefined("#u")), + ("no values", _q("pk = :a AND pk = :b"), _undefined(":a")), + # A number on the S key: the duplicate comes ahead of the type check. + ("#p and pk, :n", _q("#p = :a AND pk = :n", "a n", {"#p": "pk"}), ONE_PER_KEY), + ( + "#s and sk, :n", + _q("pk = :a AND #s = :b AND sk = :n", "a b n", {"#s": "sk"}), + ONE_PER_KEY, + ), + ("unused :z", _q("pk = :a AND pk = :b", "a b z"), ONE_PER_KEY), + ] + + @pytest.mark.parametrize("row", ROWS, ids=[r[0] for r in ROWS]) + def test_refused(self, dynamodb_client, range_table, row): + _, request, want = row + _refused(dynamodb_client, range_table, request, want) + + +class TestDuplicateAheadOfRequestChecks: + """The duplicate against the FilterExpression (A), the table, index, + ConsistentRead and Select checks (B) and parameter mixing (E8, E9), + measured 2026-11-11T09:43Z and 11:23Z.""" + + DUP = "pk = :a AND pk = :b" + ROWS = [ + ("A1", _q(DUP, "a b", FilterExpression="#q = :a"), _undefined("#q", "FilterExpression")), + ("A2", _q(DUP, "a b", FilterExpression="foo = :zz"), _undefined(":zz", "FilterExpression")), + ("A3", _q(DUP, "a b n", FilterExpression="begins_with(foo, :n)"), FILTER_BEGINS_WITH_N), + ("A4", _q(DUP, "a b", FilterExpression="name = :a"), FILTER_RESERVED_NAME), + ("A5", _q(DUP, "a b", FilterExpression="zz = = :a"), FILTER_PREFIX), + ("B1", _q(DUP, "a b", TableName=MISSING_TABLE), ONE_PER_KEY), + ("B2", _q(DUP, "a b", IndexName="nope"), ONE_PER_KEY), + ("B3", _q("g = :a AND g = :b", "a b", IndexName=GSI, ConsistentRead=True), ONE_PER_KEY), + ("B4", _q(DUP, "a b", Select="BOGUS"), ONE_PER_KEY), + ("B5", _q("g = :a AND g = :b", "a b", IndexName=GSI, Select="ALL_ATTRIBUTES"), ONE_PER_KEY), + ( + "E8", + _q(DUP, "a b", ConditionalOperator="AND"), + _mixing("ConditionalOperator", "KeyConditionExpression"), + ), + ( + "E9", + _q(DUP, "a b", KeyConditions=LEGACY_PK), + _mixing("KeyConditions", "KeyConditionExpression"), + ), + ] + + @pytest.mark.parametrize("row", ROWS, ids=[r[0] for r in ROWS]) + def test_refused(self, dynamodb_client, range_table, row): + _, request, want = row + _refused(dynamodb_client, range_table, request, want) + + +class TestReferenceAndOperatorOrder: + """The first undefined reference in the order the expression is written + (C, 2026-11-11, and the 2026-11-10 rows on a table keyed on pk alone), and + `<>`, `contains` and `begins_with` with and without a duplicate (D, E, + 2026-11-11).""" + + ROWS = [ + ("C1", _q("pk = :q AND #u = :c"), _undefined(":q")), + ("C2", _q("sk = :b AND pk = :a"), _undefined(":b")), + ("C3", _q("pk = :a AND sk = :missing", "a extra"), _undefined(":missing")), + ("C4", _q("pk = :a AND pk = :b AND #u = :c"), _undefined(":a")), + ("C5", _q("pk = :q AND pk = :b AND #u = :c", "b c"), _undefined(":q")), + ("C6", _q("#u = :a AND #u = :b"), _undefined("#u")), + ("C7", _q("pk = :b AND pk = :a"), _undefined(":b")), + # 2026-11-10: each request also carries an unused name or value. + ("10 Nov unused :w", _q("pk = :v", {":w": A}), _undefined(":v")), + ("10 Nov #k, unused :w", _q("#k = :v", "v w"), _undefined("#k")), + ("10 Nov #k, unused #j", _q("#k = :v", "v", {"#j": "pk"}), _undefined("#k")), + ("10 Nov unused #j and :w", _q("pk = :v", {":w": A}, {"#j": "pk"}), _undefined(":v")), + ("10 Nov #k, only :w", _q("#k = :v", {":w": A}), _undefined("#k")), + ("D1", _q("pk = :a AND pk <> :b", "a b"), ONE_PER_KEY), + ("D2", _q("pk = :a AND contains(pk, :b)", "a b"), ONE_PER_KEY), + ("D3", _q("pk = :a AND begins_with(sk, :n) AND sk = :b", "a b n"), BEGINS_WITH_N), + ("E11", _q("pk = :a AND sk <> :b AND sk = :c", "a b c"), ONE_PER_KEY), + ("E12", _q("pk = :a AND contains(sk, :b) AND sk = :c", "a b c"), ONE_PER_KEY), + ("E1", _q("pk = :a AND begins_with(sk, :n)", "a n"), BEGINS_WITH_N), + ("E2", _q("pk = :a AND sk <> :b AND #u = :c", "a b c"), _undefined("#u")), + ("E3", _q("pk = :a AND contains(sk, :b) AND #u = :c", "a b c"), _undefined("#u")), + # The service answers a syntax error; the prefix match also checks that + # the operator is not what is reported. + ("E10", _q("pk = :a AND sk <> :b AND", "a b"), KCE_PREFIX), + ] + + @pytest.mark.parametrize("row", ROWS, ids=[r[0] for r in ROWS]) + def test_refused(self, dynamodb_client, range_table, row): + _, request, want = row + _refused(dynamodb_client, range_table, request, want) + + +class TestQueryCheckOrder: + """The order of a Query's checks without a duplicate (2026-11-11T12:42Z to + 12:44Z): parameters, then the FilterExpression, then the + KeyConditionExpression, then Select, the table, the index and + ConsistentRead. F3 is an undefined filter value on a partition with no + items. R10 and R11 (2026-11-23T16:58Z) have no equality on the partition + key: the service reads the key condition's shape after the table.""" + + Q = "#q = :a" + CO = {"ConditionalOperator": "AND"} + UNDEFINED_Q = _undefined("#q", "FilterExpression") + MIXING = _mixing("ConditionalOperator", "KeyConditionExpression") + ROWS = [ + ("F1", _q("pk = :a AND sk = :missing", "a", FilterExpression=Q), UNDEFINED_Q), + ("F1b", _q("pk = :a AND sk = :missing", "a", FilterExpression="zz = = :a"), FILTER_PREFIX), + ("F1c", _q("pk = :a AND #s = :b", "a b", FilterExpression=Q), UNDEFINED_Q), + ( + "F1d", + _q("pk = :a AND #s = :b", "a b", FilterExpression="foo = :zz"), + _undefined(":zz", "FilterExpression"), + ), + ( + "F1e", + _q("pk = :a AND sk = :missing", "a", FilterExpression="foo = :a"), + _undefined(":missing"), + ), + ("F1f", _q("pk = :a AND begins_with(sk, :n)", "a n", FilterExpression=Q), UNDEFINED_Q), + ("F1g", _q("pk = :a AND", "a", FilterExpression=Q), UNDEFINED_Q), + ("F2a", _q("pk = :a", "a", TableName=MISSING_TABLE, **CO), MIXING), + ("F2b", _q("pk = :a", "a", IndexName="nope", **CO), MIXING), + ("F2c", _q("pk = :a", "a", Select="BOGUS", **CO), MIXING), + ("F2d", _q("g = :a", "a", IndexName=GSI, ConsistentRead=True, **CO), MIXING), + ("H1", _q("pk = :a", "a", TableName=MISSING_TABLE, FilterExpression=Q), UNDEFINED_Q), + ("H2", _q("pk = :a", "a", IndexName="nope", FilterExpression=Q), UNDEFINED_Q), + ("H3", _q("pk = :a", "a", Select="BOGUS", FilterExpression=Q), UNDEFINED_Q), + ( + "H4", + _q("g = :a", "a", IndexName=GSI, ConsistentRead=True, FilterExpression=Q), + UNDEFINED_Q, + ), + ( + "H5", + _q("pk = :a", "a", FilterExpression=Q, **CO), + _mixing("ConditionalOperator", "FilterExpression", "KeyConditionExpression"), + ), + ( + "F3", + _q("pk = :a", {":a": {"S": "p484-empty"}}, FilterExpression="foo = :zz"), + _undefined(":zz", "FilterExpression"), + ), + ("R10", _q("pk > :a", "a", TableName=MISSING_TABLE), NOT_FOUND), + ("R11", _q("pk > :a AND sk > :b", "a b", TableName=MISSING_TABLE), NOT_FOUND), + ] + + @pytest.mark.parametrize("row", ROWS, ids=[r[0] for r in ROWS]) + def test_refused(self, dynamodb_client, range_table, row): + _, request, want = row + _refused(dynamodb_client, range_table, request, want) + + +class TestLimitAndParameterChecksFirst: + """Limit 0 ahead of every other fault (L), begins_with on the partition + key (P1) and the parameter checks ahead of a missing table (M), measured + 2026-11-11T13:26Z. The SDK refuses Limit 0 before it sends the request, so + the L rows use the client with its checks off.""" + + ROWS = [ + ("L1", _q("pk = :a", "a", Limit=0), LIMIT_ZERO), + ("L2", _q("pk = :a AND", "a", Limit=0), LIMIT_ZERO), + ("L3", _q("pk = :a AND pk = :b", "a b", Limit=0), LIMIT_ZERO), + ("L4", _q("pk = :a", "a", FilterExpression="#q = :a", Limit=0), LIMIT_ZERO), + ("L5", _q("pk = :a", "a", ConditionalOperator="AND", Limit=0), LIMIT_ZERO), + ("L6", _q("pk = :a", "a", TableName=MISSING_TABLE, Limit=0), LIMIT_ZERO), + ("L7", _q("pk = :a", "a", Select="BOGUS", Limit=0), LIMIT_ZERO), + ("P1", _q("begins_with(pk, :n)", "n"), BEGINS_WITH_N), + ( + "M1", + _q(None, "a", TableName=MISSING_TABLE, KeyConditions=LEGACY_PK), + "ExpressionAttributeValues can only be specified when using expressions", + ), + ( + "M2", + _q("", TableName=MISSING_TABLE), + "Invalid KeyConditionExpression: The expression can not be empty;", + ), + ( + "M3", + _q(None, TableName=MISSING_TABLE, KeyConditions=LEGACY_PK, ConditionalOperator="AND"), + "ConditionalOperator cannot be used without Filter or Expected", + ), + ] + + @pytest.mark.parametrize("row", ROWS, ids=[r[0] for r in ROWS]) + def test_refused(self, dynamodb_client, dynamodb_client_no_validation, range_table, row): + _, request, want = row + client = dynamodb_client_no_validation if "Limit" in request else dynamodb_client + _refused(client, range_table, request, want)