Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(ddb): key att enforcement + fix tests (#1445)
Nahuel Nucera5cbf88695300
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.pyindex 3c9f7ffd..f4072c32 100644--- a/ministack/services/dynamodb.py+++ b/ministack/services/dynamodb.py@@ -1289,6 +1289,20 @@ def _update_table(data):return error_response_json("ResourceNotFoundException", f"Requested resource not found: Table: {name} not found", 400)table = _tables[name]+ # UpdateTable must carry at least one actionable change. AttributeDefinitions+ # on its own is rejected by AWS (and no API can change a key attribute's+ # type — MiniStack used to merge it in and silently mutate the key). #1432+ _ACTIONABLE_UPDATE_PARAMS = (+ "ProvisionedThroughput", "BillingMode", "GlobalSecondaryIndexUpdates",+ "StreamSpecification", "SSESpecification", "ReplicaUpdates", "TableClass",+ "OnDemandThroughput", "DeletionProtectionEnabled", "WarmThroughput",+ )+ if not any(k in data for k in _ACTIONABLE_UPDATE_PARAMS):+ return error_response_json("ValidationException",+ "At least one of ProvisionedThroughput, BillingMode, UpdateStreamEnabled, "+ "GlobalSecondaryIndexUpdates, SSESpecification, ReplicaUpdates or TableClass "+ "is required", 400)+current_billing = table.get("BillingModeSummary", {}).get("BillingMode", "PROVISIONED")new_billing = data.get("BillingMode")# ProvisionedThroughput validation when supplied.@@ -1636,6 +1650,12 @@ def _put_item(data):if table.get("sk_name") and table["sk_name"] not in item:return error_response_json("ValidationException",f"One or more parameter values were invalid: Missing the key {table['sk_name']} in the item", 400)+ # A key attribute present with the wrong type is a ValidationException on+ # PutItem, as on UpdateItem/GetItem/TransactWrite (real AWS: "Type mismatch+ # for key <name> expected: <S> actual: <N>").+ type_msg = _key_type_mismatch_reason(table, item)+ if type_msg:+ return error_response_json("ValidationException", type_msg, 400)pk_val = _extract_key_val(item.get(table["pk_name"]))sk_val = _extract_key_val(item.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"old_item = table["items"].get(pk_val, {}).get(sk_val)@@ -2040,6 +2060,19 @@ def _query(data):if pk_val is None:return error_response_json("ValidationException",f"Query condition missed key schema element: {pk_name}", 400)+ # A key-condition value whose type does not match the key's schema type is+ # rejected, as on real AWS ("Condition parameter type does not match schema+ # type") — MiniStack used to accept N for an S key and return the row.+ for _kn in (pk_name, sk_name):+ if not _kn:+ continue+ _av = _key_condition_av(key_cond, key_conditions, eav, ean, _kn)+ if isinstance(_av, dict) and len(_av) == 1:+ _expected = _get_attr_type(table, _kn)+ if _expected and next(iter(_av)) != _expected:+ return error_response_json("ValidationException",+ "One or more parameter values were invalid: Condition "+ "parameter type does not match schema type", 400)# Reject non-key attributes in KeyConditionExpression: every bare identifier# in the expression must be either the hash key or the sort key (resolved# via ExpressionAttributeNames if aliased).@@ -5981,6 +6014,32 @@ def _extract_pk_from_condition(condition, attr_values, attr_names, pk_name):return None+def _key_condition_av(condition, key_conditions, eav, attr_names, key_name):+ """The typed AttributeValue bound to ``key_name`` in a Query key condition,+ for the type-vs-schema check. Covers legacy KeyConditions and the+ KeyConditionExpression forms (``key <op> :v`` / ``:v = key``,+ ``begins_with(key, :v)``, ``key BETWEEN :lo AND :hi``); returns the first+ bound value, which is enough to catch a type mismatch."""+ if key_conditions:+ cond = key_conditions.get(key_name)+ if isinstance(cond, dict):+ avl = cond.get("AttributeValueList") or []+ return avl[0] if avl else None+ return None+ if not condition:+ return None+ refs = [key_name] + [a for a, r in attr_names.items() if r == key_name]+ for ref in refs:+ for pat in (rf'(?:^|[\s(]){re.escape(ref)}\s*(?:<=|>=|=|<|>)\s*(:\w+)',+ rf'(:\w+)\s*(?:<=|>=|=|<|>)\s*{re.escape(ref)}(?:$|[\s)])',+ rf'begins_with\s*\(\s*{re.escape(ref)}\s*,\s*(:\w+)\s*\)',+ rf'{re.escape(ref)}\s+BETWEEN\s+(:\w+)'):+ m = re.search(pat, condition, re.I)+ if m and m.group(1) in eav:+ return eav[m.group(1)]+ return None++# ---------------------------------------------------------------------------# Pagination helpers# ---------------------------------------------------------------------------diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex e622619c..acaf8f0b 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -2873,6 +2873,7 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):etag = f'"{md5_hash(body)}"'obj = _build_object_record(body, headers, etag=etag, checksums=checksums)+ obj["preserved_headers"].update(sse_headers)prior_obj = bucket["objects"].get(key)bucket["objects"][key] = obj@@ -2894,7 +2895,7 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):)resp_headers = {"ETag": obj["etag"], "Content-Length": "0"}- resp_headers.update(_bucket_default_sse_headers(bucket_name))+ resp_headers.update(sse_headers)version_id = _record_object_version(bucket_name, key, prior_obj, obj, body)if version_id:resp_headers["x-amz-version-id"] = version_id@@ -3072,8 +3073,20 @@ def _post_object(bucket_name: str, body: bytes, headers: dict):if canned_acl and canned_acl not in _CANNED_OBJECT_ACLS:return _error("InvalidArgument", f"Invalid x-amz-acl value: {canned_acl}", 400)+ # The POST form names its SSE fields exactly like the request headers.+ sse_fields = {h: fields[h] for h in (+ "x-amz-server-side-encryption",+ "x-amz-server-side-encryption-aws-kms-key-id",+ "x-amz-server-side-encryption-customer-algorithm",+ "x-amz-server-side-encryption-customer-key",+ "x-amz-server-side-encryption-customer-key-md5") if h in fields}+ sse_headers, sse_err = _resolve_sse_write_headers(sse_fields, bucket_name)+ if sse_err:+ return sse_err+etag = f'"{md5_hash(file_value)}"'obj = _build_object_record(file_value, synth, etag=etag)+ obj["preserved_headers"].update(sse_headers)prior_obj = bucket["objects"].get(key)bucket["objects"][key] = obj_apply_object_lock_from_headers(bucket_name, key, synth)@@ -5202,6 +5215,14 @@ def _complete_multipart_upload(f"/{bucket_name}/{key}",)+ # An SSE-C upload's completion must present the create-time key again, as+ # every part did; a plain upload's completion must present none. (The+ # idempotent replay above deliberately skips this — the original request+ # already presented the key when it committed.)+ sse_part_err = _check_sse_c_part(headers or {}, upload)+ if sse_part_err is not None:+ return sse_part_err+# CompleteMultipartUpload takes the same If-Match / If-None-Match# preconditions PutObject does, evaluated against the current object at# complete time. (The idempotent replay above deliberately skips them —diff --git a/tests/conftest.py b/tests/conftest.pyindex 4ad01dc3..3a96c57e 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -172,6 +172,52 @@ _SERIAL_TESTS = {"tests/test_iot_data.py::test_iot_rule_where_topic_function_under_basic_ingest","tests/test_iot_data.py::test_iot_rule_where_or_clause_dispatches_either_branch","tests/test_iot_data.py::test_iot_jitr_registration_event_drives_a_topic_rule",+ # WS/MQTT-broker tests (MQTT-over-WebSocket connect/publish/subscribe,+ # device shadows over MQTT, fleet-index connectivity). They drive the+ # single-event-loop broker over real WebSocket connections with tight+ # ready-event / delivery-window timing, so cross-file xdist pressure on the+ # shared server slips a handshake or a delivery and one of them fails at+ # random. Correct serially; run them in the dedicated serial phase.+ "tests/test_iot_data.py::test_iot_lambda_publishes_browser_subscribes_e2e",+ "tests/test_iot_data.py::test_iot_ws_publish_isolated_between_regions",+ "tests/test_iot_data.py::test_iot_ws_credential_region_wildcards_cannot_bypass_isolation",+ "tests/test_iot_data.py::test_iot_ws_topic_isolation_between_accounts",+ "tests/test_iot_data.py::test_iot_ws_same_account_publish_delivers",+ "tests/test_iot_data.py::test_iot_rule_republish_where_gated_ws_subscriber",+ "tests/test_iot_data.py::test_search_index_finds_connected_thing_and_loses_it_on_disconnect",+ "tests/test_iot_data.py::test_search_index_connectivity_timestamp_moves_on_disconnect",+ "tests/test_iot_data.py::test_search_index_connectivity_is_tied_to_the_client_id",+ "tests/test_iot_data.py::test_search_index_connectivity_reports_a_dropped_transport",+ "tests/test_iot_data.py::test_search_index_reports_duplicate_client_id_after_a_takeover",+ "tests/test_iot_data.py::test_search_index_connectivity_is_isolated_across_accounts_and_regions",+ "tests/test_iot_data.py::test_shadow_update_over_mqtt_emits_accepted_delta_documents",+ "tests/test_iot_data.py::test_named_shadow_update_over_mqtt",+ "tests/test_iot_data.py::test_shadow_get_missing_over_mqtt_rejected_404",+ "tests/test_iot_data.py::test_shadow_accepted_drives_topic_rule_republish",+ "tests/test_iot_data.py::test_mqtt5_connect_is_accepted_with_properties",+ "tests/test_iot_data.py::test_mqtt311_connack_is_byte_identical",+ "tests/test_iot_data.py::test_unsupported_protocol_level_is_refused",+ "tests/test_iot_data.py::test_mqtt5_empty_client_id_gets_assigned_identifier",+ "tests/test_iot_data.py::test_mqtt5_unknown_property_is_ignored",+ "tests/test_iot_data.py::test_mqtt5_subscribe_options_byte_gets_v5_suback",+ "tests/test_iot_data.py::test_mqtt5_publish_round_trip_forwards_properties",+ "tests/test_iot_data.py::test_mqtt311_publisher_reaches_mqtt5_subscriber",+ "tests/test_iot_data.py::test_mqtt5_publisher_reaches_mqtt311_subscriber",+ "tests/test_iot_data.py::test_mqtt5_qos1_puback_carries_reason_code",+ "tests/test_iot_data.py::test_mqtt311_qos1_puback_stays_two_bytes",+ "tests/test_iot_data.py::test_mqtt5_unsuback_reason_codes_follow_the_actual_removal",+ "tests/test_iot_data.py::test_mqtt311_unsuback_stays_two_bytes",+ "tests/test_iot_data.py::test_mqtt5_disconnect_with_reason_code_closes_cleanly",+ "tests/test_iot_data.py::test_mqtt5_property_value_running_past_the_block_is_refused",+ "tests/test_iot_data.py::test_mqtt5_property_block_truncated_at_the_packet_end_is_refused",+ "tests/test_iot_data.py::test_mqtt5_malformed_connect_is_refused_with_a_connack_reason_code",+ "tests/test_iot_data.py::test_mqtt5_property_block_longer_than_127_bytes_round_trips",+ "tests/test_iot_data.py::test_mqtt5_no_local_withholds_a_publisher_its_own_message",+ "tests/test_iot_data.py::test_mqtt5_retain_as_published_keeps_the_publishers_retain_flag",+ "tests/test_iot_data.py::test_mqtt5_retain_handling_2_suppresses_the_retained_replay",+ "tests/test_iot_data.py::test_mqtt5_retain_handling_1_replays_only_for_a_new_subscription",+ "tests/test_iot_data.py::test_mqtt5_will_with_properties_fires_on_transport_drop",+ "tests/test_iot_data.py::test_mqtt5_malformed_will_properties_answer_connack_0x81",}diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.pyindex 7932c69a..30348a12 100644--- a/tests/test_dynamodb.py+++ b/tests/test_dynamodb.py@@ -1040,6 +1040,71 @@ def test_dynamodb_get_item_wrong_key_type_fails_validation(ddb):assert exc.value.response["Error"]["Code"] == "ValidationException"assert exc.value.response["Error"]["Message"] == "The provided key element does not match the schema"+def test_dynamodb_put_item_wrong_key_type_fails_validation(ddb):+ """PutItem with a key attribute typed against its schema is rejected (#1432)."""+ try:+ ddb.delete_table(TableName="t_put_wrong_type")+ except Exception:+ pass+ ddb.create_table(+ TableName="t_put_wrong_type",+ KeySchema=[{"AttributeName": "device", "KeyType": "HASH"},+ {"AttributeName": "ts", "KeyType": "RANGE"}],+ AttributeDefinitions=[{"AttributeName": "device", "AttributeType": "S"},+ {"AttributeName": "ts", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ with pytest.raises(ClientError) as exc:+ ddb.put_item(TableName="t_put_wrong_type",+ Item={"device": {"S": "d1"}, "ts": {"N": "123"}})+ assert exc.value.response["Error"]["Code"] == "ValidationException"+ assert exc.value.response["Error"]["Message"] == (+ "One or more parameter values were invalid: "+ "Type mismatch for key ts expected: S actual: N")++def test_dynamodb_query_wrong_key_condition_type_fails_validation(ddb):+ """Query whose key-condition value type mismatches the schema is rejected (#1432)."""+ try:+ ddb.delete_table(TableName="t_query_wrong_type")+ except Exception:+ pass+ ddb.create_table(+ TableName="t_query_wrong_type",+ KeySchema=[{"AttributeName": "device", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "device", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ ddb.put_item(TableName="t_query_wrong_type", Item={"device": {"S": "d1"}})+ with pytest.raises(ClientError) as exc:+ ddb.query(TableName="t_query_wrong_type",+ KeyConditionExpression="device = :v",+ ExpressionAttributeValues={":v": {"N": "1"}})+ assert exc.value.response["Error"]["Code"] == "ValidationException"+ assert "Condition parameter type does not match schema type" in \+ exc.value.response["Error"]["Message"]++def test_dynamodb_update_table_attribute_definitions_only_is_rejected(ddb):+ """UpdateTable with only AttributeDefinitions (no actionable change, and no+ API can alter a key's type) is rejected (#1432)."""+ try:+ ddb.delete_table(TableName="t_upd_attrdefs")+ except Exception:+ pass+ ddb.create_table(+ TableName="t_upd_attrdefs",+ KeySchema=[{"AttributeName": "ts", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "ts", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ with pytest.raises(ClientError) as exc:+ ddb.update_table(TableName="t_upd_attrdefs",+ AttributeDefinitions=[{"AttributeName": "ts", "AttributeType": "N"}])+ assert exc.value.response["Error"]["Code"] == "ValidationException"+ assert "At least one of" in exc.value.response["Error"]["Message"]+ # The key type must be unchanged.+ desc = ddb.describe_table(TableName="t_upd_attrdefs")["Table"]+ assert {a["AttributeName"]: a["AttributeType"] for a in desc["AttributeDefinitions"]}["ts"] == "S"+def test_dynamodb_update_item_extra_key_attribute_fails_validation(ddb):try:ddb.delete_table(TableName="t_update_extra_key")