diff --git a/crates/engine/src/create_table.rs b/crates/engine/src/create_table.rs index 3426d16d7..a98d7c2c9 100755 --- a/crates/engine/src/create_table.rs +++ b/crates/engine/src/create_table.rs @@ -13,6 +13,9 @@ pub async fn handle_create_table( mut body: Value, ctx: &OperationContext, ) -> Result { + // The service answers a TableClass outside its set ahead of the + // BillingMode fault, which is checked here before the read. + let table_class = crate::nested_enums::table_class_fault(&body); crate::validate_enum_fields( &body, &[ @@ -27,7 +30,8 @@ pub async fn handle_create_table( clause: crate::EnumClause::Named("tableThroughputMode"), }, ], - )?; + ) + .map_err(|e| table_class.clone().unwrap_or(e))?; crate::require_stream_enabled_member(&body)?; let enum_faults = crate::nested_enums::EnumFaults::create_table(&mut body)?; @@ -50,10 +54,18 @@ pub async fn handle_create_table( )) } })?; + read_sse_enabled(input.sse_specification.as_mut())?; + // The service reads the body and checks the table name length before it + // answers the table class fault. + if let Some(fault) = table_class { + extenddb_core::validation::validate_table_name(&input.table_name, &ctx.limits)?; + return Err(fault); + } enum_faults.check()?; input.resolve_table_throughput_mode(); validate_create_table(&input, &ctx.limits)?; + check_sse_specification(input.sse_specification.as_ref())?; // An empty SearchSchema means the same as an absent one, so it is collapsed // here, once, rather than in each backend. Storing the empty list would make @@ -113,6 +125,53 @@ pub async fn handle_create_table( serialize_output(&output) } +/// The service's refusals of an `SSESpecification` whose members do not go +/// together, once [`read_sse_enabled`] has read its `Enabled`. They come +/// after the member faults. An `Enabled` that is not a boolean is not +/// checked. +fn check_sse_specification(spec: Option<&Value>) -> Result<(), DynamoDbError> { + let Some(spec) = spec else { + return Ok(()); + }; + let sse_type = spec.get("SSEType").and_then(Value::as_str); + let key = spec.get("KMSMasterKeyId").is_some_and(|k| !k.is_null()); + let reason = match spec.get("Enabled").and_then(Value::as_bool) { + Some(false) if sse_type.is_some() => "SSEType can not be specified if Enabled is false", + Some(false) if key => "KMSMasterKeyId can not be specified if Enabled is false", + Some(true) if sse_type == Some("AES256") => "SSEType AES256 is not supported", + Some(true) if key && sse_type != Some("KMS") => { + "SSEType KMS is required if KMSMasterKeyId is specified" + } + _ => return Ok(()), + }; + Err(DynamoDbError::ValidationException(format!( + "One or more parameter values were invalid: {reason}" + ))) +} + +/// Writes an `Enabled` given as a string back as the boolean the service +/// reads it as, so that the checks and the backends read the same value: a +/// string of [`crate::query_key_values::boolean_text`], in any ASCII case. +/// The service refuses any other string while it reads the body. Measured on +/// UpdateTable on 2026-12-02, each body twice: `"FALSE"`, `"False"`, `"no"`, +/// `"f"`, `"0"` and `"N"` read as false, `"TRUE"`, `"true"`, `"t"` and `"1"` +/// as true, and `""`, `"on"` and `"maybe"` answer `Unexpected token received +/// from parser`. +fn read_sse_enabled(spec: Option<&mut Value>) -> Result<(), DynamoDbError> { + let Some(enabled) = spec.and_then(|spec| spec.get_mut("Enabled")) else { + return Ok(()); + }; + if let Some(text) = enabled.as_str() { + let read = crate::query_key_values::boolean_text(text).ok_or_else(|| { + DynamoDbError::SerializationException( + "Unexpected token received from parser".to_owned(), + ) + })?; + *enabled = Value::Bool(read); + } + Ok(()) +} + /// Map a storage-layer error to its `DynamoDB` wire error. /// /// Exposed so the server's authorization path classifies a key-info lookup diff --git a/crates/engine/src/nested_enums.rs b/crates/engine/src/nested_enums.rs index 1743f57fb..333138151 100644 --- a/crates/engine/src/nested_enums.rs +++ b/crates/engine/src/nested_enums.rs @@ -2,14 +2,16 @@ // SPDX-License-Identifier: Apache-2.0 //! The `ProjectionType` of each index and the `StreamViewType` of a -//! `CreateTable` or `UpdateTable` body, which [`crate::validate_enum_fields`] -//! does not reach. +//! `CreateTable` or `UpdateTable` body, and the `SSEType` and +//! `KMSMasterKeyId` of a `CreateTable` body, which +//! [`crate::validate_enum_fields`] does not reach. Also the `TableClass` of +//! both, which the service refuses with its own sentence. //! //! The typed read refuses a value outside its enum with a //! `SerializationException`. The service answers a `ValidationException` //! naming each such member, in its own order, once the body is read -//! (measured 2026-11-13, 2026-11-14 and 2026-11-17, us-east-1). So -//! [`EnumFaults`] takes the faults out of the body before the read. +//! (measured 2026-11-13, 2026-11-14, 2026-11-17 and 2026-11-18, us-east-1). +//! So [`EnumFaults`] takes the faults out of the body before the read. //! //! The typed read takes a structure written as a JSON array and an enum //! written as a JSON object, which the service refuses while it reads the @@ -26,6 +28,27 @@ const PROJECTION_TYPES: &[&str] = &["ALL", "INCLUDE", "KEYS_ONLY"]; /// The values of `StreamViewType`, in the service's order. const STREAM_VIEW_TYPES: &[&str] = &["OLD_IMAGE", "KEYS_ONLY", "NEW_AND_OLD_IMAGES", "NEW_IMAGE"]; +/// The values of `SSEType`, in the service's order. +const SSE_TYPES: &[&str] = &["AES256", "KMS"]; + +/// The values of `TableClass`, in the service's order. +const TABLE_CLASSES: &[&str] = &["STANDARD", "STANDARD_INFREQUENT_ACCESS"]; + +/// The most characters a `KMSMasterKeyId` may hold. +const KMS_MASTER_KEY_ID_MAX: usize = 2048; + +/// The service's answer to a `TableClass` outside its set. +pub(crate) fn table_class_fault(body: &Value) -> Option { + let sent = body.get("TableClass")?.as_str()?; + (!TABLE_CLASSES.contains(&sent)).then(|| { + DynamoDbError::ValidationException(format!( + "Invalid table-class parameter provided. Please try again with a valid \ + table-class value: [{}].", + TABLE_CLASSES.join(", ") + )) + }) +} + /// The most faults one refusal lists, the first ones in the service's order. /// Its count then says 10 too (measured 2026-12-02 with twelve). The PartiQL /// request checks keep the same number, in a module behind the `partiql` @@ -70,8 +93,8 @@ const ENUMS: &[&str] = &[ "TableThroughputMode", ]; -/// Each member outside its set: the value sent, the member's path and the -/// constraint it fails. +/// Each member outside its set or over its length: the value sent, the +/// member's path and the constraint it fails. #[derive(Default)] pub(crate) struct EnumFaults(Vec<(String, String, String)>); @@ -79,6 +102,7 @@ impl EnumFaults { pub(crate) fn create_table(body: &mut Value) -> Result { let mut faults = Self::default(); faults.projections(body, "GlobalSecondaryIndexes", false); + faults.sse_specification(body); faults.stream_view_type(body); faults.projections(body, "LocalSecondaryIndexes", false); faults.member_types(body) @@ -132,6 +156,27 @@ impl EnumFaults { } } + /// The length of the `KMSMasterKeyId`, which the service counts in + /// characters, then the `SSEType`. + fn sse_specification(&mut self, body: &mut Value) { + if let Some(key) = body + .pointer("/SSESpecification/KMSMasterKeyId") + .and_then(Value::as_str) + && key.chars().count() > KMS_MASTER_KEY_ID_MAX + { + self.0.push(( + key.to_owned(), + "sSESpecification.kMSMasterKeyId".to_owned(), + format!("Member must have length less than or equal to {KMS_MASTER_KEY_ID_MAX}"), + )); + } + self.one_of( + body.pointer_mut("/SSESpecification/SSEType"), + "sSESpecification.sSEType".to_owned(), + SSE_TYPES, + ); + } + fn stream_view_type(&mut self, body: &mut Value) { self.one_of( body.pointer_mut("/StreamSpecification/StreamViewType"), diff --git a/crates/engine/src/nested_enums_tests.rs b/crates/engine/src/nested_enums_tests.rs index 412466a26..0fdf79d2f 100644 --- a/crates/engine/src/nested_enums_tests.rs +++ b/crates/engine/src/nested_enums_tests.rs @@ -4,7 +4,9 @@ //! DynamoDB's answers to `CreateTable` and `UpdateTable` requests with a //! `ProjectionType` or `StreamViewType` outside its set (measured in //! us-east-1 on 2026-11-13 and 2026-11-14, and beside a member of the wrong -//! JSON type on 2026-11-17). +//! JSON type on 2026-11-17), and with a `TableClass` or an +//! `SSESpecification` the service refuses (measured on 2026-11-13, +//! 2026-11-14 and 2026-11-18). use extenddb_core::error::DynamoDbError; use serde_json::{Value, json}; @@ -15,6 +17,10 @@ use crate::partiql::test_context::context; const PROJECTION_SET: &str = "ALL, INCLUDE, KEYS_ONLY"; const VIEW_SET: &str = "OLD_IMAGE, KEYS_ONLY, NEW_AND_OLD_IMAGES, NEW_IMAGE"; const VIEW: &str = "streamSpecification.streamViewType"; +const SSE_SET: &str = "AES256, KMS"; +const SSE_TYPE: &str = "sSESpecification.sSEType"; +const TABLE_CLASS: &str = "Invalid table-class parameter provided. Please try again with a \ + valid table-class value: [STANDARD, STANDARD_INFREQUENT_ACCESS]."; const ONE: &str = "1 validation error detected: "; /// One fault of a `ValidationException` that lists member faults. @@ -29,6 +35,19 @@ fn refused(value: &str, path: &str, set: &str) -> Option { Some(format!("{ONE}{}", clause(value, path, &constraint))) } +/// The service's sentence for an `SSESpecification` whose members do not go +/// together. +fn invalid(reason: &str) -> Option { + Some(format!( + "One or more parameter values were invalid: {reason}" + )) +} + +fn too_long(value: &str, path: &str, max: usize) -> Option { + let constraint = format!("Member must have length less than or equal to {max}"); + Some(format!("{ONE}{}", clause(value, path, &constraint))) +} + /// The faults of `first`, then of `second`, each the text of a /// `ValidationException` with one fault. fn both(first: Option, second: Option) -> Option { @@ -88,6 +107,19 @@ fn stream(enabled: bool, view: &str) -> Value { json!({"StreamSpecification": {"StreamEnabled": enabled, "StreamViewType": view}}) } +/// A `CreateTable` of the issue's table, keyed on `pk` alone, with +/// `members`. +fn plain(members: Value) -> (&'static str, Value) { + create(with( + json!({"AttributeDefinitions": defs(&["pk"])}), + members, + )) +} + +fn sse(spec: Value) -> (&'static str, Value) { + plain(json!({"SSESpecification": spec})) +} + fn rows() -> Vec<((&'static str, Value), Option)> { let bad_gsi = || json!({"GlobalSecondaryIndexes": [index("gsi", "g", "EVERY_ATTRIBUTE")]}); let bad_create = || { @@ -118,6 +150,11 @@ fn rows() -> Vec<((&'static str, Value), Option)> { "ALL_ATTRIBUTES", "globalSecondaryIndexUpdates.1.member.create", ); + let sse_bogus = refused("BOGUS", SSE_TYPE, SSE_SET); + let kms_key = |key: &str| json!({"Enabled": true, "KMSMasterKeyId": key}); + let key_2049 = "k".repeat(2049); + let key_fault = too_long(&key_2049, "sSESpecification.kMSMasterKeyId", 2048); + let name_256 = "t".repeat(256); let mut rows = vec![ ( create(bad_gsi()), @@ -155,6 +192,118 @@ fn rows() -> Vec<((&'static str, Value), Option)> { create(stream(true, "NEW_IMAGES")), refused("NEW_IMAGES", VIEW, VIEW_SET), ), + // A `TableClass` or an `SSESpecification` the service refuses. + ( + sse(json!({"Enabled": true, "SSEType": "AES256"})), + invalid("SSEType AES256 is not supported"), + ), + ( + sse(json!({"Enabled": false, "SSEType": "KMS"})), + invalid("SSEType can not be specified if Enabled is false"), + ), + ( + sse(kms_key("alias/no-such-key")), + invalid("SSEType KMS is required if KMSMasterKeyId is specified"), + ), + ( + sse(json!({"Enabled": false, "KMSMasterKeyId": "alias/no-such-key"})), + invalid("KMSMasterKeyId can not be specified if Enabled is false"), + ), + ( + sse(json!({"Enabled": true, "SSEType": "KMS", "KMSMasterKeyId": key_2049})), + key_fault.clone(), + ), + // The service lists the key's length ahead of the SSEType. + ( + sse(json!({"Enabled": true, "SSEType": "BOGUS", "KMSMasterKeyId": key_2049})), + both(key_fault.clone(), sse_bogus.clone()), + ), + // The service counts the key's length in characters. + ( + sse(kms_key(&"k".repeat(2048))), + invalid("SSEType KMS is required if KMSMasterKeyId is specified"), + ), + ( + sse(kms_key(&"\u{1F600}".repeat(1025))), + invalid("SSEType KMS is required if KMSMasterKeyId is specified"), + ), + ( + create(with( + bad_gsi(), + json!({"SSESpecification": {"Enabled": true, "SSEType": "BOGUS"}}), + )), + both(gsi_fault.clone(), sse_bogus.clone()), + ), + ( + plain(with( + stream(true, "NEW_IMAGES"), + json!({"SSESpecification": {"Enabled": true, "SSEType": "BOGUS"}}), + )), + both(sse_bogus.clone(), refused("NEW_IMAGES", VIEW, VIEW_SET)), + ), + ( + create(with( + bad_gsi(), + json!({"SSESpecification": {"Enabled": true, "SSEType": "AES256"}}), + )), + gsi_fault.clone(), + ), + ( + plain(json!({"TableClass": "STANDARD_IA"})), + Some(TABLE_CLASS.to_owned()), + ), + ( + plain(json!({"BillingMode": "ON_DEMAND", "TableClass": "PAY_PER_REQUEST"})), + Some(TABLE_CLASS.to_owned()), + ), + ( + create(with(bad_gsi(), json!({"TableClass": "BOGUS"}))), + Some(TABLE_CLASS.to_owned()), + ), + ( + plain(json!({"TableName": name_256, "TableClass": "BOGUS"})), + too_long(&name_256, "tableName", 255), + ), + (plain(json!({"TableClass": "BOGUS", "Tags": "x"})), None), + ( + update(json!({"TableClass": "STANDARD_IA"})), + Some(TABLE_CLASS.to_owned()), + ), + ( + update(json!({"BillingMode": "ALSO_BOGUS", "TableClass": "BOGUS"})), + Some(TABLE_CLASS.to_owned()), + ), + ( + update(json!({"TableClass": "BOGUS", "AttributeDefinitions": "x"})), + None, + ), + // UpdateTable checks the table name first too (measured 2026-12-02). + ( + update(json!({"TableName": name_256, "TableClass": "BOGUS"})), + too_long(&name_256, "tableName", 255), + ), + ( + update(json!({"TableName": "ab", "TableClass": "BOGUS"})), + Some(format!( + "{ONE}{}", + clause( + "ab", + "tableName", + "Member must have length greater than or equal to 3" + ) + )), + ), + ( + update(json!({"TableName": "tr04 bad!", "TableClass": "BOGUS"})), + Some(format!( + "{ONE}{}", + clause( + "tr04 bad!", + "tableName", + "Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+" + ) + )), + ), ]; for view in ["NEW_AND_OLD_IMAGE", "keys_only", "", "TOTAL"] { rows.push((update(stream(true, view)), refused(view, VIEW, VIEW_SET))); @@ -307,6 +456,37 @@ fn rows() -> Vec<((&'static str, Value), Option)> { ] { rows.push(((operation, body), None)); } + for sse_type in ["BOGUS", "AES"] { + rows.push(( + sse(json!({"Enabled": true, "SSEType": sse_type})), + refused(sse_type, SSE_TYPE, SSE_SET), + )); + } + // An Enabled written as a string reads as a boolean, in any ASCII case, + // and another string is refused. The service reads these strings so on + // UpdateTable (measured 2026-12-02). These CreateTable rows assume the + // same read; no CreateTable was sent. + let disabled = invalid("SSEType can not be specified if Enabled is false"); + let aes256 = invalid("SSEType AES256 is not supported"); + for (enabled, sse_type, expected) in [ + ("false", "KMS", disabled.clone()), + ("FALSE", "KMS", disabled.clone()), + ("False", "KMS", disabled.clone()), + ("no", "KMS", disabled.clone()), + ("f", "KMS", disabled.clone()), + ("0", "KMS", disabled.clone()), + ("N", "KMS", disabled), + ("TRUE", "AES256", aes256.clone()), + ("true", "AES256", aes256.clone()), + ("t", "AES256", aes256.clone()), + ("1", "AES256", aes256), + ("", "KMS", None), + ("on", "KMS", None), + ("maybe", "KMS", None), + ] { + let spec = json!({"Enabled": enabled, "SSEType": sse_type}); + rows.push((sse(spec), expected)); + } rows } @@ -327,3 +507,40 @@ async fn refused_enum_members() { } } } + +/// The table stores an Enabled written as a string as the boolean the checks +/// read, so CreateTable and DescribeTable report the same encryption. Another +/// string gets the service's text. +#[tokio::test] +async fn sse_enabled_string_is_stored_as_read() { + let dir = tempfile::TempDir::new().unwrap(); + let ctx = crate::test_context::catalog_context(&dir).await; + for (name, spec, sse_type) in [ + ( + "sse-true", + json!({"Enabled": "TRUE", "SSEType": "KMS"}), + Some("KMS"), + ), + ("sse-no", json!({"Enabled": "no"}), None), + ] { + let (operation, mut body) = sse(spec); + body["TableName"] = json!(name); + let created = dispatch(operation, body, &ctx, "") + .await + .expect("CreateTable"); + let table = dispatch("DescribeTable", json!({"TableName": name}), &ctx, "") + .await + .expect("DescribeTable"); + for described in [&created.body["TableDescription"], &table.body["Table"]] { + let sse = described["SSEDescription"].get("SSEType"); + assert_eq!(sse.and_then(Value::as_str), sse_type, "{described}"); + } + } + let (operation, body) = sse(json!({"Enabled": "on", "SSEType": "KMS"})); + match dispatch(operation, body, &ctx, "").await.map(|r| r.body) { + Err(DynamoDbError::SerializationException(m)) => { + assert_eq!(m, "Unexpected token received from parser"); + } + other => panic!("CreateTable answered {other:?}"), + } +} diff --git a/crates/engine/src/query_key_values.rs b/crates/engine/src/query_key_values.rs index 8dd925af3..f2296b355 100644 --- a/crates/engine/src/query_key_values.rs +++ b/crates/engine/src/query_key_values.rs @@ -220,6 +220,15 @@ pub(crate) fn shape_fault_first( .unwrap_or(check) } +/// The boolean the service reads `text` as (see [`BOOLEAN_TEXTS`]), or +/// `None` for a string it refuses. +pub(crate) fn boolean_text(text: &str) -> Option { + let at = BOOLEAN_TEXTS + .iter() + .position(|word| word.eq_ignore_ascii_case(text))?; + Some(at < 5) +} + /// The strings the service reads as a boolean, in any ASCII case: the first /// five as true, the others as false. It refuses every other string with /// `SerializationException`. Measured 2026-11-10 for each of them in diff --git a/crates/engine/src/search_vectors_order_tests.rs b/crates/engine/src/search_vectors_order_tests.rs index d4343475a..042518424 100644 --- a/crates/engine/src/search_vectors_order_tests.rs +++ b/crates/engine/src/search_vectors_order_tests.rs @@ -16,39 +16,10 @@ use std::time::Duration; use serde_json::{Value, json}; use extenddb_core::error::DynamoDbError; -use extenddb_storage::server_components::ServerComponentsOptions; -use extenddb_storage_sqlite::SqliteConfig; use tempfile::TempDir; use crate::OperationContext; - -/// A context on a bootstrapped SQLite catalog in `dir`, where a table is -/// created ACTIVE. -async fn context(dir: &TempDir) -> OperationContext { - let config = SqliteConfig { - path: dir.path().join("catalog.sqlite").display().to_string(), - pool_size: 2, - }; - let mut options = ServerComponentsOptions::default(); - options.bootstrap_if_uninitialized = true; - options.release = "test"; - let components = - (extenddb_storage_sqlite::backend().server_components)(&config, "us-east-1", options) - .await - .unwrap_or_else(|e| panic!("server components: {e:?}")); - let account_id = components - .catalog_store - .default_account_id() - .await - .unwrap() - .expect("the bootstrapped account"); - components - .catalog_store - .set_setting("control_plane_delay_seconds", "0") - .await - .unwrap(); - crate::test_context::context_on(components.engine, &account_id) -} +use crate::test_context::catalog_context; /// A table "tbl" with a four-dimension vector index "vix" whose HASH element /// is `Country`, once the index serves searches. @@ -122,7 +93,7 @@ fn us() -> Option { #[tokio::test] async fn an_empty_map_answers_before_a_missing_table() { let dir = TempDir::new().unwrap(); - let ctx = context(&dir).await; + let ctx = catalog_context(&dir).await; let values_empty = answer(&ctx, request("missing", 4, Some(json!({})), None)).await; assert!( validation("ExpressionAttributeValues must not be empty")(&values_empty), @@ -143,7 +114,7 @@ async fn an_empty_map_answers_before_a_missing_table() { #[tokio::test] async fn an_empty_map_answers_before_a_dimension_mismatch() { let dir = TempDir::new().unwrap(); - let ctx = context(&dir).await; + let ctx = catalog_context(&dir).await; table(&ctx).await; let values_empty = answer(&ctx, request("tbl", 2, Some(json!({})), None)).await; assert!( @@ -176,7 +147,7 @@ async fn an_empty_map_answers_before_a_dimension_mismatch() { #[tokio::test] async fn the_size_counts_a_name_at_each_use_before_a_missing_table() { let dir = TempDir::new().unwrap(); - let ctx = context(&dir).await; + let ctx = catalog_context(&dir).await; let body = |conditions: usize| { let mut body = request("missing", 4, us(), Some(json!({"#x0": "x".repeat(65_533)}))); body["ExpressionAttributeValues"] = json!({":s": {"S": "US"}}); diff --git a/crates/engine/src/test_context.rs b/crates/engine/src/test_context.rs index 6999fd528..d6a055d5c 100644 --- a/crates/engine/src/test_context.rs +++ b/crates/engine/src/test_context.rs @@ -2,14 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 //! The storage engine and the [`OperationContext`] that the engine's unit -//! tests build: an empty in-memory SQLite database, and a context on a given -//! engine with no item authorizer and no authorized keys. +//! tests build: an empty in-memory SQLite database, a context on a given +//! engine with no item authorizer and no authorized keys, and a context on +//! a bootstrapped SQLite catalog. use std::sync::Arc; use extenddb_core::limits::LimitsConfig; use extenddb_storage::StorageEngine; -use extenddb_storage_sqlite::SqliteEngine; +use extenddb_storage::server_components::ServerComponentsOptions; +use extenddb_storage_sqlite::{SqliteConfig, SqliteEngine}; +use tempfile::TempDir; use crate::{AuthorizedKeyInfo, BackupRuntime, OperationContext}; @@ -39,3 +42,31 @@ pub(crate) fn context_on(storage: Arc, account_id: &str) -> O item_authorizer: None, } } + +/// A context on a bootstrapped SQLite catalog in `dir`, where a table is +/// created ACTIVE. +pub(crate) async fn catalog_context(dir: &TempDir) -> OperationContext { + let config = SqliteConfig { + path: dir.path().join("catalog.sqlite").display().to_string(), + pool_size: 2, + }; + let mut options = ServerComponentsOptions::default(); + options.bootstrap_if_uninitialized = true; + options.release = "test"; + let components = + (extenddb_storage_sqlite::backend().server_components)(&config, "us-east-1", options) + .await + .unwrap_or_else(|e| panic!("server components: {e:?}")); + let account_id = components + .catalog_store + .default_account_id() + .await + .unwrap() + .expect("the bootstrapped account"); + components + .catalog_store + .set_setting("control_plane_delay_seconds", "0") + .await + .unwrap(); + context_on(components.engine, &account_id) +} diff --git a/crates/engine/src/update_table.rs b/crates/engine/src/update_table.rs index 65a69d2e7..52c24587d 100755 --- a/crates/engine/src/update_table.rs +++ b/crates/engine/src/update_table.rs @@ -28,7 +28,9 @@ pub async fn handle_update_table( ctx: &OperationContext, ) -> Result { // Per-member enum validation precedes everything else, including the table - // lookup, matching the measured service ordering. + // lookup, matching the measured service ordering. The service answers a + // TableClass outside its set ahead of the BillingMode fault. + let table_class = crate::nested_enums::table_class_fault(&body); crate::validate_enum_fields( &body, &[ @@ -43,12 +45,19 @@ pub async fn handle_update_table( clause: crate::EnumClause::Named("tableThroughputMode"), }, ], - )?; + ) + .map_err(|e| table_class.clone().unwrap_or(e))?; crate::require_stream_enabled_member(&body)?; let enum_faults = crate::nested_enums::EnumFaults::update_table(&mut body)?; let mut input: UpdateTableInput = serde_json::from_value(body).map_err(crate::deserialize_error)?; + // The service checks the table name before it answers the table class + // fault, as on CreateTable (measured 2026-12-02). + if let Some(fault) = table_class { + extenddb_core::validation::validate_table_name(&input.table_name, &ctx.limits)?; + return Err(fault); + } enum_faults.check()?; input.resolve_table_throughput_mode(); diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 1a32ce7c0..559f37cc9 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -425,6 +425,20 @@ deployment, even when no catalog migration is required. **Who is affected.** A client, a test or an alarm that expects `SerializationException` for such an enum value, or that sends `ReplicaUpdates` in another form. No catalog migration or configuration change is required. After a rollback to 1.1.0, these requests get the 1.1.0 answers again. +### v1.2.0: CreateTable refuses the `SSESpecification` values that DynamoDB refuses, and CreateTable and UpdateTable refuse a `TableClass` outside its set + +**What changed** (#1114). Each refusal below is an HTTP 400 `ValidationException` with DynamoDB's text (measured 2026-11-13 to 2026-11-18). 1.1.0 created the table for each of the `SSESpecification` requests. + +- An `SSEType` outside `[AES256, KMS]` and a `KMSMasterKeyId` of more than 2048 characters are member faults. They go into one `N validation errors detected` message with the other member faults. +- `{"Enabled": true, "SSEType": "AES256"}` gets `One or more parameter values were invalid: SSEType AES256 is not supported`. +- An `SSEType` with `Enabled` false gets `One or more parameter values were invalid: SSEType can not be specified if Enabled is false`. A `KMSMasterKeyId` with `Enabled` false gets the same sentence with `KMSMasterKeyId` in place of `SSEType`. +- A `KMSMasterKeyId` with `Enabled` true and no `SSEType` `KMS` gets `One or more parameter values were invalid: SSEType KMS is required if KMSMasterKeyId is specified`. +- On CreateTable and UpdateTable, a `TableClass` outside `[STANDARD, STANDARD_INFREQUENT_ACCESS]` gets `Invalid table-class parameter provided. Please try again with a valid table-class value: [STANDARD, STANDARD_INFREQUENT_ACCESS].` 1.1.0 created or updated the table with that value, or answered another fault. + +CreateTable also reads an `Enabled` written as a string. In any ASCII case, `"true"`, `"t"`, `"yes"`, `"y"` and `"1"` are true, and `"false"`, `"f"`, `"no"`, `"n"` and `"0"` are false. So `{"Enabled": "true", "SSEType": "KMS"}` creates a table with encryption, where 1.1.0 created one without. Another string, such as `"on"`, gets `SerializationException` with `Unexpected token received from parser`. This is how DynamoDB's UpdateTable read these strings. On 2026-12-02 it read `"TRUE"`, `"true"`, `"t"` and `"1"` as true, read `"FALSE"`, `"False"`, `"false"`, `"no"`, `"f"`, `"0"` and `"N"` as false, and refused `""`, `"on"` and `"maybe"`. On 2026-12-03 it read `"yes"` and `"y"` as true and `"n"` as false. The other ASCII cases of the ten strings come from other boolean members that DynamoDB reads the same way, such as `ConsistentRead` (measured 2026-11-10 to 2026-11-23). DynamoDB's CreateTable was not sent an `Enabled` string. + +**Who is affected.** A client that sends one of these requests, or that sends `Enabled` as a string. A table that 1.1.0 created with a `TableClass` outside the set keeps it after the upgrade. No catalog migration or configuration change is required. After a rollback to 1.1.0, these requests get the 1.1.0 answers again. + ### v1.1.0: latency `segments` are summed into time buckets **What changed** (#398). The latency `segments` that `/metrics` and the console's `/console/metrics-data` return come from time buckets per account and operation. 1.0.0 kept one record per request for 24 hours. Each operation's count and means are still exact over the requests that the window covers. Four things change: diff --git a/tests/test_table_enum_members.py b/tests/test_table_enum_members.py index 3635169fe..86ca935eb 100644 --- a/tests/test_table_enum_members.py +++ b/tests/test_table_enum_members.py @@ -1,11 +1,12 @@ # Copyright 2026 ExtendDB contributors # SPDX-License-Identifier: Apache-2.0 -"""CreateTable and UpdateTable refuse a ProjectionType or StreamViewType outside its set. +"""CreateTable and UpdateTable refuse members outside their sets. Measured against Amazon DynamoDB in us-east-1 on 13 and 14 Nov 2026, and beside another such member or a member of the wrong JSON type on 17 and 18 -Nov and 2 Dec 2026. Each request went out twice with the same answer. +Nov and 2 Dec 2026. The TableClass and SSESpecification rows were measured on +13, 14 and 18 Nov 2026. Each request went out twice with the same answer. - The service answers ``ValidationException`` with the enum text, the member path and the set in its own order, at most ten faults. @@ -14,6 +15,16 @@ object. Its text there, such as "Unexpected field type", is not the text ExtendDB sends, so these rows check the exception only. +- A TableClass outside its set gets the service's own sentence. A member of + the wrong JSON type and a table name of a bad length or a bad character + answer ahead of it, on CreateTable and on UpdateTable. + It answers ahead of every member fault. +- CreateTable refuses an SSEType outside its set and a KMSMasterKeyId of + more than 2048 characters with the other member faults. After them it + refuses an SSESpecification whose members do not go together. + It reads an Enabled written as a string as the service's UpdateTable + reads one, and records that boolean. No CreateTable with such a string + was sent to the service, so those rows do not run against it. - UpdateTable refuses before it looks up the table. After a refused CreateTable no table exists. After a refused UpdateTable the table has no stream, and the same UpdateTable with ``NEW_IMAGE`` enables one. @@ -29,13 +40,17 @@ import boto3 import pytest -from conftest import wait_for_active, wait_for_deleted +from conftest import _is_real_dynamodb, wait_for_active, wait_for_deleted from raw_signed_request import signed_post REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") SERIALIZATION = "SerializationException" PROJECTION_SET = "[ALL, INCLUDE, KEYS_ONLY]" VIEW_SET = "[OLD_IMAGE, KEYS_ONLY, NEW_AND_OLD_IMAGES, NEW_IMAGE]" +SSE_SET = "[AES256, KMS]" +SSE_TYPE = "sSESpecification.sSEType" +TABLE_CLASS = ("Invalid table-class parameter provided. Please try again with a valid " + "table-class value: [STANDARD, STANDARD_INFREQUENT_ACCESS].") ONE = "1 validation error detected: " @@ -47,11 +62,19 @@ def _refused(value: str, path: str, values: str) -> str: return ONE + _clause(value, path, f"Member must satisfy enum value set: {values}") +def _too_long(value: str, path: str, most: int) -> str: + return ONE + _clause(value, path, f"Member must have length less than or equal to {most}") + + def _both(first: str, second: str) -> str: """The faults of two texts with one fault each, in that order.""" return f"2 validation errors detected: {first.removeprefix(ONE)}; {second.removeprefix(ONE)}" +def _invalid(reason: str) -> str: + return f"One or more parameter values were invalid: {reason}" + + def _projection(value: str, member: str) -> str: return _refused(value, f"{member}.projection.projectionType", PROJECTION_SET) @@ -216,6 +239,81 @@ def _stream(enabled: bool, view: str) -> dict: ] ] +# A TableClass or an SSESpecification the service refuses. PLAIN is the +# table keyed on pk alone. The rows with "name" in their id send their own +# TableName. +PLAIN = {**TABLE, "AttributeDefinitions": _defs("pk")} +SSE_BOGUS = _refused("BOGUS", SSE_TYPE, SSE_SET) +KEY_2049 = "k" * 2049 +KEY_FAULT = _too_long(KEY_2049, "sSESpecification.kMSMasterKeyId", 2048) +NAME_256 = "t" * 256 +KMS_REQUIRED = _invalid("SSEType KMS is required if KMSMasterKeyId is specified") + + +def _sse(**spec) -> dict: + return {**PLAIN, "SSESpecification": spec} + + +ROWS += [ + ("ct-sse-aes256", "CreateTable", _sse(Enabled=True, SSEType="AES256"), + _invalid("SSEType AES256 is not supported")), + ("ct-sse-bogus", "CreateTable", _sse(Enabled=True, SSEType="BOGUS"), SSE_BOGUS), + ("ct-sse-aes", "CreateTable", _sse(Enabled=True, SSEType="AES"), + _refused("AES", SSE_TYPE, SSE_SET)), + ("ct-sse-type-disabled", "CreateTable", _sse(Enabled=False, SSEType="KMS"), + _invalid("SSEType can not be specified if Enabled is false")), + ("ct-sse-key-without-type", "CreateTable", + _sse(Enabled=True, KMSMasterKeyId="alias/no-such-key"), KMS_REQUIRED), + ("ct-sse-key-disabled", "CreateTable", + _sse(Enabled=False, KMSMasterKeyId="alias/no-such-key"), + _invalid("KMSMasterKeyId can not be specified if Enabled is false")), + ("ct-sse-key-2049", "CreateTable", + _sse(Enabled=True, SSEType="KMS", KMSMasterKeyId=KEY_2049), KEY_FAULT), + # The service lists the key's length ahead of the SSEType. + ("ct-sse-bogus-key-2049", "CreateTable", + _sse(Enabled=True, SSEType="BOGUS", KMSMasterKeyId=KEY_2049), _both(KEY_FAULT, SSE_BOGUS)), + # The service counts the key's length in characters. + ("ct-sse-key-2048", "CreateTable", _sse(Enabled=True, KMSMasterKeyId="k" * 2048), + KMS_REQUIRED), + ("ct-sse-key-1025-emoji", "CreateTable", + _sse(Enabled=True, KMSMasterKeyId="\U0001F600" * 1025), KMS_REQUIRED), + ("ct-sse-bogus-gsi", "CreateTable", + {**TABLE, "GlobalSecondaryIndexes": BAD_GSI, + "SSESpecification": {"Enabled": True, "SSEType": "BOGUS"}}, + _both(GSI_FAULT, SSE_BOGUS)), + ("ct-sse-bogus-stream", "CreateTable", + {**_sse(Enabled=True, SSEType="BOGUS"), "StreamSpecification": _stream(True, "NEW_IMAGES")}, + _both(SSE_BOGUS, _view("NEW_IMAGES"))), + ("ct-sse-aes256-gsi", "CreateTable", + {**TABLE, "GlobalSecondaryIndexes": BAD_GSI, + "SSESpecification": {"Enabled": True, "SSEType": "AES256"}}, + GSI_FAULT), + ("ct-table-class", "CreateTable", {**PLAIN, "TableClass": "STANDARD_IA"}, TABLE_CLASS), + ("ct-table-class-billing", "CreateTable", + {**PLAIN, "BillingMode": "ON_DEMAND", "TableClass": "PAY_PER_REQUEST"}, TABLE_CLASS), + ("ct-table-class-gsi", "CreateTable", + {**TABLE, "GlobalSecondaryIndexes": BAD_GSI, "TableClass": "BOGUS"}, TABLE_CLASS), + ("ct-table-class-name", "CreateTable", + {**PLAIN, "TableName": NAME_256, "TableClass": "BOGUS"}, + _too_long(NAME_256, "tableName", 255)), + ("ct-table-class-tags", "CreateTable", {**PLAIN, "TableClass": "BOGUS", "Tags": "x"}, + SERIALIZATION), + ("ut-table-class", "UpdateTable", {"TableClass": "STANDARD_IA"}, TABLE_CLASS), + ("ut-table-class-billing", "UpdateTable", + {"BillingMode": "ALSO_BOGUS", "TableClass": "BOGUS"}, TABLE_CLASS), + ("ut-table-class-defs", "UpdateTable", + {"TableClass": "BOGUS", "AttributeDefinitions": "x"}, SERIALIZATION), + # UpdateTable checks the table name first too (measured 2 Dec 2026). + ("ut-table-class-name", "UpdateTable", {"TableName": NAME_256, "TableClass": "BOGUS"}, + _too_long(NAME_256, "tableName", 255)), + ("ut-table-class-short-name", "UpdateTable", {"TableName": "ab", "TableClass": "BOGUS"}, + ONE + _clause("ab", "tableName", "Member must have length greater than or equal to 3")), + ("ut-table-class-name-chars", "UpdateTable", + {"TableName": "tr04 bad!", "TableClass": "BOGUS"}, + ONE + _clause("tr04 bad!", "tableName", + "Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+")), +] + @pytest.fixture(scope="module") def post(endpoint_url): @@ -282,3 +380,27 @@ def test_refused_update_leaves_existing_table_without_stream( arn = dynamodb_client.describe_table(TableName=unique_table_name)["Table"]["LatestStreamArn"] streams = _streams(endpoint_url, unique_table_name) assert [s["StreamArn"] for s in streams] == [arn], streams + + +# ExtendDB's answers, not the service's: DynamoDB's UpdateTable reads these +# strings as true and false (measured 2 and 3 Dec 2026), and no CreateTable +# with them was sent to it. +@pytest.mark.skipif(_is_real_dynamodb(), reason="extenddb_only: CreateTable not measured") +@pytest.mark.parametrize( + ("spec", "expected"), + [pytest.param({"Enabled": "TRUE", "SSEType": "KMS"}, ("ENABLED", "KMS"), id="true-kms"), + pytest.param({"Enabled": "no"}, None, id="no")], +) +def test_sse_enabled_string_creates_the_table(dynamodb_client, unique_table_name, post, spec, + expected): + resp = post("CreateTable", {"TableName": unique_table_name, **PLAIN, + "SSESpecification": spec}) + assert resp.status_code == 200, resp.text + try: + wait_for_active(dynamodb_client, unique_table_name) + table = dynamodb_client.describe_table(TableName=unique_table_name)["Table"] + finally: + dynamodb_client.delete_table(TableName=unique_table_name) + wait_for_deleted(dynamodb_client, unique_table_name) + for sse in (resp.json()["TableDescription"].get("SSEDescription"), table.get("SSEDescription")): + assert (sse and (sse.get("Status"), sse.get("SSEType"))) == expected, sse