Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(tf): acm validation (#1257)

Nahuel Nucerae3ee3766754a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 528735bd..7bcd83b4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,9 +7,13 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+- **CloudFront — cache policies** — `CreateCachePolicy`, `GetCachePolicy`, `GetCachePolicyConfig`, `UpdateCachePolicy`, `DeleteCachePolicy`, and `ListDistributionsByCachePolicyId` under `/2020-05-31/cache-policy`, so Terraform's `aws_cloudfront_cache_policy` creates, reads, updates, and deletes end-to-end. The full `CachePolicyConfig` round-trips — `MinTTL`/`DefaultTTL`/`MaxTTL` and `ParametersInCacheKeyAndForwardedToOrigin` with the gzip/brotli flags and the header/cookie/query-string behaviors and name lists — with `ETag` on every read, `If-Match` enforced on update/delete (`InvalidIfMatchVersion` / `PreconditionFailed`), and `CachePolicyAlreadyExists` / `NoSuchCachePolicy` / `CachePolicyInUse` errors matching AWS. Reported by @wparad.
+
### Fixed
- **IoT — binary topic-rule payloads are no longer corrupted** — the rules engine built every rule event by decoding the payload as UTF-8 with `errors="replace"`, so a payload that is not valid UTF-8 reached the action with each non-ASCII byte replaced by `U+FFFD`. `encode(<expr>, 'base64')` is now supported and encodes the payload as published, so `SELECT encode(*, 'base64') AS data FROM 'telemetry'` delivers `{"data": "<base64>"}` that decodes back to the published bytes — the documented way to reach a Lambda action, which does not accept binary input. No lossy decode remains on the publish → rule → invoke path; a payload that is not valid UTF-8 and whose SELECT projects no attributes dispatches no action rather than dispatching corrupted text.
- **IoT — topic-rule SQL is now evaluated** — the rules engine routed a publish to its actions but ignored the rule's `SELECT` clause, so a rule declaring `SELECT deviceId AS id FROM 'sensors/+/telemetry'` delivered the whole message instead of the projection. The SELECT clause is now parsed and projected — `*`, attribute paths, `AS` aliases, `topic()` / `topic(n)`, `timestamp()`, and literals, with unaliased items named as AWS names them and missing attributes omitted — for both delivery paths, Basic Ingest (where `topic()` reports the topic after the rule prefix) and a publish matching the `FROM` filter. A JSON payload under `SELECT *` still arrives as the parsed object.
+- **ACM — wildcard SAN DNS validation record now matches its base domain** — a certificate with a wildcard subject alternative name emitted a validation `ResourceRecord` named `_acme-challenge.*.example.com`, so Terraform's `aws_acm_certificate_validation` never found the record its `aws_route53_record` had created and failed with `missing DNS validation record`. Real ACM strips the leading `*.`, so `*.example.com` and `example.com` share one `_acme-challenge.example.com` CNAME with an identical name and value. `RequestCertificate` now emits that collapsed record, so the wildcard and apex entries line up and the validation resource resolves. Reported by @wparad.
## [1.4.9] — 2026-08-01
diff --git a/ministack/services/acm.py b/ministack/services/acm.py
index 77ff2bc3..bef5ae66 100644
--- a/ministack/services/acm.py
+++ b/ministack/services/acm.py
@@ -8,6 +8,7 @@ Supports: RequestCertificate, DescribeCertificate, ListCertificates,
"""
import copy
+import hashlib
import json
import logging
import os
@@ -178,14 +179,23 @@ def _certificate_not_found(arn):
def _validation_options(domain, method):
+ # A wildcard SAN validates through the same DNS record as its base domain:
+ # real ACM strips the leading "*." so "*.example.com" and "example.com"
+ # both resolve to a single _acme-challenge.example.com CNAME whose name AND
+ # value are identical. Terraform's aws_route53_record for_each keyed by
+ # domain_validation_options then collapses the two onto one record, and
+ # aws_acm_certificate_validation finds the FQDN it created (#1250). The
+ # value is derived from the base domain so the wildcard/apex pair match.
+ base = domain[2:] if domain.startswith("*.") else domain
+ digest = hashlib.sha256(base.encode("utf-8")).hexdigest()[:8]
return {
"DomainName": domain,
"ValidationMethod": method,
"ValidationStatus": "SUCCESS",
"ResourceRecord": {
- "Name": f"_acme-challenge.{domain}.",
+ "Name": f"_acme-challenge.{base}.",
"Type": "CNAME",
- "Value": f"fake-validation-{new_uuid()[:8]}.acm.amazonaws.com.",
+ "Value": f"fake-validation-{digest}.acm.amazonaws.com.",
},
}
diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.py
index 1cb7e8cb..deb18ddf 100644
--- a/ministack/services/cloudfront.py
+++ b/ministack/services/cloudfront.py
@@ -61,6 +61,11 @@ _FUN_NAME_RE = re.compile(r"^/2020-05-31/function/([^/]+)/?$")
_KVS_LIST_RE = re.compile(r"^/2020-05-31/key-value-store/?$")
_KVS_NAME_RE = re.compile(r"^/2020-05-31/key-value-store/([^/]+)/?$")
+_CACHE_POLICY_RE = re.compile(r"^/2020-05-31/cache-policy/?$")
+_CACHE_POLICY_CFG_RE = re.compile(r"^/2020-05-31/cache-policy/([^/]+)/config$")
+_CACHE_POLICY_ID_RE = re.compile(r"^/2020-05-31/cache-policy/([^/]+)/?$")
+_DIST_BY_CACHE_POLICY_RE = re.compile(r"^/2020-05-31/distributionsByCachePolicyId/([^/]+)/?$")
+
# ---------------------------------------------------------------------------
# In-memory state
# ---------------------------------------------------------------------------
@@ -70,6 +75,7 @@ _tags = AccountScopedDict() # arn -> [{"Key": ..., "Value": ...}]
_oacs = AccountScopedDict() # Id -> OAC record
_functions = AccountScopedDict() # Name -> function record (CloudFront Functions API)
_kvstores = AccountScopedDict() # Name -> KVS record
+_cache_policies = AccountScopedDict() # Id -> cache policy record
def reset():
@@ -79,6 +85,7 @@ def reset():
_oacs.clear()
_functions.clear()
_kvstores.clear()
+ _cache_policies.clear()
def get_state():
@@ -90,6 +97,7 @@ def get_state():
"oacs": _oacs,
"functions": _functions,
"kvstores": _kvstores,
+ "cache_policies": _cache_policies,
}
)
@@ -101,6 +109,7 @@ def restore_state(data):
_oacs.update(data.get("oacs", {}))
_functions.update(data.get("functions", {}))
_kvstores.update(data.get("kvstores", {}))
+ _cache_policies.update(data.get("cache_policies", {}))
try:
@@ -663,6 +672,266 @@ def _cf_delete_function(name: str, headers):
return 204, {}, b""
+# ---------------------------------------------------------------------------
+# Cache policies (Terraform aws_cloudfront_cache_policy)
+# Shapes verified against botocore cloudfront service-2.json (2020-05-31).
+# ---------------------------------------------------------------------------
+
+_CACHE_HEADER_BEHAVIORS = {"none", "whitelist"}
+_CACHE_COOKIE_BEHAVIORS = {"none", "whitelist", "allExcept", "all"}
+_CACHE_QUERYSTRING_BEHAVIORS = {"none", "whitelist", "allExcept", "all"}
+
+
+def _parse_name_items(block_el, names_tag):
+ """Pull <Items><Name>..</Name></Items> out of a Headers/Cookies/QueryStrings block."""
+ names = _find(block_el, names_tag) if block_el is not None else None
+ items = []
+ if names is not None:
+ items_el = _find(names, "Items")
+ if items_el is not None:
+ for child in items_el:
+ local = child.tag.split("}")[-1] if "}" in child.tag else child.tag
+ if local == "Name":
+ items.append(child.text or "")
+ return items
+
+
+def _parse_cache_policy_config(el):
+ """Parse a <CachePolicyConfig> element into a stored dict, or return an _error tuple."""
+ name = _text(el, "Name")
+ if not name:
+ return None, _error("InvalidArgument", "The cache policy name is required.", 400)
+
+ min_ttl_el = _find(el, "MinTTL")
+ if min_ttl_el is None or not (min_ttl_el.text or "").strip():
+ return None, _error("InvalidArgument", "The MinTTL value is required.", 400)
+ try:
+ min_ttl = int(min_ttl_el.text)
+ except (TypeError, ValueError):
+ return None, _error("InvalidArgument", "The MinTTL value is not valid.", 400)
+
+ cfg = {"Name": name, "Comment": _text(el, "Comment"), "MinTTL": min_ttl}
+ for opt in ("DefaultTTL", "MaxTTL"):
+ opt_el = _find(el, opt)
+ if opt_el is not None and (opt_el.text or "").strip():
+ try:
+ cfg[opt] = int(opt_el.text)
+ except (TypeError, ValueError):
+ return None, _error("InvalidArgument", f"The {opt} value is not valid.", 400)
+
+ params_el = _find(el, "ParametersInCacheKeyAndForwardedToOrigin")
+ if params_el is not None:
+ headers_cfg = _find(params_el, "HeadersConfig")
+ cookies_cfg = _find(params_el, "CookiesConfig")
+ qs_cfg = _find(params_el, "QueryStringsConfig")
+ if headers_cfg is None or cookies_cfg is None or qs_cfg is None:
+ return None, _error(
+ "InvalidArgument",
+ "HeadersConfig, CookiesConfig, and QueryStringsConfig are required.",
+ 400,
+ )
+ header_behavior = _text(headers_cfg, "HeaderBehavior")
+ cookie_behavior = _text(cookies_cfg, "CookieBehavior")
+ qs_behavior = _text(qs_cfg, "QueryStringBehavior")
+ if header_behavior not in _CACHE_HEADER_BEHAVIORS:
+ return None, _error("InvalidArgument", "Invalid HeaderBehavior value.", 400)
+ if cookie_behavior not in _CACHE_COOKIE_BEHAVIORS:
+ return None, _error("InvalidArgument", "Invalid CookieBehavior value.", 400)
+ if qs_behavior not in _CACHE_QUERYSTRING_BEHAVIORS:
+ return None, _error("InvalidArgument", "Invalid QueryStringBehavior value.", 400)
+ gzip_el = _find(params_el, "EnableAcceptEncodingGzip")
+ if gzip_el is None:
+ return None, _error("InvalidArgument", "EnableAcceptEncodingGzip is required.", 400)
+ cfg["Parameters"] = {
+ "EnableAcceptEncodingGzip": (gzip_el.text or "").strip().lower() == "true",
+ "EnableAcceptEncodingBrotli": _text(params_el, "EnableAcceptEncodingBrotli").strip().lower() == "true",
+ "HeaderBehavior": header_behavior,
+ "Headers": _parse_name_items(headers_cfg, "Headers"),
+ "CookieBehavior": cookie_behavior,
+ "Cookies": _parse_name_items(cookies_cfg, "Cookies"),
+ "QueryStringBehavior": qs_behavior,
+ "QueryStrings": _parse_name_items(qs_cfg, "QueryStrings"),
+ }
+ return cfg, None
+
+
+def _build_names_block(parent, names_tag, items):
+ block = SubElement(parent, names_tag)
+ SubElement(block, "Quantity").text = str(len(items))
+ if items:
+ items_el = SubElement(block, "Items")
+ for it in items:
+ SubElement(items_el, "Name").text = it
+
+
+def _build_cache_policy_config_xml(parent, cfg):
+ SubElement(parent, "Comment").text = cfg.get("Comment", "")
+ SubElement(parent, "Name").text = cfg["Name"]
+ # AWS fills the documented defaults when the caller omits these.
+ SubElement(parent, "DefaultTTL").text = str(cfg.get("DefaultTTL", 86400))
+ SubElement(parent, "MaxTTL").text = str(cfg.get("MaxTTL", 31536000))
+ SubElement(parent, "MinTTL").text = str(cfg["MinTTL"])
+ params = cfg.get("Parameters")
+ if params is not None:
+ p_el = SubElement(parent, "ParametersInCacheKeyAndForwardedToOrigin")
+ SubElement(p_el, "EnableAcceptEncodingGzip").text = "true" if params["EnableAcceptEncodingGzip"] else "false"
+ SubElement(p_el, "EnableAcceptEncodingBrotli").text = "true" if params["EnableAcceptEncodingBrotli"] else "false"
+ hc = SubElement(p_el, "HeadersConfig")
+ SubElement(hc, "HeaderBehavior").text = params["HeaderBehavior"]
+ _build_names_block(hc, "Headers", params["Headers"])
+ cc = SubElement(p_el, "CookiesConfig")
+ SubElement(cc, "CookieBehavior").text = params["CookieBehavior"]
+ _build_names_block(cc, "Cookies", params["Cookies"])
+ qc = SubElement(p_el, "QueryStringsConfig")
+ SubElement(qc, "QueryStringBehavior").text = params["QueryStringBehavior"]
+ _build_names_block(qc, "QueryStrings", params["QueryStrings"])
+
+
+def _build_cache_policy_xml(parent, policy):
+ SubElement(parent, "Id").text = policy["Id"]
+ SubElement(parent, "LastModifiedTime").text = policy["LastModifiedTime"]
+ cfg_el = SubElement(parent, "CachePolicyConfig")
+ _build_cache_policy_config_xml(cfg_el, policy["Config"])
+
+
+def _value_contains(obj, target):
+ """Best-effort recursive search for a policy Id anywhere in a distribution record."""
+ if isinstance(obj, str):
+ return obj == target
+ if isinstance(obj, dict):
+ return any(_value_contains(v, target) for v in obj.values())
+ if isinstance(obj, (list, tuple)):
+ return any(_value_contains(v, target) for v in obj)
+ return False
+
+
+def _distributions_using_cache_policy(policy_id):
+ return [d.get("Id", "") for d in _distributions.values() if _value_contains(d, policy_id)]
+
+
+def _create_cache_policy(body):
+ el = _parse_body(body)
+ if el is None:
+ return _error("MalformedXML", "The XML document is malformed.", 400)
+ cfg, err = _parse_cache_policy_config(el)
+ if err is not None:
+ return err
+ for existing in _cache_policies.values():
+ if existing["Config"]["Name"] == cfg["Name"]:
+ return _error("CachePolicyAlreadyExists", "A cache policy with the same name already exists.", 409)
+ policy_id = new_uuid()
+ etag = new_uuid()
+ policy = {"Id": policy_id, "ETag": etag, "LastModifiedTime": _now_iso(), "Config": cfg}
+ _cache_policies[policy_id] = policy
+ logger.info("CreateCachePolicy id=%s name=%s", policy_id, cfg["Name"])
+
+ def build(root):
+ _build_cache_policy_xml(root, policy)
+
+ return _xml_response(
+ "CachePolicy", build, status=201,
+ extra_headers={"ETag": etag, "Location": f"/2020-05-31/cache-policy/{policy_id}"},
+ )
+
+
+def _get_cache_policy(policy_id):
+ policy = _cache_policies.get(policy_id)
+ if not policy:
+ return _error("NoSuchCachePolicy", "The cache policy does not exist.", 404)
+
+ def build(root):
+ _build_cache_policy_xml(root, policy)
+
+ return _xml_response("CachePolicy", build, extra_headers={"ETag": policy["ETag"]})
+
+
+def _get_cache_policy_config(policy_id):
+ policy = _cache_policies.get(policy_id)
+ if not policy:
+ return _error("NoSuchCachePolicy", "The cache policy does not exist.", 404)
+
+ def build(root):
+ _build_cache_policy_config_xml(root, policy["Config"])
+
+ return _xml_response("CachePolicyConfig", build, extra_headers={"ETag": policy["ETag"]})
+
+
+def _update_cache_policy(policy_id, headers, body):
+ policy = _cache_policies.get(policy_id)
+ if not policy:
+ return _error("NoSuchCachePolicy", "The cache policy does not exist.", 404)
+ if_match = headers.get("if-match")
+ if not if_match:
+ return _error("InvalidIfMatchVersion", "The If-Match version is missing or not valid for the resource.", 400)
+ if if_match != policy["ETag"]:
+ return _error(
+ "PreconditionFailed",
+ "The precondition given in one or more of the request-header fields evaluated to false.",
+ 412,
+ )
+ el = _parse_body(body)
+ if el is None:
+ return _error("MalformedXML", "The XML document is malformed.", 400)
+ cfg, err = _parse_cache_policy_config(el)
+ if err is not None:
+ return err
+ for existing in _cache_policies.values():
+ if existing["Id"] != policy_id and existing["Config"]["Name"] == cfg["Name"]:
+ return _error("CachePolicyAlreadyExists", "A cache policy with the same name already exists.", 409)
+ new_etag = new_uuid()
+ policy["Config"] = cfg
+ policy["ETag"] = new_etag
+ policy["LastModifiedTime"] = _now_iso()
+ logger.info("UpdateCachePolicy id=%s name=%s", policy_id, cfg["Name"])
+
+ def build(root):
+ _build_cache_policy_xml(root, policy)
+
+ return _xml_response("CachePolicy", build, extra_headers={"ETag": new_etag})
+
+
+def _delete_cache_policy(policy_id, headers):
+ policy = _cache_policies.get(policy_id)
+ if not policy:
+ return _error("NoSuchCachePolicy", "The cache policy does not exist.", 404)
+ if_match = headers.get("if-match")
+ if not if_match:
+ return _error("InvalidIfMatchVersion", "The If-Match version is missing or not valid for the resource.", 400)
+ if if_match != policy["ETag"]:
+ return _error(
+ "PreconditionFailed",
+ "The precondition given in one or more of the request-header fields evaluated to false.",
+ 412,
+ )
+ if _distributions_using_cache_policy(policy_id):
+ return _error(
+ "CachePolicyInUse",
+ "The cache policy cannot be deleted because it is attached to one or more cache behaviors.",
+ 409,
+ )
+ del _cache_policies[policy_id]
+ logger.info("DeleteCachePolicy id=%s", policy_id)
+ return 204, {}, b""
+
+
+def _list_distributions_by_cache_policy(policy_id):
+ if not _cache_policies.get(policy_id):
+ return _error("NoSuchCachePolicy", "The cache policy does not exist.", 404)
+ dist_ids = _distributions_using_cache_policy(policy_id)
+
+ def build(root):
+ SubElement(root, "Marker").text = ""
+ SubElement(root, "MaxItems").text = "100"
+ SubElement(root, "IsTruncated").text = "false"
+ SubElement(root, "Quantity").text = str(len(dist_ids))
+ if dist_ids:
+ items_el = SubElement(root, "Items")
+ for did in dist_ids:
+ SubElement(items_el, "DistributionId").text = did
+
+ return _xml_response("DistributionIdList", build)
+
+
# ---------------------------------------------------------------------------
# Request dispatcher
# ---------------------------------------------------------------------------
@@ -752,6 +1021,32 @@ async def handle_request(method, path, headers, body, query_params):
if method == "DELETE":
return _delete_oac(oac_id, headers)
+ # Cache policy routes
+ m = _CACHE_POLICY_CFG_RE.match(path)
+ if m:
+ if method == "GET":
+ return _get_cache_policy_config(m.group(1))
+
+ m = _CACHE_POLICY_RE.match(path)
+ if m:
+ if method == "POST":
+ return _create_cache_policy(body)
+
+ m = _CACHE_POLICY_ID_RE.match(path)
+ if m:
+ policy_id = m.group(1)
+ if method == "GET":
+ return _get_cache_policy(policy_id)
+ if method == "PUT":
+ return _update_cache_policy(policy_id, headers, body)
+ if method == "DELETE":
+ return _delete_cache_policy(policy_id, headers)
+
+ m = _DIST_BY_CACHE_POLICY_RE.match(path)
+ if m:
+ if method == "GET":
+ return _list_distributions_by_cache_policy(m.group(1))
+
# CloudFront Functions API (used by Terraform aws_cloudfront_function)
m = _FUN_DESCRIBE_RE.match(path)
if m:
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index 6f1ee180..acd44895 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -2199,6 +2199,9 @@ def _scan(data):
# LSI: items lacking the index's RANGE attribute don't appear.
if sk_name_idx:
all_items = [it for it in all_items if sk_name_idx in it]
+ # Sort by index key ordering so ESK/LEK pagination is consistent.
+ sort_keys = _index_order_keys(table, sk_name_idx)
+ all_items.sort(key=lambda it: tuple(_index_order_value(it, n, t) for n, t in sort_keys))
# Parallel scan: partition items deterministically across segments by
# hashing the partition key. AWS guarantees segments return disjoint
@@ -2230,7 +2233,13 @@ def _scan(data):
if not required.issubset(esk.keys()):
return error_response_json("ValidationException",
"The provided starting key is invalid: The provided key element does not match the schema", 400)
- all_items = _apply_exclusive_start_key_scan(all_items, esk, table)
+ if index_name:
+ # For index scans, use index-aware ordering (same as Query pagination).
+ all_items = _apply_exclusive_start_key(
+ all_items, esk, pk_name_idx, sk_name_idx, scan_forward=True, table=table
+ )
+ else:
+ all_items = _apply_exclusive_start_key_scan(all_items, esk, table)
# Same LastEvaluatedKey semantics as Query: stopping exactly at the limit
# still yields a key, because AWS doesn't look ahead.
@@ -2268,7 +2277,12 @@ def _scan(data):
}
if has_more and all_items:
- result["LastEvaluatedKey"] = _build_key(all_items[-1], table["pk_name"], table["sk_name"])
+ lek = _build_key(all_items[-1], table["pk_name"], table["sk_name"])
+ if index_name:
+ ik = _build_key(all_items[-1], pk_name_idx, sk_name_idx)
+ for k, v in ik.items():
+ lek.setdefault(k, v)
+ result["LastEvaluatedKey"] = lek
_add_consumed_capacity(result, data, name)
return json_response(result)
@@ -2391,14 +2405,41 @@ def _partiql_key_target(table, parsed):
if pk_typed is None or (sk_attr and sk_typed is None):
return None, None, None, error_response_json(
"ValidationException",
- "WHERE clause must specify every primary key attribute with equality.",
+ "Where clause does not contain a mandatory equality on all key attributes",
400,
)
def non_key_fn(item):
+ # Each predicate is a fail-fast check: on a pass we fall through to the
+ # next condition rather than returning, so every predicate in a
+ # multi-condition WHERE is evaluated (not just the first special op).
for attr, op, val in rest:
- if not _compare_ddb(item.get(attr), op, val):
- return False
+ if op == "begins_with":
+ iv = item.get(attr)
+ if iv is None or "S" not in iv:
+ return False
+ prefix = val.get("S", "") if isinstance(val, dict) else str(val)
+ if not iv["S"].startswith(prefix):
+ return False
+ elif op == "not_begins_with":
+ iv = item.get(attr)
+ if iv is not None and "S" in iv:
+ prefix = val.get("S", "") if isinstance(val, dict) else str(val)
+ if iv["S"].startswith(prefix):
+ return False
+ elif op == "is_missing":
+ if item.get(attr) is not None:
+ return False
+ elif op == "is_not_missing":
+ if item.get(attr) is None:
+ return False
+ elif op == "IN":
+ iv = item.get(attr)
+ if iv is None or not any(_ddb_equals(iv, v) for v in val):
+ return False
+ else:
+ if not _compare_ddb(item.get(attr), op, val):
+ return False
return True
pk_key = _extract_key_val(pk_typed)
@@ -2406,46 +2447,132 @@ def _partiql_key_target(table, parsed):
return pk_key, sk_key, non_key_fn, None
+def _build_partiql_returning(item_before, item_after, returning_clause):
+ """Build the Items list for a RETURNING clause response.
+
+ Supported: ALL OLD *, ALL NEW *, MODIFIED OLD *, MODIFIED NEW *
+ Returns (items_list, error_or_None)
+ """
+ if not returning_clause:
+ return [], None
+ r = returning_clause.upper().strip()
+ if r == "ALL OLD *":
+ return [item_before] if item_before else [], None
+ elif r == "ALL NEW *":
+ return [item_after] if item_after else [], None
+ elif r == "MODIFIED NEW *":
+ if not item_before or not item_after:
+ return [], None
+ changed = {k: v for k, v in item_after.items()
+ if k not in item_before or item_before[k] != v}
+ return [changed] if changed else [], None
+ elif r == "MODIFIED OLD *":
+ if not item_before or not item_after:
+ return [], None
+ changed = {k: item_before[k] for k in item_before
+ if k not in item_after or item_after[k] != item_before[k]}
+ return [changed] if changed else [], None
+ else:
+ return None, f"Invalid returning clause: {returning_clause}"
+
+
def _partiql_update(table, parsed):
set_attrs = parsed.get("set_attrs", {})
- if not parsed.get("where_fn") or not set_attrs:
+ remove_attrs = parsed.get("remove_attrs", [])
+ returning = parsed.get("returning")
+
+ if not parsed.get("where_fn") and not parsed.get("conditions"):
+ return error_response_json("ValidationException",
+ "UPDATE requires a WHERE clause", 400)
+ if not set_attrs and not remove_attrs:
return error_response_json("ValidationException",
- "UPDATE requires SET and WHERE clauses", 400)
+ "UPDATE requires SET or REMOVE clause", 400)
+
+ # Validate RETURNING clause
+ if returning:
+ valid_returning = {"ALL OLD *", "ALL NEW *", "MODIFIED OLD *", "MODIFIED NEW *"}
+ if returning.upper().strip() not in valid_returning:
+ return error_response_json("ValidationException",
+ f"Invalid returning clause: RETURNING {returning} is not supported", 400)
pk_key, sk_key, non_key_fn, err = _partiql_key_target(table, parsed)
if err:
return err
item = table["items"].get(pk_key, {}).get(sk_key)
- if item is None or not non_key_fn(item):
+ # UPDATE on a missing key → ConditionalCheckFailedException (not upsert).
+ if item is None:
+ return _conditional_check_failed({}, None)
+ if not non_key_fn(item):
return _conditional_check_failed({}, item)
+ item_before = copy.deepcopy(item) if returning else None
for attr, val in set_attrs.items():
- item[attr] = val
- # AWS ExecuteStatement returns {"Items": []} for UPDATE/DELETE (not an
- # empty object). Some SDKs check for the Items key presence.
+ # Handle arithmetic: {"__partiql_arith": {"attr": "n", "op": "+", "val": {"N": "1"}}}
+ if isinstance(val, dict) and "__partiql_arith" in val:
+ arith = val["__partiql_arith"]
+ src_attr = arith["attr"]
+ op = arith["op"]
+ operand = arith["val"]
+ cur = item.get(src_attr)
+ if cur and "N" in cur and "N" in operand:
+ from decimal import Decimal
+ result_n = Decimal(cur["N"]) + Decimal(operand["N"]) if op == "+" else Decimal(cur["N"]) - Decimal(operand["N"])
+ item[attr] = {"N": str(result_n)}
+ else:
+ item[attr] = operand # fallback: just set to operand
+ else:
+ item[attr] = val
+ for attr in remove_attrs:
+ item.pop(attr, None)
+ item_after = item
+
+ if returning:
+ items_list, ret_err = _build_partiql_returning(item_before, item_after, returning)
+ if ret_err:
+ return error_response_json("ValidationException", ret_err, 400)
+ return json_response({"Items": items_list})
return json_response({"Items": []})
def _partiql_delete(table, parsed):
- if not parsed.get("where_fn"):
+ returning = parsed.get("returning")
+ if not parsed.get("where_fn") and not parsed.get("conditions"):
return error_response_json("ValidationException",
"DELETE requires a WHERE clause", 400)
+ # Validate RETURNING clause — DELETE only supports ALL OLD *
+ if returning:
+ r = returning.upper().strip()
+ if r not in ("ALL OLD *",):
+ return error_response_json("ValidationException",
+ f"Only RETURNING ALL OLD * is allowed on DELETE statements; got: RETURNING {returning}", 400)
+
pk_key, sk_key, non_key_fn, err = _partiql_key_target(table, parsed)
if err:
return err
item = table["items"].get(pk_key, {}).get(sk_key)
- if item is None or not non_key_fn(item):
+
+ # If item doesn't exist and there are non-key predicates, that's a silent no-op.
+ # If item doesn't exist and there are NO non-key predicates, also a silent no-op.
+ if item is None:
+ if returning and returning.upper().strip() == "ALL OLD *":
+ return json_response({"Items": []})
+ return json_response({"Items": []})
+
+ # Non-key predicate fails → ConditionalCheckFailed
+ if not non_key_fn(item):
return _conditional_check_failed({}, item)
+ item_before = copy.deepcopy(item) if returning else None
del table["items"][pk_key][sk_key]
if not table["items"][pk_key]:
del table["items"][pk_key]
_update_counts(table)
- # AWS ExecuteStatement returns {"Items": []} for UPDATE/DELETE (not an
- # empty object). Some SDKs check for the Items key presence.
+
+ if returning and returning.upper().strip() == "ALL OLD *":
+ return json_response({"Items": [item_before] if item_before else []})
return json_response({"Items": []})
@@ -2468,7 +2595,25 @@ def _batch_execute_statement(data):
rc = data.get("ReturnConsumedCapacity", "NONE")
per_table_units: dict[str, float] = {}
for stmt in statements:
- sub = {"Statement": stmt.get("Statement"), "Parameters": stmt.get("Parameters", [])}
+ raw_stmt = stmt.get("Statement", "")
+ # Pre-check: RETURNING clause in batch is surfaced as per-statement error.
+ import re as _re
+ _ret_match = _re.search(r'\s+RETURNING\s+', raw_stmt, _re.IGNORECASE)
+ if _ret_match:
+ # Check if it's a valid RETURNING variant — invalid ones get ValidationError.
+ _ret_clause = raw_stmt[_ret_match.end():].strip().rstrip(';').strip().upper()
+ _valid_ret = {"ALL OLD *", "ALL NEW *", "MODIFIED OLD *", "MODIFIED NEW *"}
+ # For DELETE, only ALL OLD * is valid.
+ _is_delete = raw_stmt.strip().upper().startswith("DELETE")
+ if _is_delete and _ret_clause not in ("ALL OLD *",):
+ responses.append({"Error": {"Code": "ValidationError",
+ "Message": f"Only RETURNING ALL OLD * is allowed on DELETE statements"}})
+ continue
+ if _ret_clause not in _valid_ret:
+ responses.append({"Error": {"Code": "ValidationError",
+ "Message": f"Invalid RETURNING clause: {_ret_clause}"}})
+ continue
+ sub = {"Statement": raw_stmt, "Parameters": stmt.get("Parameters", [])}
status, _, body = _execute_statement(sub)
try:
payload = json.loads(body)
@@ -2476,23 +2621,26 @@ def _batch_execute_statement(data):
payload = {}
if status == 200:
entry: dict = {}
- if payload.get("Items") is not None:
- entry["Item"] = payload["Items"][0] if payload["Items"] else None
- if entry.get("Item") is None and "Item" in entry:
- entry.pop("Item")
+ items = payload.get("Items")
+ if items is not None:
+ # RETURNING responses: include the item if present
+ if items:
+ entry["Item"] = items[0]
responses.append(entry)
else:
err_code = payload.get("__type", "ValidationException")
err_msg = payload.get("message", "")
- # Per-statement error code in BatchExecuteStatement is the short
- # form ('ResourceNotFound', not 'ResourceNotFoundException').
+ # Per-statement error code: AWS uses "ValidationError" for validation
+ # errors, and the short name (sans Exception) for other errors.
short = err_code.split("#")[-1]
- if short.endswith("Exception"):
+ if short == "ValidationException":
+ short = "ValidationError"
+ elif short.endswith("Exception"):
short = short[: -len("Exception")]
responses.append({"Error": {"Code": short, "Message": err_msg}})
- # Crude per-table unit attribution.
+ # Per-table unit attribution.
try:
- parsed = _parse_partiql(stmt.get("Statement", ""), stmt.get("Parameters", []))
+ parsed = _parse_partiql(raw_stmt, stmt.get("Parameters", []))
per_table_units[parsed["table"]] = per_table_units.get(parsed["table"], 0.0) + 1.0
except Exception:
pass
@@ -2539,6 +2687,11 @@ def _execute_transaction(data):
for stmt in statements:
statement = stmt.get("Statement", "")
parameters = stmt.get("Parameters", [])
+ # RETURNING clause is not allowed in transaction statements.
+ import re as _re2
+ if _re2.search(r'\s+RETURNING\s+', statement, _re2.IGNORECASE):
+ return error_response_json("ValidationException",
+ "RETURNING clause is not supported in TransactStatement", 400)
try:
parsed = _parse_partiql(statement, parameters)
except ValueError as e:
@@ -2680,36 +2833,70 @@ def _parse_partiql_insert(s, parameters):
def _parse_partiql_update(s, parameters):
import re
- # UPDATE <table> SET <attr>=<val>[,...] WHERE <condition>
+ # UPDATE <table> SET <assignments> [REMOVE <paths>] WHERE <condition> [RETURNING <clause>]
+ # Strip RETURNING clause first (it's always at the end).
+ returning = None
+ ret_match = re.search(r'\s+RETURNING\s+(.+)$', s, re.IGNORECASE)
+ if ret_match:
+ returning = ret_match.group(1).strip()
+ s = s[:ret_match.start()].strip()
+
+ # Try SET ... WHERE form first.
m = re.match(
r"UPDATE\s+\"?([A-Za-z0-9_.\-]+)\"?\s+SET\s+(.+?)\s+WHERE\s+(.+)$",
s, re.IGNORECASE | re.DOTALL,
)
- if not m:
- raise ValueError(f"Could not parse UPDATE statement: {s}")
+ if m:
+ table_name = m.group(1).strip()
+ set_str = m.group(2).strip()
+ where_str = m.group(3).strip()
+ remove_str = None
+ # Check for embedded REMOVE clause within SET string (SET x=v REMOVE y WHERE ...)
+ rem_in_set = re.search(r'\s+REMOVE\s+(.+)$', set_str, re.IGNORECASE)
+ if rem_in_set:
+ remove_str = rem_in_set.group(1).strip()
+ set_str = set_str[:rem_in_set.start()].strip()
+ set_attrs = {}
+ param_idx = [0]
+ for assignment in _split_top_level(set_str, ','):
+ parts = assignment.split("=", 1)
+ if len(parts) != 2:
+ raise ValueError(f"Invalid SET assignment: {assignment}")
+ attr = parts[0].strip().strip('"')
+ val_str = parts[1].strip()
+ set_attrs[attr] = _parse_partiql_literal(val_str, parameters, param_idx)
+ where_fn, conditions = _build_partiql_where(where_str, parameters, param_idx)
+ return {"op": "UPDATE", "table": table_name, "set_attrs": set_attrs,
+ "remove_attrs": [r.strip() for r in remove_str.split(",")] if remove_str else [],
+ "where_fn": where_fn, "conditions": conditions, "returning": returning}
+
+ # Try REMOVE ... WHERE form.
+ m = re.match(
+ r"UPDATE\s+\"?([A-Za-z0-9_.\-]+)\"?\s+REMOVE\s+(.+?)\s+WHERE\s+(.+)$",
+ s, re.IGNORECASE | re.DOTALL,
+ )
+ if m:
+ table_name = m.group(1).strip()
+ remove_str = m.group(2).strip()
+ where_str = m.group(3).strip()
+ param_idx = [0]
+ where_fn, conditions = _build_partiql_where(where_str, parameters, param_idx)
+ return {"op": "UPDATE", "table": table_name, "set_attrs": {},
+ "remove_attrs": [r.strip() for r in remove_str.split(",")],
+ "where_fn": where_fn, "conditions": conditions, "returning": returning}
- table_name = m.group(1).strip()
- set_str = m.group(2).strip()
- where_str = m.group(3).strip()
-
- # Parse SET assignments
- set_attrs = {}
- param_idx = [0]
- for assignment in _split_top_level(set_str, ','):
- parts = assignment.split("=", 1)
- if len(parts) != 2:
- raise ValueError(f"Invalid SET assignment: {assignment}")
- attr = parts[0].strip().strip('"')
- val_str = parts[1].strip()
- set_attrs[attr] = _parse_partiql_literal(val_str, parameters, param_idx)
-
- where_fn, conditions = _build_partiql_where(where_str, parameters, param_idx)
- return {"op": "UPDATE", "table": table_name, "set_attrs": set_attrs,
- "where_fn": where_fn, "conditions": conditions}
+ raise ValueError(f"Could not parse UPDATE statement: {s}")
def _parse_partiql_delete(s, parameters):
import re
+ # Strip RETURNING clause first.
+ returning = None
+ ret_match = re.search(r'\s+RETURNING\s+(.+)$', s, re.IGNORECASE)
+ if ret_match:
+ returning = ret_match.group(1).strip()
+ s = s[:ret_match.start()].strip()
+
# DELETE FROM <table> WHERE <condition>
m = re.match(
r"DELETE\s+FROM\s+\"?([A-Za-z0-9_.\-]+)\"?\s+WHERE\s+(.+)$",
@@ -2717,12 +2904,11 @@ def _parse_partiql_delete(s, parameters):
)
if not m:
raise ValueError(f"Could not parse DELETE statement: {s}")
-
table_name = m.group(1).strip()
where_str = m.group(2).strip()
where_fn, conditions = _build_partiql_where(where_str, parameters)
return {"op": "DELETE", "table": table_name, "where_fn": where_fn,
- "conditions": conditions}
+ "conditions": conditions, "returning": returning}
def _build_partiql_where(where_str, parameters, param_idx=None):
@@ -2735,10 +2921,35 @@ def _build_partiql_where(where_str, parameters, param_idx=None):
conditions = _parse_partiql_conditions(where_str, parameters, param_idx)
def where_fn(item):
+ # Fail-fast per predicate (see non_key_fn): a passing condition falls
+ # through to the next one instead of returning, so every predicate in a
+ # multi-condition WHERE is evaluated regardless of order.
for attr, op, val in conditions:
item_val = item.get(attr)
- if not _compare_ddb(item_val, op, val):
- return False
+ if op == "begins_with":
+ if item_val is None or not isinstance(item_val, dict) or "S" not in item_val:
+ return False
+ prefix = val.get("S", "") if isinstance(val, dict) else str(val)
+ if not item_val["S"].startswith(prefix):
+ return False
+ elif op == "not_begins_with":
+ # missing attribute / non-string → NOT begins_with is True (pass)
+ if item_val is not None and isinstance(item_val, dict) and "S" in item_val:
+ prefix = val.get("S", "") if isinstance(val, dict) else str(val)
+ if item_val["S"].startswith(prefix):
+ return False
+ elif op == "is_missing":
+ if item_val is not None:
+ return False
+ elif op == "is_not_missing":
+ if item_val is None:
+ return False
+ elif op == "IN":
+ if item_val is None or not any(_ddb_equals(item_val, v) for v in val):
+ return False
+ else:
+ if not _compare_ddb(item_val, op, val):
+ return False
return True
return where_fn, conditions
@@ -2748,10 +2959,45 @@ def _parse_partiql_conditions(where_str, parameters, param_idx):
"""Parse WHERE conditions joined by AND. Returns list of (attr, op, ddb_value)."""
import re
conditions = []
- # Split on AND (case-insensitive, word boundary)
- parts = re.split(r'\s+AND\s+', where_str, flags=re.IGNORECASE)
+ # Split on AND (case-insensitive, word boundary) — but not inside parens.
+ parts = _split_top_level_by_and(where_str)
for part in parts:
part = part.strip()
+ # begins_with(attr, val)
+ m = re.match(r'begins_with\s*\(\s*"?([A-Za-z0-9_.\-]+)"?\s*,\s*(.+)\s*\)\s*$', part, re.IGNORECASE)
+ if m:
+ attr = m.group(1)
+ val = _parse_partiql_literal(m.group(2).strip(), parameters, param_idx)
+ conditions.append((attr, "begins_with", val))
+ continue
+ # NOT begins_with(attr, val)
+ m = re.match(r'NOT\s+begins_with\s*\(\s*"?([A-Za-z0-9_.\-]+)"?\s*,\s*(.+)\s*\)\s*$', part, re.IGNORECASE)
+ if m:
+ attr = m.group(1)
+ val = _parse_partiql_literal(m.group(2).strip(), parameters, param_idx)
+ conditions.append((attr, "not_begins_with", val))
+ continue
+ # attr IS MISSING
+ m = re.match(r'"?([A-Za-z0-9_.\-]+)"?\s+IS\s+MISSING\s*$', part, re.IGNORECASE)
+ if m:
+ conditions.append((m.group(1), "is_missing", None))
+ continue
+ # attr IS NOT MISSING
+ m = re.match(r'"?([A-Za-z0-9_.\-]+)"?\s+IS\s+NOT\s+MISSING\s*$', part, re.IGNORECASE)
+ if m:
+ conditions.append((m.group(1), "is_not_missing", None))
+ continue
+ # attr IN ('v1', 'v2', ...)
+ m = re.match(r'"?([A-Za-z0-9_.\-]+)"?\s+IN\s*\[(.+)\]\s*$', part, re.IGNORECASE)
+ if not m:
+ m = re.match(r'"?([A-Za-z0-9_.\-]+)"?\s+IN\s*\((.+)\)\s*$', part, re.IGNORECASE)
+ if m:
+ attr = m.group(1)
+ vals = [_parse_partiql_literal(v.strip(), parameters, param_idx)
+ for v in _split_top_level(m.group(2), ',')]
+ conditions.append((attr, "IN", vals))
+ continue
+ # Standard comparison
m = re.match(r'"?([A-Za-z0-9_.\-]+)"?\s*(=|<>|!=|<=|>=|<|>)\s*(.+)$', part)
if not m:
raise ValueError(f"Could not parse WHERE condition: {part}")
@@ -2765,6 +3011,52 @@ def _parse_partiql_conditions(where_str, parameters, param_idx):
return conditions
+def _split_top_level_by_and(s):
+ """Split a WHERE string on AND at the top level (respecting parens/quotes)."""
+ import re
+ # Use the existing _split_top_level approach but with AND as delimiter
+ parts = []
+ depth = 0
+ in_str = None
+ current = []
+ i = 0
+ s_up = s.upper()
+ while i < len(s):
+ ch = s[i]
+ if in_str:
+ current.append(ch)
+ if ch == in_str:
+ in_str = None
+ i += 1
+ continue
+ if ch in ("'", '"'):
+ in_str = ch
+ current.append(ch)
+ i += 1
+ continue
+ if ch in ('(', '[', '{'):
+ depth += 1
+ current.append(ch)
+ i += 1
+ continue
+ if ch in (')', ']', '}'):
+ depth -= 1
+ current.append(ch)
+ i += 1
+ continue
+ # Check for AND keyword at depth 0
+ if depth == 0 and s_up[i:i+4] == ' AND' and (i + 4 >= len(s) or s[i+4] == ' '):
+ parts.append("".join(current))
+ current = []
+ i += 4 # skip " AND"
+ continue
+ current.append(ch)
+ i += 1
+ if current:
+ parts.append("".join(current))
+ return [p.strip() for p in parts if p.strip()]
+
+
def _parse_partiql_literal(val_str, parameters, param_idx=None):
"""Parse a PartiQL literal or ? parameter reference into a DynamoDB typed value."""
if param_idx is None:
@@ -2800,6 +3092,15 @@ def _parse_partiql_literal(val_str, parameters, param_idx=None):
except (InvalidOperation, ValueError):
pass
+ # Arithmetic expression: attr +/- number (e.g. "n + 1")
+ arith_m = re.match(r'^"?([A-Za-z0-9_.\-]+)"?\s*([+\-])\s*(.+)$', val_str)
+ if arith_m:
+ left_attr = arith_m.group(1)
+ operator = arith_m.group(2)
+ right_str = arith_m.group(3).strip()
+ right_val = _parse_partiql_literal(right_str, parameters, param_idx)
+ return {"__partiql_arith": {"attr": left_attr, "op": operator, "val": right_val}}
+
raise ValueError(f"Cannot parse PartiQL value: {val_str}")
@@ -5746,7 +6047,8 @@ def _parse_projection_path(path: str, attr_names: dict) -> list:
def _project_one(node, path_parts):
"""Walk `path_parts` into a DynamoDB AttributeValue `node` and return a
pruned copy that contains only the path, or None if the path doesn't
- exist."""
+ exist. For list indices, returns a sparse dict-based representation
+ so that _merge_projection can identify and merge same-index paths."""
if not path_parts:
return node
if not isinstance(node, dict) or len(node) != 1:
@@ -5769,14 +6071,20 @@ def _project_one(node, path_parts):
sub = _project_one(vval[key], rest)
if sub is None:
return None
- return {"L": [sub]}
+ # Represent as a sparse list with the element at position `key`.
+ # This allows _merge_projection to correctly merge same-index paths.
+ sparse = [None] * (key + 1)
+ sparse[key] = sub
+ return {"L": sparse}
return None
def _merge_projection(into: dict | None, add: dict | None) -> dict | None:
"""Merge two projection-result AttributeValues at the same level.
Both must share the same wrapping type (M or L); merging M unions keys,
- merging L unions indices (kept in original order)."""
+ merging L merges elements that share the same index (AWS behaviour: two
+ paths referencing sub-attributes of the same list index produce one element,
+ not two separate single-element lists)."""
if into is None:
return add
if add is None:
@@ -5795,9 +6103,25 @@ def _merge_projection(into: dict | None, add: dict | None) -> dict | None:
merged[k] = _merge_projection(merged.get(k), v) if k in merged else v
return {"M": merged}
if it_t == "L" and isinstance(it_v, list) and isinstance(ad_v, list):
- # When two paths reference the same list, AWS preserves the union of
- # indices in original order.
- return {"L": it_v + [x for x in ad_v if x not in it_v]}
+ # AWS merges sub-attributes of the same list index into one element.
+ # We reconstruct a merged list: for each index present in either side,
+ # deep-merge the elements if both sides provide it, otherwise take
+ # whichever side has it.
+ # Represent each list as a dict[index -> value] for merging.
+ def _to_indexed(lst):
+ return {i: v for i, v in enumerate(lst)}
+ into_idx = _to_indexed(it_v)
+ add_idx = _to_indexed(ad_v)
+ all_indices = sorted(set(into_idx) | set(add_idx))
+ merged_list = []
+ for idx in all_indices:
+ if idx in into_idx and idx in add_idx:
+ merged_list.append(_merge_projection(into_idx[idx], add_idx[idx]))
+ elif idx in into_idx:
+ merged_list.append(into_idx[idx])
+ else:
+ merged_list.append(add_idx[idx])
+ return {"L": merged_list}
return into
@@ -5812,9 +6136,50 @@ def _project_item(item, proj_expr, attr_names):
head = path.split(".")[0].split("[")[0].strip()
if head and not head.startswith("#") and head.upper() in AWS_KEYWORDS:
raise ValueError(f"Invalid ProjectionExpression: Attribute name is a reserved keyword; reserved keyword: {head}")
- result: dict = {}
+
+ # Resolve all paths to their canonical (alias-substituted) string forms
+ # and check for duplicates or parent/child overlaps — AWS rejects these.
+ resolved_paths = []
for path in paths:
parts = _parse_projection_path(path, attr_names or {})
+ resolved_paths.append(parts)
+
+ def _path_str(parts):
+ s = ""
+ for kind, key in parts:
+ if kind == "name":
+ s += ("." if s else "") + key
+ else:
+ s += f"[{key}]"
+ return s
+
+ canonical = [_path_str(p) for p in resolved_paths]
+ # Check for duplicates and parent/child overlaps.
+ for i, p1 in enumerate(canonical):
+ for j, p2 in enumerate(canonical):
+ if i >= j:
+ continue
+ if p1 == p2:
+ raise ValueError(
+ f"Invalid ProjectionExpression: Two document paths overlap with each other; "
+ f"must remove or rewrite one of these paths; path one: [{p1}], path two: [{p2}]"
+ )
+ # Check parent/child: p1 is ancestor of p2 if p2 starts with p1 followed by . or [
+ p1_prefix_dot = p1 + "."
+ p1_prefix_bracket = p1 + "["
+ if p2.startswith(p1_prefix_dot) or p2.startswith(p1_prefix_bracket):
+ raise ValueError(
+ f"Invalid ProjectionExpression: Two document paths overlap with each other; "
+ f"must remove or rewrite one of these paths; path one: [{p1}], path two: [{p2}]"
+ )
+ if p1.startswith(p2 + ".") or p1.startswith(p2 + "["):
+ raise ValueError(
+ f"Invalid ProjectionExpression: Two document paths overlap with each other; "
+ f"must remove or rewrite one of these paths; path one: [{p2}], path two: [{p1}]"
+ )
+
+ result: dict = {}
+ for parts in resolved_paths:
if not parts:
continue
root_kind, root_name = parts[0]
@@ -5829,7 +6194,23 @@ def _project_item(item, proj_expr, attr_names):
result[root_name] = _merge_projection(result[root_name], sub)
else:
result[root_name] = sub
- return result
+ # Compact sparse lists: remove None placeholders and collapse to dense lists.
+ return _compact_projection(result)
+
+
+def _compact_projection(value):
+ """Recursively compact projection results: remove None placeholders from
+ sparse L lists, preserving order of non-None elements."""
+ if not isinstance(value, dict):
+ return value
+ if len(value) == 1:
+ (vtype, vval), = value.items()
+ if vtype == "L" and isinstance(vval, list):
+ compacted = [_compact_projection(x) for x in vval if x is not None]
+ return {"L": compacted}
+ if vtype == "M" and isinstance(vval, dict):
+ return {"M": {k: _compact_projection(v) for k, v in vval.items()}}
+ return value
# ---------------------------------------------------------------------------
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 8c2a2483..04e9cac5 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -1987,31 +1987,6 @@ def _rule_event(sql: str, topic: str, payload: bytes):
return event
-def _rule_event(sql: str, topic: str, payload: bytes):
- """Project a publish payload through a rule's SELECT clause."""
- payload = payload or b""
- message = _rule_message(payload)
- items = _split_select_items(_rule_select_clause(sql)) or ["*"]
-
- if len(items) == 1:
- expr, alias = _split_select_alias(items[0])
- if expr == "*" and alias is None:
- return message
-
- event: dict = {}
- for item in items:
- expr, alias = _split_select_alias(item)
- value = _eval_select_expr(expr, topic, message)
- if value is _MISSING:
- continue
- if expr == "*" and alias is None:
- if isinstance(value, dict):
- event.update(value)
- continue
- event[alias or _select_default_key(expr)] = value
- return event
-
-
def _dispatch_rule_to_lambda(
account_id: str, region: str, function_arn: str, event
) -> None:
diff --git a/tests/test_acm.py b/tests/test_acm.py
index 30c3d1cf..c0c871c6 100644
--- a/tests/test_acm.py
+++ b/tests/test_acm.py
@@ -28,6 +28,28 @@ def test_acm_describe_certificate(acm_client):
assert len(cert["DomainValidationOptions"]) >= 1
assert "ResourceRecord" in cert["DomainValidationOptions"][0]
+def test_acm_wildcard_san_validation_record_matches_base_domain(acm_client):
+ """A wildcard SAN validates through the same DNS record as its base domain:
+ real ACM strips the leading '*.' so '*.example.com' and 'example.com' share
+ one _acme-challenge.example.com CNAME with an identical name and value.
+ Regression for #1250 — aws_acm_certificate_validation could not find the
+ FQDN because the wildcard emitted _acme-challenge.*.example.com."""
+ arn = acm_client.request_certificate(
+ DomainName="wild.example.com",
+ ValidationMethod="DNS",
+ SubjectAlternativeNames=["*.wild.example.com"],
+ )["CertificateArn"]
+ cert = acm_client.describe_certificate(CertificateArn=arn)["Certificate"]
+ dvo = {o["DomainName"]: o["ResourceRecord"] for o in cert["DomainValidationOptions"]}
+
+ # The wildcard entry keeps its own DomainName but its record name has the
+ # '*.' stripped — never _acme-challenge.*.<domain>.
+ assert dvo["*.wild.example.com"]["Name"] == "_acme-challenge.wild.example.com."
+ assert "*." not in dvo["*.wild.example.com"]["Name"]
+ # Wildcard and apex collapse onto one identical CNAME (name AND value), so
+ # Terraform's for_each dedup and validation_record_fqdns line up.
+ assert dvo["*.wild.example.com"] == dvo["wild.example.com"]
+
def test_acm_list_certificates(acm_client):
arn = acm_client.request_certificate(DomainName="list.example.com")["CertificateArn"]
resp = acm_client.list_certificates()
diff --git a/tests/test_cloudfront.py b/tests/test_cloudfront.py
index 531159e3..f851867b 100644
--- a/tests/test_cloudfront.py
+++ b/tests/test_cloudfront.py
@@ -1257,3 +1257,136 @@ def test_kvs_dataplane_list_keys_pagination(cloudfront, cloudfront_kvs):
all_keys = [item["Key"] for item in resp["Items"] + resp2["Items"]]
assert len(set(all_keys)) == 4
+
+
+# ---------------------------------------------------------------------------
+# Cache policies (aws_cloudfront_cache_policy) — #1249
+# ---------------------------------------------------------------------------
+
+
+def _cache_policy_config(name):
+ return {
+ "Name": name,
+ "Comment": "test cache policy",
+ "DefaultTTL": 3600,
+ "MaxTTL": 86400,
+ "MinTTL": 1,
+ "ParametersInCacheKeyAndForwardedToOrigin": {
+ "EnableAcceptEncodingGzip": True,
+ "EnableAcceptEncodingBrotli": True,
+ "HeadersConfig": {
+ "HeaderBehavior": "whitelist",
+ "Headers": {"Quantity": 1, "Items": ["Authorization"]},
+ },
+ "CookiesConfig": {"CookieBehavior": "none"},
+ "QueryStringsConfig": {
+ "QueryStringBehavior": "whitelist",
+ "QueryStrings": {"Quantity": 2, "Items": ["a", "b"]},
+ },
+ },
+ }
+
+
+def test_cloudfront_create_and_get_cache_policy(cloudfront):
+ name = f"cp-{_uuid_mod.uuid4().hex[:8]}"
+ create = cloudfront.create_cache_policy(CachePolicyConfig=_cache_policy_config(name))
+ assert create["ETag"]
+ policy = create["CachePolicy"]
+ pid = policy["Id"]
+ assert policy["Id"]
+ assert "LastModifiedTime" in policy
+
+ got = cloudfront.get_cache_policy(Id=pid)
+ cfg = got["CachePolicy"]["CachePolicyConfig"]
+ assert got["ETag"] == create["ETag"]
+ assert cfg["Name"] == name
+ assert cfg["MinTTL"] == 1
+ assert cfg["DefaultTTL"] == 3600
+ assert cfg["MaxTTL"] == 86400
+ params = cfg["ParametersInCacheKeyAndForwardedToOrigin"]
+ assert params["EnableAcceptEncodingGzip"] is True
+ assert params["EnableAcceptEncodingBrotli"] is True
+ assert params["HeadersConfig"]["HeaderBehavior"] == "whitelist"
+ assert params["HeadersConfig"]["Headers"]["Items"] == ["Authorization"]
+ assert params["CookiesConfig"]["CookieBehavior"] == "none"
+ assert params["QueryStringsConfig"]["QueryStringBehavior"] == "whitelist"
+ assert params["QueryStringsConfig"]["QueryStrings"]["Items"] == ["a", "b"]
+
+ cloudfront.delete_cache_policy(Id=pid, IfMatch=got["ETag"])
+
+
+def test_cloudfront_get_cache_policy_config(cloudfront):
+ name = f"cp-{_uuid_mod.uuid4().hex[:8]}"
+ create = cloudfront.create_cache_policy(CachePolicyConfig=_cache_policy_config(name))
+ pid = create["CachePolicy"]["Id"]
+ resp = cloudfront.get_cache_policy_config(Id=pid)
+ assert resp["ETag"] == create["ETag"]
+ assert resp["CachePolicyConfig"]["Name"] == name
+ assert resp["CachePolicyConfig"]["MinTTL"] == 1
+ cloudfront.delete_cache_policy(Id=pid, IfMatch=create["ETag"])
+
+
+def test_cloudfront_update_cache_policy(cloudfront):
+ name = f"cp-{_uuid_mod.uuid4().hex[:8]}"
+ create = cloudfront.create_cache_policy(CachePolicyConfig=_cache_policy_config(name))
+ pid = create["CachePolicy"]["Id"]
+
+ # No If-Match -> InvalidIfMatchVersion.
+ updated_cfg = _cache_policy_config(name)
+ updated_cfg["MinTTL"] = 5
+ with pytest.raises(ClientError) as exc:
+ cloudfront.update_cache_policy(CachePolicyConfig=updated_cfg, Id=pid)
+ assert exc.value.response["Error"]["Code"] == "InvalidIfMatchVersion"
+
+ # Stale If-Match -> PreconditionFailed.
+ with pytest.raises(ClientError) as exc:
+ cloudfront.update_cache_policy(CachePolicyConfig=updated_cfg, Id=pid, IfMatch="stale-etag")
+ assert exc.value.response["Error"]["Code"] == "PreconditionFailed"
+
+ upd = cloudfront.update_cache_policy(CachePolicyConfig=updated_cfg, Id=pid, IfMatch=create["ETag"])
+ assert upd["ETag"] != create["ETag"]
+ assert upd["CachePolicy"]["CachePolicyConfig"]["MinTTL"] == 5
+ cloudfront.delete_cache_policy(Id=pid, IfMatch=upd["ETag"])
+
+
+def test_cloudfront_delete_cache_policy(cloudfront):
+ name = f"cp-{_uuid_mod.uuid4().hex[:8]}"
+ create = cloudfront.create_cache_policy(CachePolicyConfig=_cache_policy_config(name))
+ pid = create["CachePolicy"]["Id"]
+
+ with pytest.raises(ClientError) as exc:
+ cloudfront.delete_cache_policy(Id=pid)
+ assert exc.value.response["Error"]["Code"] == "InvalidIfMatchVersion"
+
+ cloudfront.delete_cache_policy(Id=pid, IfMatch=create["ETag"])
+ with pytest.raises(ClientError) as exc:
+ cloudfront.get_cache_policy(Id=pid)
+ assert exc.value.response["Error"]["Code"] == "NoSuchCachePolicy"
+
+
+def test_cloudfront_cache_policy_duplicate_name_rejected(cloudfront):
+ name = f"cp-{_uuid_mod.uuid4().hex[:8]}"
+ create = cloudfront.create_cache_policy(CachePolicyConfig=_cache_policy_config(name))
+ pid = create["CachePolicy"]["Id"]
+ with pytest.raises(ClientError) as exc:
+ cloudfront.create_cache_policy(CachePolicyConfig=_cache_policy_config(name))
+ assert exc.value.response["Error"]["Code"] == "CachePolicyAlreadyExists"
+ cloudfront.delete_cache_policy(Id=pid, IfMatch=create["ETag"])
+
+
+def test_cloudfront_get_missing_cache_policy(cloudfront):
+ with pytest.raises(ClientError) as exc:
+ cloudfront.get_cache_policy(Id="no-such-cache-policy")
+ assert exc.value.response["Error"]["Code"] == "NoSuchCachePolicy"
+
+
+def test_cloudfront_list_distributions_by_cache_policy(cloudfront):
+ name = f"cp-{_uuid_mod.uuid4().hex[:8]}"
+ create = cloudfront.create_cache_policy(CachePolicyConfig=_cache_policy_config(name))
+ pid = create["CachePolicy"]["Id"]
+ resp = cloudfront.list_distributions_by_cache_policy_id(CachePolicyId=pid)
+ dil = resp["DistributionIdList"]
+ assert dil["Quantity"] == 0
+ assert dil["IsTruncated"] is False
+ assert dil.get("Items", []) == []
+ cloudfront.delete_cache_policy(Id=pid, IfMatch=create["ETag"])
diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.py
index 7b51b6f2..a49d1d5e 100644
--- a/tests/test_dynamodb.py
+++ b/tests/test_dynamodb.py
@@ -2243,6 +2243,159 @@ def test_partiql_delete(ddb):
assert "Item" not in resp
+def _mk_partiql_table(ddb, tname):
+ try:
+ ddb.delete_table(TableName=tname)
+ except ClientError:
+ pass
+ ddb.create_table(
+ TableName=tname,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+
+
+def test_partiql_select_multi_predicate_begins_with_not_last(ddb):
+ """A predicate AFTER begins_with must still be enforced. Regression: the
+ begins_with branch used to `return` inside the WHERE loop, so any condition
+ following it was silently ignored (order-dependent wrong results)."""
+ tname = "partiql-where-multi"
+ _mk_partiql_table(ddb, tname)
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "a1"}, "name": {"S": "apple"}, "status": {"S": "active"}})
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "a2"}, "name": {"S": "apricot"}, "status": {"S": "inactive"}})
+
+ resp = ddb.execute_statement(
+ Statement=f"SELECT * FROM \"{tname}\" WHERE begins_with(name, 'ap') AND status = ?",
+ Parameters=[{"S": "active"}],
+ )
+ # Both names begin with 'ap'; only one is active. The trailing status
+ # predicate must filter out apricot.
+ pks = sorted(it["pk"]["S"] for it in resp["Items"])
+ assert pks == ["a1"]
+
+
+def test_partiql_update_trailing_predicate_after_begins_with_enforced(ddb):
+ """UPDATE's non-key predicate after begins_with is a conditional check;
+ when it fails the item is left unchanged (ConditionalCheckFailedException)."""
+ tname = "partiql-update-multi"
+ _mk_partiql_table(ddb, tname)
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "u1"}, "name": {"S": "apple"}, "status": {"S": "old"}})
+
+ with pytest.raises(ClientError) as exc:
+ ddb.execute_statement(
+ Statement=f"UPDATE \"{tname}\" SET status = ? WHERE pk = ? AND begins_with(name, 'ap') AND status = ?",
+ Parameters=[{"S": "new"}, {"S": "u1"}, {"S": "beta"}],
+ )
+ assert exc.value.response["Error"]["Code"] == "ConditionalCheckFailedException"
+ # Item must be untouched.
+ got = ddb.get_item(TableName=tname, Key={"pk": {"S": "u1"}})
+ assert got["Item"]["status"]["S"] == "old"
+
+
+def test_partiql_update_returning_all_old(ddb):
+ tname = "partiql-ret-allold"
+ _mk_partiql_table(ddb, tname)
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "r1"}, "status": {"S": "old"}})
+ resp = ddb.execute_statement(
+ Statement=f"UPDATE \"{tname}\" SET status = ? WHERE pk = ? RETURNING ALL OLD *",
+ Parameters=[{"S": "new"}, {"S": "r1"}],
+ )
+ assert resp["Items"] == [{"pk": {"S": "r1"}, "status": {"S": "old"}}]
+ assert ddb.get_item(TableName=tname, Key={"pk": {"S": "r1"}})["Item"]["status"]["S"] == "new"
+
+
+def test_partiql_update_returning_all_new(ddb):
+ tname = "partiql-ret-allnew"
+ _mk_partiql_table(ddb, tname)
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "r1"}, "status": {"S": "old"}})
+ resp = ddb.execute_statement(
+ Statement=f"UPDATE \"{tname}\" SET status = ? WHERE pk = ? RETURNING ALL NEW *",
+ Parameters=[{"S": "new"}, {"S": "r1"}],
+ )
+ assert resp["Items"] == [{"pk": {"S": "r1"}, "status": {"S": "new"}}]
+
+
+def test_partiql_update_returning_modified(ddb):
+ tname = "partiql-ret-mod"
+ _mk_partiql_table(ddb, tname)
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "r1"}, "status": {"S": "old"}, "keep": {"S": "same"}})
+ old = ddb.execute_statement(
+ Statement=f"UPDATE \"{tname}\" SET status = ? WHERE pk = ? RETURNING MODIFIED OLD *",
+ Parameters=[{"S": "new"}, {"S": "r1"}],
+ )
+ # Only the changed attribute, as it was before.
+ assert old["Items"] == [{"status": {"S": "old"}}]
+ new = ddb.execute_statement(
+ Statement=f"UPDATE \"{tname}\" SET status = ? WHERE pk = ? RETURNING MODIFIED NEW *",
+ Parameters=[{"S": "newer"}, {"S": "r1"}],
+ )
+ assert new["Items"] == [{"status": {"S": "newer"}}]
+
+
+def test_partiql_delete_returning_all_old(ddb):
+ tname = "partiql-del-ret"
+ _mk_partiql_table(ddb, tname)
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "d1"}, "val": {"S": "x"}})
+ resp = ddb.execute_statement(
+ Statement=f"DELETE FROM \"{tname}\" WHERE pk = ? RETURNING ALL OLD *",
+ Parameters=[{"S": "d1"}],
+ )
+ assert resp["Items"] == [{"pk": {"S": "d1"}, "val": {"S": "x"}}]
+ assert "Item" not in ddb.get_item(TableName=tname, Key={"pk": {"S": "d1"}})
+
+
+def test_partiql_update_missing_item_conditional_check_failed(ddb):
+ """AWS: 'If the WHERE clause of the UPDATE statement does not evaluate to
+ true for any item, ConditionalCheckFailedException is returned.' No upsert."""
+ tname = "partiql-update-missing"
+ _mk_partiql_table(ddb, tname)
+ with pytest.raises(ClientError) as exc:
+ ddb.execute_statement(
+ Statement=f"UPDATE \"{tname}\" SET status = ? WHERE pk = ?",
+ Parameters=[{"S": "new"}, {"S": "ghost"}],
+ )
+ assert exc.value.response["Error"]["Code"] == "ConditionalCheckFailedException"
+ assert "Item" not in ddb.get_item(TableName=tname, Key={"pk": {"S": "ghost"}})
+
+
+def test_partiql_update_remove_clause(ddb):
+ tname = "partiql-remove"
+ _mk_partiql_table(ddb, tname)
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "u1"}, "a": {"S": "keep"}, "b": {"S": "drop"}})
+ ddb.execute_statement(
+ Statement=f"UPDATE \"{tname}\" REMOVE b WHERE pk = ?",
+ Parameters=[{"S": "u1"}],
+ )
+ item = ddb.get_item(TableName=tname, Key={"pk": {"S": "u1"}})["Item"]
+ assert item["a"]["S"] == "keep"
+ assert "b" not in item
+
+
+def test_partiql_select_in_and_is_missing(ddb):
+ """IN membership and IS MISSING / IS NOT MISSING predicates filter rows."""
+ tname = "partiql-in-missing"
+ _mk_partiql_table(ddb, tname)
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "p1"}, "status": {"S": "active"}, "note": {"S": "hi"}})
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "p2"}, "status": {"S": "pending"}})
+ ddb.put_item(TableName=tname, Item={"pk": {"S": "p3"}, "status": {"S": "closed"}, "note": {"S": "bye"}})
+
+ in_resp = ddb.execute_statement(
+ Statement=f"SELECT * FROM \"{tname}\" WHERE status IN ('active', 'pending')",
+ )
+ assert sorted(it["pk"]["S"] for it in in_resp["Items"]) == ["p1", "p2"]
+
+ missing = ddb.execute_statement(
+ Statement=f"SELECT * FROM \"{tname}\" WHERE note IS MISSING",
+ )
+ assert sorted(it["pk"]["S"] for it in missing["Items"]) == ["p2"]
+
+ not_missing = ddb.execute_statement(
+ Statement=f"SELECT * FROM \"{tname}\" WHERE note IS NOT MISSING",
+ )
+ assert sorted(it["pk"]["S"] for it in not_missing["Items"]) == ["p1", "p3"]
+
+
def test_partiql_nonexistent_table(ddb):
"""ExecuteStatement on a nonexistent table should return ResourceNotFoundException."""
with pytest.raises(ClientError) as exc: