Skip to content

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

fix dim report (#2100)

Nahuel Nucera5eafc8e83602
diff --git a/Dockerfile b/Dockerfile
index a94defce..7b0fb171 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -35,15 +35,22 @@ RUN rm -rf /usr/local/lib/python3.13/site-packages/awscli/examples \
# Plugin artifacts are release-stable; release builds pin this donor by digest.
FROM ${PLUGIN_DONOR_IMAGE} AS plugin-donor
-FROM python:3.13-alpine
-
-LABEL maintainer="MiniStack" \
- description="Local AWS Service Emulator — drop-in LocalStack replacement"
+FROM python:3.13-alpine AS runtime
# Upgrade base packages to pick up latest security patches.
RUN apk upgrade --no-cache && apk add --no-cache nodejs bash openssl && rm -f /usr/bin/wget /bin/wget \
- && rm -rf /usr/local/lib/python3.13/site-packages/pip* \
- /usr/local/bin/pip*
+ && rm -rf /usr/local/lib/python3.13/site-packages/pip* /usr/local/bin/pip* \
+ /usr/local/lib/python3.13/ensurepip /usr/local/lib/python3.13/idlelib \
+ /usr/local/lib/python3.13/pydoc_data /usr/local/lib/python3.13/tkinter \
+ /usr/local/lib/python3.13/turtledemo
+
+# Flatten so upgraded and deleted base files do not also ship in a lower layer.
+FROM scratch
+COPY --from=runtime / /
+ENV PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
+
+LABEL maintainer="MiniStack" \
+ description="Local AWS Service Emulator — drop-in LocalStack replacement"
WORKDIR /opt/ministack
diff --git a/ministack/core/container_reaper.py b/ministack/core/container_reaper.py
index 2b9981f6..93385daa 100644
--- a/ministack/core/container_reaper.py
+++ b/ministack/core/container_reaper.py
@@ -288,10 +288,16 @@ def drop_containers(containers, stop_timeout: int = 2, force: bool = False) -> i
c.stop(timeout=stop_timeout)
c.remove(v=True, force=force) # v=True: reclaim the anonymous volume too
return True
- except Exception:
+ except Exception as e:
+ logger.debug("container_reaper: could not remove %s: %s", getattr(c, "id", "?"), e)
return False
with concurrent.futures.ThreadPoolExecutor(
max_workers=min(16, len(targets)), thread_name_prefix="ministack-reap") as pool:
- return sum(1 for ok in pool.map(_drop, targets) if ok)
+ results = list(pool.map(_drop, targets))
+ left = [getattr(c, "id", "?")[:12] for c, ok in zip(targets, results) if not ok]
+ if left:
+ logger.warning("container_reaper: %d container(s) could not be removed: %s",
+ len(left), ", ".join(left))
+ return len(targets) - len(left)
diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.py
index 40e1acb3..f87a8358 100644
--- a/ministack/services/cloudwatch.py
+++ b/ministack/services/cloudwatch.py
@@ -142,6 +142,9 @@ def _parse_ts(value):
"""Parse ISO-8601 string, epoch float, or None into a Unix timestamp."""
if value is None:
return None
+ if isinstance(value, datetime):
+ # rpc-v2-cbor timestamps (tag 1) decode to datetime; naive means UTC.
+ return (value if value.tzinfo else value.replace(tzinfo=timezone.utc)).timestamp()
if isinstance(value, (int, float)):
return float(value)
if isinstance(value, str):
diff --git a/ministack/services/dynamodb_streams.py b/ministack/services/dynamodb_streams.py
index c9e64197..97ce2d9d 100644
--- a/ministack/services/dynamodb_streams.py
+++ b/ministack/services/dynamodb_streams.py
@@ -12,6 +12,7 @@ shard per stream; no duplicate storage).
import base64
import json
import logging
+import time
from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.responses import error_response_json, get_account_id, get_region, json_response
@@ -22,6 +23,18 @@ logger = logging.getLogger("dynamodb_streams")
# Single synthetic shard per stream — MiniStack does not model shard splitting.
_DEFAULT_SHARD_ID = "shardId-00000000000000000000-00000000"
+# "A shard iterator expires 15 minutes after it is returned to the requester."
+_ITERATOR_TTL_SECONDS = 15 * 60
+# "GetRecords can retrieve a maximum of 1 MB of data or 1000 stream records,
+# whichever comes first."
+_GET_RECORDS_MAX_BYTES = 1024 * 1024
+
+def _shard_not_found():
+ # Real AWS: "ResourceNotFoundException: Requested resource not found: Shard does not exist"
+ return error_response_json("ResourceNotFoundException",
+ "Requested resource not found: Shard does not exist", 400)
+
+
_ITERATOR_TYPES = {
"TRIM_HORIZON",
"LATEST",
@@ -71,7 +84,7 @@ def _encode_iterator(
it back unmodified. We base64-url-encode a small JSON payload so it stays
short enough to fit in AWS's 2 KB iterator limit.
"""
- payload_data = {"t": table_name, "s": shard_id, "p": position}
+ payload_data = {"t": table_name, "s": shard_id, "p": position, "i": time.time()}
if account_id:
payload_data["a"] = account_id
if region:
@@ -269,7 +282,8 @@ def _describe_stream(data):
# ExclusiveStartShardId skips past a previously-returned shard. We expose
# one synthetic shard so this is degenerate, but the fields must be honored
# for SDK consumers that pass them.
- all_shards = [shard]
+ # The single synthetic shard has no children.
+ all_shards = [] if (data.get("ShardFilter") or {}).get("Type") == "CHILD_SHARDS" else [shard]
start_shard = data.get("ExclusiveStartShardId")
if start_shard:
idx = next((i for i, s in enumerate(all_shards) if s["ShardId"] == start_shard), -1)
@@ -295,6 +309,8 @@ def _describe_stream(data):
def _get_shard_iterator(data):
stream_arn = data.get("StreamArn")
shard_id = data.get("ShardId") or _DEFAULT_SHARD_ID
+ if shard_id != _DEFAULT_SHARD_ID:
+ return _shard_not_found()
iterator_type = data.get("ShardIteratorType")
seq_number = data.get("SequenceNumber")
@@ -361,11 +377,24 @@ def _get_shard_iterator(data):
return json_response({"ShardIterator": iterator})
+def _cap_page_bytes(page: list) -> list:
+ """Stop the page before the record that would pass 1 MB."""
+ total = 0
+ for i, record in enumerate(page):
+ size = len(json.dumps(record, separators=(",", ":"), default=str).encode("utf-8"))
+ if i and total + size > _GET_RECORDS_MAX_BYTES:
+ return page[:i]
+ total += size
+ return page
+
+
def _get_records(data):
iterator = data.get("ShardIterator")
- limit = int(data.get("Limit", 1000) or 1000)
- if limit <= 0:
- limit = 1000
+ limit = int(data.get("Limit", 1000))
+ if limit < 1:
+ return error_response_json("ValidationException",
+ f"1 validation error detected: Value '{limit}' at 'limit' failed to satisfy constraint: "
+ "Member must have value greater than or equal to 1", 400)
limit = min(limit, 1000)
if not iterator:
@@ -379,6 +408,8 @@ def _get_records(data):
table_name = decoded["t"]
shard_id = decoded.get("s", _DEFAULT_SHARD_ID)
+ if shard_id != _DEFAULT_SHARD_ID:
+ return _shard_not_found()
position = int(decoded.get("p", 0))
account_id = decoded.get("a", get_account_id())
region = decoded.get("r", get_region())
@@ -388,6 +419,10 @@ def _get_records(data):
return error_response_json(
"ValidationException", "ShardIterator is not valid", 400
)
+ issued = decoded.get("i")
+ if not isinstance(issued, (int, float)) or time.time() - issued >= _ITERATOR_TTL_SECONDS:
+ return error_response_json("ExpiredIteratorException",
+ "The shard iterator has expired and can no longer be used to retrieve stream records.", 400)
info = _enabled_stream_info(table_name, account_id=account_id, region=region)
closed = None
@@ -403,15 +438,20 @@ def _get_records(data):
# ``position`` is absolute, so an iterator minted before records expired
# still lands correctly; one that now points behind the trim horizon
# resumes at the horizon rather than skipping live records.
+ # An iterator whose position has since been trimmed (records past 24 h)
+ # raises TrimmedDataAccessException, as botocore documents.
+ horizon = closed["trimmed"] if closed else _horizon(account_id, region, table_name)
+ if position < horizon:
+ return error_response_json("TrimmedDataAccessException",
+ "The data you are trying to access has been trimmed", 400)
if closed:
- position = max(position, closed["trimmed"])
offset = position - closed["trimmed"]
page = closed["records"][offset:offset + limit]
else:
- position = max(position, _horizon(account_id, region, table_name))
page = _ddb.stream_records_since(
table_name, position, limit, account_id=account_id, region=region
)
+ page = _cap_page_bytes(page)
next_position = position + len(page)
# The Streams Record shape carries no eventSourceARN (Lambda events do).
page = [{k: v for k, v in r.items() if k != "eventSourceARN"} for r in page]
diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.py
index c2e4937f..e7f426e0 100644
--- a/ministack/services/eventbridge.py
+++ b/ministack/services/eventbridge.py
@@ -2505,13 +2505,14 @@ def _dispatch_to_sqs(spec, payload, sqs_parameters=None):
def _dispatch_to_sns(arn, payload):
from ministack.services import sns as _sns
- topic = _sns._topics.get(arn)
- if not topic:
+ try:
+ result = _sns.publish_internal(arn, payload, "EventBridge Notification")
+ except _sns.SnsPublishError as exc:
+ logger.warning("EventBridge → SNS %s refused: %s", arn, exc)
+ return
+ if result is None:
logger.warning("EventBridge → SNS: topic %s not found", arn)
return
-
- msg_id = new_uuid()
- _sns._fanout(arn, msg_id, payload, "EventBridge Notification")
logger.info("EventBridge → SNS %s", arn)
diff --git a/ministack/services/glue.py b/ministack/services/glue.py
index 5a4579ec..ffa48f89 100644
--- a/ministack/services/glue.py
+++ b/ministack/services/glue.py
@@ -691,7 +691,10 @@ def _iceberg_rest_commit_table(namespace, table_name, body):
meta_loc = table["Parameters"]["metadata_location"]
metadata = _iceberg_fetch_metadata(meta_loc) or {}
try:
+ _s3t._check_iceberg_requirements(metadata, body.get("requirements", []))
_s3t._apply_iceberg_updates(metadata, body.get("updates", []))
+ except _s3t.IcebergCommitFailed as exc:
+ return _iceberg_error(str(exc), "CommitFailedException", 409)
except ValueError as exc:
# A refused update (an illegal format-version change) commits
# nothing: the stored metadata_location is only advanced below.
diff --git a/ministack/services/pipes.py b/ministack/services/pipes.py
index 5985bbc5..2f80c815 100644
--- a/ministack/services/pipes.py
+++ b/ministack/services/pipes.py
@@ -30,7 +30,6 @@ from ministack.core.responses import (
_request_region,
get_account_id,
get_region,
- new_uuid,
)
logger = logging.getLogger("pipes")
@@ -147,6 +146,12 @@ def check_same_region(*arns):
raise ValueError(CROSS_REGION_PIPE_ERROR)
+def check_target_supported(target: str) -> None:
+ """Pipes does not take an SNS FIFO topic as a target (measured on AWS)."""
+ if target.startswith("arn:") and target.split(":")[2:3] == ["sns"] and target.endswith(".fifo"):
+ raise ValueError("SNS FIFO topics are not supported as a pipe target.")
+
+
def register_pipe(
*,
name: str,
@@ -161,6 +166,7 @@ def register_pipe(
pipe_region = get_region()
# AWS rejects cross-region source/target ARNs before role validation.
check_same_region(source, target)
+ check_target_supported(target)
arn = f"arn:aws:pipes:{pipe_region}:{get_account_id()}:pipe/{name}"
state = "STOPPED" if str(desired_state).upper() == "STOPPED" else "RUNNING"
@@ -297,16 +303,13 @@ def _start_state_machine_from_records(sm_arn: str, pipe: dict, records: list) ->
def _publish_record_to_sns(topic_arn: str, pipe: dict, record: dict):
from ministack.services import sns as _sns
- topic = _sns._topics.get(topic_arn)
- if not topic:
- logger.warning("Pipes %s: SNS topic not found %s", pipe.get("Name"), topic_arn)
+ try:
+ result = _sns.publish_internal(topic_arn, json.dumps(record), f"Pipes {pipe.get('Name', '')}")
+ except _sns.SnsPublishError as exc:
+ logger.warning("Pipes %s: SNS publish to %s refused: %s", pipe.get("Name"), topic_arn, exc)
return
-
- msg_id = new_uuid()
- message = json.dumps(record)
- subject = f"Pipes {pipe.get('Name', '')}"
-
- _sns._fanout(topic_arn, msg_id, message, subject, "", {})
+ if result is None:
+ logger.warning("Pipes %s: SNS topic not found %s", pipe.get("Name"), topic_arn)
def _arn_service(arn: str) -> str:
@@ -509,6 +512,10 @@ def _update_pipe(name, body):
pipe = _pipes.get(name)
if pipe is None:
return _not_found(name)
+ try:
+ check_target_supported(body.get("Target") or "")
+ except ValueError as e:
+ return _error(400, "ValidationException", str(e))
if "Description" in body:
pipe["Description"] = body.get("Description", "") or ""
if "RoleArn" in body:
diff --git a/ministack/services/s3tables.py b/ministack/services/s3tables.py
index d6463cc8..b3a65efe 100644
--- a/ministack/services/s3tables.py
+++ b/ministack/services/s3tables.py
@@ -592,13 +592,33 @@ def _iceberg_error(message, exc_type, code):
return code, {"Content-Type": "application/json"}, body
+def _bucket_scope_from_prefix(prefix: str):
+ """The table bucket a REST {prefix} names. "For S3 Tables the REST path
+ {prefix} is always your url-encoded table bucket ARN"; the Glue form is
+ ``{account}:s3tablescatalog/{bucket}``. Anything else is unscoped."""
+ if prefix.startswith("arn:") and ":bucket/" in prefix:
+ return prefix
+ if ":s3tablescatalog/" in prefix:
+ return prefix.split(":s3tablescatalog/", 1)[1]
+ return None
+
+
+def _in_bucket(bucket_arn: str, bucket_filter) -> bool:
+ if not bucket_filter:
+ return True
+ if bucket_filter.startswith("arn:"):
+ return bucket_arn == bucket_filter
+ return bucket_arn.endswith("/" + bucket_filter)
+
+
def _iceberg_allows_cross_region(headers):
return _SIGV4_CREDENTIAL_REGION_RE.search(headers.get("authorization", "")) is None
-def _iceberg_list_namespaces(allow_cross_region):
+def _iceberg_list_namespaces(allow_cross_region, bucket_filter=None):
result = []
- for ns in _iceberg_values(_namespaces, lambda _ns: True, allow_cross_region):
+ for ns in _iceberg_values(
+ _namespaces, lambda ns: _in_bucket(ns.get("tableBucketARN", ""), bucket_filter), allow_cross_region):
result.append(ns.get("namespace", []))
return json_response({"namespaces": result})
@@ -617,19 +637,17 @@ def _iceberg_create_namespace(data, allow_cross_region, bucket_filter=None):
# Find the table bucket to create the namespace in. When the prefix
# carries a bucket filter (from the /v1/config warehouse), use that;
# otherwise fall back to the first visible bucket.
- if bucket_filter:
- buckets = _iceberg_values(
- _table_buckets, lambda b: b.get("arn", "").endswith("/" + bucket_filter),
- allow_cross_region)
- else:
- buckets = _iceberg_values(_table_buckets, lambda _b: True, allow_cross_region)
+ buckets = _iceberg_values(
+ _table_buckets, lambda b: _in_bucket(b.get("arn", ""), bucket_filter), allow_cross_region)
if not buckets:
return _iceberg_error("No table bucket found", "NoSuchNamespaceException", 404)
bucket = buckets[0]
bucket_arn = bucket.get("arn", "")
# Check if namespace already exists.
existing = _iceberg_values(
- _namespaces, lambda ns: _namespace_name(ns) == ns_name, allow_cross_region)
+ _namespaces,
+ lambda ns: _namespace_name(ns) == ns_name and ns.get("tableBucketARN") == bucket_arn,
+ allow_cross_region)
if existing:
return _iceberg_error(
f"Namespace already exists: {ns_name}", "AlreadyExistsException", 409)
@@ -637,8 +655,11 @@ def _iceberg_create_namespace(data, allow_cross_region, bucket_filter=None):
return json_response({"namespace": [ns_name], "properties": data.get("properties", {})})
-def _iceberg_get_namespace(namespace, allow_cross_region):
- if _iceberg_values(_namespaces, lambda ns: _namespace_name(ns) == namespace, allow_cross_region):
+def _iceberg_get_namespace(namespace, allow_cross_region, bucket_filter=None):
+ if _iceberg_values(
+ _namespaces,
+ lambda ns: _namespace_name(ns) == namespace and _in_bucket(ns.get("tableBucketARN", ""), bucket_filter),
+ allow_cross_region):
return json_response({"namespace": [namespace], "properties": {}})
return _iceberg_error(f"Namespace {namespace} not found", "NoSuchNamespaceException", 404)
@@ -647,9 +668,7 @@ def _iceberg_list_tables(namespace, allow_cross_region, bucket_filter=None):
def _pred(table):
if _namespace_name(table) != namespace:
return False
- if bucket_filter:
- return table.get("tableBucketARN", "").endswith("/" + bucket_filter)
- return True
+ return _in_bucket(table.get("tableBucketARN", ""), bucket_filter)
result = []
for table in _iceberg_values(_tables, _pred, allow_cross_region):
@@ -657,53 +676,112 @@ def _iceberg_list_tables(namespace, allow_cross_region, bucket_filter=None):
return json_response({"identifiers": result})
+def _current_iceberg_metadata(table):
+ """(metadata, location) as a reader sees it: the newest metadata.json in
+ the table's metadata directory on S3, else the in-memory copy. Writers
+ like DuckDB commit by writing metadata.json straight to S3, so both
+ LoadTable and a REST commit must start from this, or a commit lands on a
+ stale base."""
+ metadata = table.get("_iceberg_metadata", {})
+ meta_loc = table.get("metadataLocation", "")
+ if meta_loc and meta_loc.startswith("s3://"):
+ try:
+ import ministack.services.s3 as _s3
+
+ rest = meta_loc[len("s3://") :]
+ bkt, key = rest.split("/", 1)
+ meta_dir = "/".join(key.split("/")[:-1]) + "/"
+ bucket_data = _s3._ensure_bucket(bkt)
+ if bucket_data:
+ meta_files = [
+ k for k in bucket_data.get("objects", {})
+ if k.startswith(meta_dir) and k.endswith(".metadata.json")
+ ]
+ if meta_files:
+ # Order vN.metadata.json numerically: lexically v10 sorts
+ # before v2. Spark-style zero-padded names all map to -1
+ # and keep their lexical order.
+ from ministack.services.glue import _metadata_version_from_location
+
+ meta_files.sort()
+ meta_files.sort(key=_metadata_version_from_location)
+ latest_key = meta_files[-1]
+ raw = _s3._get_object_data(bkt, latest_key)
+ if raw:
+ return json.loads(raw), f"s3://{bkt}/{latest_key}"
+ except Exception:
+ pass # fall back to in-memory
+ return metadata, meta_loc
+
+
+class IcebergCommitFailed(Exception):
+ """An Iceberg REST commit requirement did not hold (HTTP 409)."""
+
+
+def _iceberg_main_ref(metadata, name):
+ refs = metadata.get("refs") or {}
+ if name in refs:
+ return refs[name]
+ current = metadata.get("current-snapshot-id")
+ if name == "main" and current not in (None, -1):
+ return {"snapshot-id": current, "type": "branch"}
+ return None
+
+
+def _check_iceberg_requirements(metadata, requirements, staged=False):
+ """Iceberg UpdateRequirement semantics; messages as in the reference
+ implementation (org.apache.iceberg.UpdateRequirement)."""
+ def check(actual, expected, what):
+ if expected != actual:
+ raise IcebergCommitFailed(f"Requirement failed: {what} changed: expected id {expected} != {actual}")
+
+ for req in requirements or []:
+ kind = req.get("type", "")
+ if kind == "assert-create":
+ if not staged:
+ raise IcebergCommitFailed("Requirement failed: table already exists")
+ if kind == "assert-table-uuid":
+ uuid = req.get("uuid", "")
+ if uuid.lower() != str(metadata.get("table-uuid", "")).lower():
+ raise IcebergCommitFailed(
+ f"Requirement failed: UUID does not match: expected {metadata.get('table-uuid')} != {uuid}")
+ elif kind == "assert-ref-snapshot-id":
+ name, expected = req.get("ref", "main"), req.get("snapshot-id")
+ ref = _iceberg_main_ref(metadata, name)
+ if ref is not None:
+ kind_name = "tag" if ref.get("type") == "tag" else "branch"
+ if expected is None:
+ raise IcebergCommitFailed(f"Requirement failed: {kind_name} {name} was created concurrently")
+ if expected != ref.get("snapshot-id"):
+ raise IcebergCommitFailed(
+ f"Requirement failed: {kind_name} {name} has changed: "
+ f"expected id {expected} != {ref.get('snapshot-id')}")
+ elif expected is not None:
+ raise IcebergCommitFailed(
+ f"Requirement failed: branch or tag {name} is missing, expected {expected}")
+ elif kind == "assert-last-assigned-field-id":
+ check(metadata.get("last-column-id"), req.get("last-assigned-field-id"), "last assigned field id")
+ elif kind == "assert-current-schema-id":
+ check(metadata.get("current-schema-id"), req.get("current-schema-id"), "current schema")
+ elif kind == "assert-last-assigned-partition-id":
+ check(metadata.get("last-partition-id"), req.get("last-assigned-partition-id"),
+ "last assigned partition id")
+ elif kind == "assert-default-spec-id":
+ check(metadata.get("default-spec-id"), req.get("default-spec-id"), "default partition spec")
+ elif kind == "assert-default-sort-order-id":
+ check(metadata.get("default-sort-order-id"), req.get("default-sort-order-id"), "default sort order")
+
+
def _iceberg_load_table(namespace, table_name, allow_cross_region, bucket_filter=None):
def _pred(table):
if _namespace_name(table) != namespace or table["name"] != table_name:
return False
- if bucket_filter:
- return table.get("tableBucketARN", "").endswith("/" + bucket_filter)
- return True
+ return _in_bucket(table.get("tableBucketARN", ""), bucket_filter)
matches = _iceberg_values(_tables, _pred, allow_cross_region)
if matches:
table = matches[0]
- # Try to read the latest metadata from S3 (source of truth). Writers
- # like DuckDB commit by writing metadata.json directly to S3 without
- # going through the REST commit endpoint, so the in-memory metadata
- # can be stale. Fall back to in-memory if S3 read fails.
- metadata = table.get("_iceberg_metadata", {})
- meta_loc = table.get("metadataLocation", "")
- if meta_loc and meta_loc.startswith("s3://"):
- try:
- import ministack.services.s3 as _s3
-
- rest = meta_loc[len("s3://") :]
- bkt, key = rest.split("/", 1)
- # Find the latest metadata file in the metadata directory
- meta_dir = "/".join(key.split("/")[:-1]) + "/"
- bucket_data = _s3._ensure_bucket(bkt)
- if bucket_data:
- meta_files = sorted(
- k
- for k in bucket_data.get("objects", {})
- if k.startswith(meta_dir) and k.endswith(".metadata.json")
- )
- if meta_files:
- # Order vN.metadata.json numerically: lexically v10
- # sorts before v2, so from the 10th commit on the scan
- # would serve v9 forever. Spark-style zero-padded
- # names all map to -1 and keep their lexical order.
- from ministack.services.glue import _metadata_version_from_location
-
- meta_files.sort(key=_metadata_version_from_location)
- latest_key = meta_files[-1]
- raw = _s3._get_object_data(bkt, latest_key)
- if raw:
- metadata = json.loads(raw)
- meta_loc = f"s3://{bkt}/{latest_key}"
- except Exception:
- pass # fall back to in-memory
+ metadata, meta_loc = _current_iceberg_metadata(table)
return json_response(
{
"metadata-location": meta_loc,
@@ -729,10 +807,22 @@ def _apply_iceberg_updates(metadata, updates):
action = update.get("action", "")
if action == "add-snapshot":
snapshot = update.get("snapshot", {})
- metadata.setdefault("snapshots", []).append(snapshot)
+ snapshots = metadata.setdefault("snapshots", [])
+ if any(s.get("snapshot-id") == snapshot.get("snapshot-id") for s in snapshots):
+ raise ValueError(f"Snapshot already exists for id: {snapshot.get('snapshot-id')}")
+ last = metadata.get("last-sequence-number", 0)
+ seq = snapshot.get("sequence-number")
+ # Iceberg TableMetadata.addSnapshot: on v2+ a snapshot with a
+ # parent must be newer than the table, and the table's
+ # last-sequence-number becomes the snapshot's own number.
+ if (int(metadata.get("format-version", 2)) > 1 and seq is not None
+ and seq <= last and snapshot.get("parent-snapshot-id") is not None):
+ raise ValueError(
+ f"Cannot add snapshot with sequence number {seq} older than last sequence number {last}")
+ snapshots.append(snapshot)
metadata["current-snapshot-id"] = snapshot.get("snapshot-id", -1)
metadata["last-updated-ms"] = int(time.time() * 1000)
- metadata["last-sequence-number"] = metadata.get("last-sequence-number", 0) + 1
+ metadata["last-sequence-number"] = seq if seq is not None else last + 1
elif action == "set-snapshot-ref":
metadata.setdefault("refs", {})[update.get("ref-name", "main")] = {
"snapshot-id": update.get("snapshot-id", -1),
@@ -813,21 +903,25 @@ def _iceberg_commit_table(namespace, table_name, data, allow_cross_region, bucke
def _pred(table):
if _namespace_name(table) != namespace or table["name"] != table_name:
return False
- if bucket_filter:
- return table.get("tableBucketARN", "").endswith("/" + bucket_filter)
- return True
+ return _in_bucket(table.get("tableBucketARN", ""), bucket_filter)
matches = _iceberg_values(_tables, _pred, allow_cross_region)
if matches:
table = matches[0]
- # Stage the commit on a copy: a refused update (an illegal
- # format-version change) must not leave the earlier updates of the
- # same commit applied — an Iceberg commit is atomic.
- metadata = copy.deepcopy(table.get("_iceberg_metadata", {}))
+ # Stage the commit on a copy of the metadata a reader sees: a refused
+ # update must not leave the earlier updates applied (an Iceberg
+ # commit is atomic), and a stale base would desynchronize sequence
+ # numbers from what LoadTable served.
+ base, _ = _current_iceberg_metadata(table)
+ metadata = copy.deepcopy(base)
try:
+ _check_iceberg_requirements(metadata, data.get("requirements", []), staged=table.get("_staged", False))
_apply_iceberg_updates(metadata, data.get("updates", []))
+ except IcebergCommitFailed as exc:
+ return _iceberg_error(str(exc), "CommitFailedException", 409)
except ValueError as exc:
return _iceberg_error(str(exc), "BadRequestException", 400)
+ table["_staged"] = False
table["_iceberg_metadata"] = metadata
table["_metadata_version"] = table.get("_metadata_version", 0) + 1
@@ -853,11 +947,14 @@ def _iceberg_commit_table(namespace, table_name, data, allow_cross_region, bucke
return _iceberg_error(f"Table {namespace}.{table_name} not found", "NoSuchTableException", 404)
-def _iceberg_create_table(namespace, data, allow_cross_region):
+def _iceberg_create_table(namespace, data, allow_cross_region, bucket_filter=None):
table_name = data.get("name", "")
schema = data.get("schema", {})
bucket_arn = None
- matches = _iceberg_values(_namespaces, lambda ns: _namespace_name(ns) == namespace, allow_cross_region)
+ matches = _iceberg_values(
+ _namespaces,
+ lambda ns: _namespace_name(ns) == namespace and _in_bucket(ns.get("tableBucketARN", ""), bucket_filter),
+ allow_cross_region)
if matches:
bucket_arn = matches[0].get("tableBucketARN")
if not bucket_arn:
@@ -912,6 +1009,9 @@ def _iceberg_create_table(namespace, data, allow_cross_region):
"_iceberg_metadata": iceberg_metadata,
"_metadata_version": 0,
"_schema_fields": schema_fields,
+ # A staged create (stage-create) exists only once its first commit,
+ # which carries assert-create, lands.
+ "_staged": bool(data.get("stage-create")),
}
_set_bucket_region_value(_tables, bucket_arn, key, table)
return json_response({"metadata-location": metadata_location, "metadata": iceberg_metadata})
@@ -937,12 +1037,14 @@ async def _handle_iceberg_request(method, path, headers, body, query_params):
# a prefixed commit is silently dropped and the delivery writes nothing.
if parts[1] == "v1" and method == "POST" and "transactions" in parts[2:]:
data = json.loads(body) if body else {}
+ tx_idx = parts.index("transactions", 2)
+ tx_filter = _bucket_scope_from_prefix(unquote("/".join(parts[2:tx_idx]))) if tx_idx > 2 else None
for change in data.get("table-changes", []):
ident = change.get("identifier", {})
ns = ident.get("namespace", [""])
ns = ns[0] if isinstance(ns, list) else ns
tbl = ident.get("name", "")
- result = _iceberg_commit_table(ns, tbl, change, allow_cross_region)
+ result = _iceberg_commit_table(ns, tbl, change, allow_cross_region, tx_filter)
if result and result[0] not in (200, 204):
return result
return json_response({})
@@ -971,19 +1073,17 @@ async def _handle_iceberg_request(method, path, headers, body, query_params):
if ns_idx is None:
return None
if ns_idx > 2:
- prefix = unquote("/".join(parts[2:ns_idx]))
- if ":s3tablescatalog/" in prefix:
- bucket_filter = prefix.split(":s3tablescatalog/", 1)[1]
+ bucket_filter = _bucket_scope_from_prefix(unquote("/".join(parts[2:ns_idx])))
rest = parts[ns_idx + 1 :] # segments after "namespaces"
if len(rest) == 0 and method == "GET":
- return _iceberg_list_namespaces(allow_cross_region)
+ return _iceberg_list_namespaces(allow_cross_region, bucket_filter)
if len(rest) == 0 and method == "POST":
data = json.loads(body) if body else {}
return _iceberg_create_namespace(data, allow_cross_region, bucket_filter)
if len(rest) == 1 and method == "GET":
- return _iceberg_get_namespace(rest[0], allow_cross_region)
+ return _iceberg_get_namespace(rest[0], allow_cross_region, bucket_filter)
if len(rest) >= 2 and rest[1] == "tables":
namespace = rest[0]
table_rest = rest[2:]
@@ -992,7 +1092,7 @@ async def _handle_iceberg_request(method, path, headers, body, query_params):
return _iceberg_list_tables(namespace, allow_cross_region, bucket_filter)
if method == "POST":
data = json.loads(body) if body else {}
- return _iceberg_create_table(namespace, data, allow_cross_region)
+ return _iceberg_create_table(namespace, data, allow_cross_region, bucket_filter)
if len(table_rest) == 1:
table_name = table_rest[0]
if method == "GET":
@@ -1003,7 +1103,8 @@ async def _handle_iceberg_request(method, path, headers, body, query_params):
if method == "HEAD":
if _iceberg_values(
_tables,
- lambda table: _namespace_name(table) == namespace and table["name"] == table_name,
+ lambda table: (_namespace_name(table) == namespace and table["name"] == table_name
+ and _in_bucket(table.get("tableBucketARN", ""), bucket_filter)),
allow_cross_region,
):
return 200, {}, b""
diff --git a/ministack/services/ses.py b/ministack/services/ses.py
index 83acee4a..b80f2211 100644
--- a/ministack/services/ses.py
+++ b/ministack/services/ses.py
@@ -503,6 +503,10 @@ def _send_email(params):
def _missing_domain(value: str) -> bool:
+ """SES answers "Missing final '@domain'" for an address without a domain
+ and for one with non-ASCII characters ("must be 7-bit ASCII")."""
+ if not value.isascii():
+ return True
_, separator, domain = parseaddr(value)[1].rpartition("@")
return not separator or not domain
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index c06762d3..1863fc81 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -1173,12 +1173,11 @@ def _fanout(topic_arn: str, msg_id: str, message: str, subject: str,
protocol = sub.get("protocol", "")
endpoint = sub.get("endpoint", "")
- if not _matches_filter_policy(sub, message_attributes or {}):
- continue
-
effective_message = _resolve_message_for_protocol(
message, message_structure, protocol
)
+ if not _matches_filter_policy(sub, message_attributes or {}, effective_message):
+ continue
raw = sub.get("attributes", {}).get("RawMessageDelivery", "false") == "true"
envelope = _build_envelope(
@@ -1801,7 +1800,7 @@ def _resolve_message_for_protocol(message: str, message_structure: str,
return parsed.get(protocol, parsed.get("default", message))
-def _matches_filter_policy(sub: dict, message_attributes: dict) -> bool:
+def _matches_filter_policy(sub: dict, message_attributes: dict, message: str = "") -> bool:
policy_json = sub.get("attributes", {}).get("FilterPolicy", "")
if not policy_json:
return True
@@ -1813,16 +1812,20 @@ def _matches_filter_policy(sub: dict, message_attributes: dict) -> bool:
return True
scope = sub.get("attributes", {}).get("FilterPolicyScope", "MessageAttributes")
-
if scope == "MessageBody":
- return True
-
- return _policy_matches(policy, message_attributes)
+ # "Filter policies for the message body assume that the message payload
+ # is a well-formed JSON object"; anything else is filtered out.
+ try:
+ body = json.loads(message)
+ except (json.JSONDecodeError, TypeError):
+ return False
+ return isinstance(body, dict) and _policy_matches(policy, _body_lookup(body), nested=True)
+ return _policy_matches(policy, _attribute_lookup(message_attributes))
_OR_RESERVED_MEMBER_KEYS = frozenset({
"anything-but", "prefix", "suffix", "equals-ignore-case",
- "numeric", "exists", "cidr",
+ "numeric", "exists", "cidr", "wildcard",
})
@@ -1841,29 +1844,64 @@ def _is_or_operator(value) -> bool:
return True
-def _policy_matches(policy: dict, message_attributes: dict) -> bool:
- """Match one filter-policy object against the message attributes. Sibling
- keys are AND-ed; a recognized ``$or`` matches when any of its member
- policies matches (evaluated recursively, so nested ``$or`` works)."""
- for key, allowed_values in policy.items():
- if key == "$or" and _is_or_operator(allowed_values):
- if not any(_policy_matches(member, message_attributes)
- for member in allowed_values):
- return False
- continue
+def _attribute_lookup(message_attributes: dict):
+ """Lookup over message attributes: key -> (present, values, nonempty)."""
+ def lookup(key):
attr = message_attributes.get(key)
if attr is None:
- return False
- if not isinstance(allowed_values, list):
- allowed_values = [allowed_values]
- # A String.Array attribute carries a JSON array of values; AWS evaluates
- # each element separately and the attribute matches if any element does.
- candidates = _attr_candidate_values(attr)
- if not any(_attr_matches_any(value, allowed_values) for value in candidates):
+ return False, [], bool(message_attributes)
+ return True, _attr_candidate_values(attr), True
+ lookup.child = None
+ return lookup
+
+
+def _body_lookup(body: dict):
+ """Lookup over a JSON body; an array value matches if any element does."""
+ def lookup(key):
+ if key not in body or body[key] is None:
+ return False, [], bool(body)
+ value = body[key]
+ return True, (value if isinstance(value, list) else [value]), True
+ lookup.child = lambda key: _body_lookup(body[key]) if isinstance(body.get(key), dict) else None
+ return lookup
+
+
+def _policy_matches(policy: dict, lookup, nested: bool = False) -> bool:
+ """Match one filter-policy object. Sibling keys are AND-ed; a recognized
+ ``$or`` matches when any member policy matches; on a message body a nested
+ policy object matches the nested property."""
+ for key, rules in policy.items():
+ if key == "$or" and _is_or_operator(rules):
+ if not any(_policy_matches(member, lookup, nested) for member in rules):
+ return False
+ continue
+ if nested and isinstance(rules, dict):
+ child = lookup.child(key)
+ if child is None or not _policy_matches(rules, child, nested):
+ return False
+ continue
+ if not isinstance(rules, list):
+ rules = [rules]
+ present, values, nonempty = lookup(key)
+ if not _key_matches(rules, present, values, nonempty):
return False
return True
+def _key_matches(rules: list, present: bool, values: list, nonempty: bool) -> bool:
+ for rule in rules:
+ if isinstance(rule, dict) and "exists" in rule:
+ # "exists": false "only matches if at least one attribute is present".
+ if rule["exists"] is True and present and any(v not in ("", None) for v in values):
+ return True
+ if rule["exists"] is False and not present and nonempty:
+ return True
+ continue
+ if present and any(_value_matches(value, rule) for value in values):
+ return True
+ return False
+
+
def _attr_candidate_values(attr: dict) -> list:
"""Values to match a message attribute against a filter policy. A scalar
attribute yields its single StringValue; a String.Array yields each element
@@ -1888,40 +1926,67 @@ def _attr_candidate_values(attr: dict) -> list:
return values or [raw]
-def _attr_matches_any(attr_value: str, rules: list) -> bool:
- for rule in rules:
- if isinstance(rule, str):
- if attr_value == rule:
- return True
- elif isinstance(rule, (int, float)):
- try:
- if float(attr_value) == float(rule):
- return True
- except (ValueError, TypeError):
- pass
- elif isinstance(rule, dict):
- if "exists" in rule:
- if rule["exists"] is True:
- return True
- continue
- if "prefix" in rule:
- if attr_value.startswith(rule["prefix"]):
- return True
- if "anything-but" in rule:
- excluded = rule["anything-but"]
- if isinstance(excluded, list):
- if attr_value not in excluded:
- return True
- elif attr_value != str(excluded):
- return True
- if "numeric" in rule:
- try:
- num = float(attr_value)
- conditions = rule["numeric"]
- if _check_numeric(num, conditions):
- return True
- except (ValueError, TypeError):
- pass
+def _as_number(value):
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, (int, float)):
+ return float(value)
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def _wildcard_matches(value: str, pattern: str) -> bool:
+ """`*` matches any run of characters; everything else is literal."""
+ return _re.fullmatch(".*".join(_re.escape(part) for part in pattern.split("*")), value, _re.S) is not None
+
+
+def _cidr_matches(value: str, cidr: str) -> bool:
+ import ipaddress
+ try:
+ return ipaddress.ip_address(value) in ipaddress.ip_network(cidr, strict=False)
+ except ValueError:
+ return False
+
+
+def _string_rule_matches(value, rule: dict) -> bool:
+ if not isinstance(value, str):
+ return False
+ if "wildcard" in rule:
+ return isinstance(rule["wildcard"], str) and _wildcard_matches(value, rule["wildcard"])
+ if "cidr" in rule:
+ return isinstance(rule["cidr"], str) and _cidr_matches(value, rule["cidr"])
+ if "prefix" in rule:
+ return isinstance(rule["prefix"], str) and value.startswith(rule["prefix"])
+ if "suffix" in rule:
+ return isinstance(rule["suffix"], str) and value.endswith(rule["suffix"])
+ if "equals-ignore-case" in rule:
+ return isinstance(rule["equals-ignore-case"], str) and value.lower() == rule["equals-ignore-case"].lower()
+ return False
+
+
+def _value_matches(value, rule) -> bool:
+ if isinstance(rule, bool) or rule is None:
+ return value is rule or (isinstance(value, str) and value == json.dumps(rule))
+ if isinstance(rule, str):
+ return isinstance(value, str) and value == rule
+ if isinstance(rule, (int, float)):
+ num = _as_number(value)
+ return num is not None and num == float(rule)
+ if not isinstance(rule, dict):
+ return False
+ if any(k in rule for k in ("prefix", "suffix", "equals-ignore-case", "wildcard", "cidr")):
+ return _string_rule_matches(value, rule)
+ if "anything-but" in rule:
+ excluded = rule["anything-but"]
+ if isinstance(excluded, dict):
+ return isinstance(value, str) and not _string_rule_matches(value, excluded)
+ excluded = excluded if isinstance(excluded, list) else [excluded]
+ return not any(_value_matches(value, e) for e in excluded)
+ if "numeric" in rule:
+ num = _as_number(value)
+ return num is not None and _check_numeric(num, rule["numeric"])
return False
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index b48c76a5..f1eae5c1 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -765,6 +765,7 @@ async def _act_receive_message(data: dict, qurl: str) -> dict:
msgs: list = []
while True:
+ _expire_retained(q)
_dlq_sweep(q)
msgs = _collect_msgs(q, max_n, vis)
if msgs or time.time() >= deadline:
@@ -1253,8 +1254,27 @@ def _ensure_msg_fields(m: dict) -> None:
m.setdefault("seq", None)
+def _expire_retained(q: dict) -> None:
+ """Drop messages older than MessageRetentionPeriod ("The length of time,
+ in seconds, for which Amazon SQS retains a message"), measured from the
+ enqueue time: the send, or a FIFO dead-letter move."""
+ try:
+ retention = int(q["attributes"].get("MessageRetentionPeriod", "345600"))
+ except (TypeError, ValueError):
+ return
+ now = time.time()
+ cutoff = now - retention
+
+ def enqueued(m):
+ return m.get("enqueued_at", m.get("sent_at", now))
+
+ if any(enqueued(m) <= cutoff for m in q["messages"]):
+ q["messages"] = [m for m in q["messages"] if enqueued(m) > cutoff]
+
+
def _refresh_counts(q: dict) -> None:
"""Recompute approximate message counters."""
+ _expire_retained(q)
now = time.time()
visible = delayed = inflight = 0
for m in q["messages"]:
@@ -1358,6 +1378,12 @@ def _dlq_sweep(q: dict) -> None:
moved = dict(m)
moved["receipt_handle"] = None
moved["visible_at"] = now
+ # Standard keeps the original enqueue timestamp; "For FIFO queues,
+ # the enqueue timestamp resets when the message is moved".
+ if dlq.get("is_fifo"):
+ moved["enqueued_at"] = now
+ moved["sys"] = {**m.get("sys", {})}
+ moved["sys"].setdefault("DeadLetterQueueSourceArn", q["attributes"].get("QueueArn", ""))
dlq["messages"].append(moved)
esm_wake.set()
else:
@@ -1424,6 +1450,9 @@ def _build_sys_attrs(msg: dict, names: list) -> dict:
trace = msg["sys"].get("AWSTraceHeader")
if trace and (want_all or "AWSTraceHeader" in names):
r["AWSTraceHeader"] = trace
+ source = msg["sys"].get("DeadLetterQueueSourceArn")
+ if source and (want_all or "DeadLetterQueueSourceArn" in names):
+ r["DeadLetterQueueSourceArn"] = source
return r
@@ -1962,6 +1991,7 @@ def _receive_messages_for_esm(queue_url: str, max_number: int) -> list[dict]:
q = _get_q(queue_url)
max_n = min(int(max_number or 1), 10)
vis = int(q["attributes"].get("VisibilityTimeout", "30"))
+ _expire_retained(q)
_dlq_sweep(q)
return _collect_msgs(q, max_n, vis)
diff --git a/tests/test_cloudwatch.py b/tests/test_cloudwatch.py
index ecc4b613..40790e1e 100644
--- a/tests/test_cloudwatch.py
+++ b/tests/test_cloudwatch.py
@@ -1061,3 +1061,13 @@ def test_cloudwatch_query_protocol_put_metric_data_values_and_statistic_values()
dp = cw.get_metric_statistics(Namespace=ns, MetricName=name, StartTime=ts - 60, EndTime=ts + 3000,
Period=3600, Statistics=["SampleCount", "Sum"])["Datapoints"][0]
assert (dp["SampleCount"], dp["Sum"]) == expected
+
+
+def test_cloudwatch_parse_ts_accepts_cbor_datetime():
+ from datetime import datetime, timezone
+
+ from ministack.services.cloudwatch import _parse_ts
+ ts = datetime(2026, 10, 6, 12, 30, tzinfo=timezone.utc)
+ assert _parse_ts(ts) == ts.timestamp()
+ assert _parse_ts(ts.replace(tzinfo=None)) == ts.timestamp()
+
diff --git a/tests/test_dynamodb_streams.py b/tests/test_dynamodb_streams.py
index 126048ec..5eb9cf8d 100644
--- a/tests/test_dynamodb_streams.py
+++ b/tests/test_dynamodb_streams.py
@@ -472,13 +472,13 @@ def test_get_records_iterator_position_survives_record_expiry(streams_state):
for record in ddb_service._stream_records[name][:2]:
record["dynamodb"]["ApproximateCreationDateTime"] = int(expired)
- second = _json(streams_service._get_records({"ShardIterator": first["NextShardIterator"]}))
- assert _seqs(second) == ["2"]
+ # The held iterator now points at a trimmed record: TrimmedDataAccessException.
+ trimmed = _json(streams_service._get_records({"ShardIterator": first["NextShardIterator"]}))
+ assert trimmed["__type"].endswith("TrimmedDataAccessException")
assert ddb_service.stream_start_position(name) == 2
- # And the iterator it hands back is past the end, not back inside the list.
- assert _seqs(_json(streams_service._get_records({
- "ShardIterator": second["NextShardIterator"],
- }))) == []
+ # A fresh TRIM_HORIZON iterator resumes at the surviving record.
+ second = _json(streams_service._get_records({"ShardIterator": _iterator(streams_service, arn, "TRIM_HORIZON")}))
+ assert _seqs(second) == ["2"]
def test_shard_iterators_are_absolute_after_a_trim(streams_state):
@@ -584,3 +584,30 @@ def test_closed_stream_stays_readable_and_new_stream_starts_empty(ddb, ddb_strea
finally:
with contextlib.suppress(ClientError):
ddb.delete_table(TableName=name)
+
+
+def test_shard_iterator_expires_after_15_minutes(streams_state, monkeypatch):
+ ddb_service, streams_service, time = streams_state
+ name = "streams-iterator-ttl"
+ arn = _streamed_table(ddb_service, name)
+ ddb_service._stream_records[name] = [_record(0, time.time())]
+ iterator = _iterator(streams_service, arn, "TRIM_HORIZON")
+ issued = time.time()
+ monkeypatch.setattr(streams_service.time, "time", lambda: issued + 15 * 60 - 1)
+ assert _seqs(_json(streams_service._get_records({"ShardIterator": iterator}))) == ["0"]
+ monkeypatch.setattr(streams_service.time, "time", lambda: issued + 15 * 60)
+ assert _json(streams_service._get_records({"ShardIterator": iterator}))["__type"].endswith(
+ "ExpiredIteratorException")
+
+
+def test_unknown_shard_is_resource_not_found(ddb, ddb_streams):
+ name = f"unknown-shard-{uuid.uuid4().hex[:8]}"
+ _make_table(ddb, name)
+ try:
+ with pytest.raises(ClientError) as exc:
+ ddb_streams.get_shard_iterator(StreamArn=_stream_arn(ddb, name), ShardId="shardId-00000000000000000000-ffffffff",
+ ShardIteratorType="TRIM_HORIZON")
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ assert exc.value.response["Error"]["Message"] == "Requested resource not found: Shard does not exist"
+ finally:
+ ddb.delete_table(TableName=name)
diff --git a/tests/test_ministack.py b/tests/test_ministack.py
index 45b9cbe7..e54665f2 100644
--- a/tests/test_ministack.py
+++ b/tests/test_ministack.py
@@ -1027,3 +1027,25 @@ def test_incomplete_non_s3_body_is_dispatched_without_s3_error(monkeypatch):
asyncio.run(app_module.app(scope, receive, send))
assert all(b"IncompleteBody" not in m.get("body", b"") for m in sent)
assert len(dispatched) == 1 and dispatched[0][3] == b"Action=ListQueues"
+
+
+def test_drop_containers_logs_the_ids_it_could_not_remove(caplog):
+ import logging
+
+ from ministack.core import container_reaper
+
+ class _C:
+ def __init__(self, cid, fail):
+ self.id, self.fail = cid, fail
+
+ def stop(self, timeout=None):
+ if self.fail:
+ raise RuntimeError("gone")
+
+ def remove(self, v=False, force=False):
+ pass
+
+ with caplog.at_level(logging.WARNING, logger="container_reaper"):
+ removed = container_reaper.drop_containers([_C("a" * 64, False), _C("b" * 64, True)])
+ assert removed == 1
+ assert "bbbbbbbbbbbb" in caplog.text and "aaaaaaaaaaaa" not in caplog.text
diff --git a/tests/test_pipes.py b/tests/test_pipes.py
index 1a0b9e84..ed6a4093 100644
--- a/tests/test_pipes.py
+++ b/tests/test_pipes.py
@@ -747,3 +747,21 @@ def test_list_tags_unknown_arn_not_found(handler_env):
status, _hdrs, b = _req("GET", f"/tags/{enc}")
assert status == 404
assert _body((status, _hdrs, b))["__type"] == "NotFoundException"
+
+
+def test_pipe_refuses_sns_fifo_target():
+ import uuid
+
+ import boto3
+ from botocore.exceptions import ClientError
+ from conftest import ENDPOINT
+ kw = dict(endpoint_url=ENDPOINT, region_name="us-east-1", aws_access_key_id="test", aws_secret_access_key="test")
+ pipes, sqs = boto3.client("pipes", **kw), boto3.client("sqs", **kw)
+ name = f"fifo-target-{uuid.uuid4().hex[:8]}"
+ qarn = sqs.get_queue_attributes(QueueUrl=sqs.create_queue(QueueName=name)["QueueUrl"],
+ AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ with pytest.raises(ClientError) as exc:
+ pipes.create_pipe(Name=name, Source=qarn, RoleArn="arn:aws:iam::000000000000:role/r",
+ Target=f"arn:aws:sns:us-east-1:000000000000:{name}.fifo")
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+ assert exc.value.response["Error"]["Message"] == "SNS FIFO topics are not supported as a pipe target."
diff --git a/tests/test_s3tables.py b/tests/test_s3tables.py
index 83c55c4d..7aa80803 100644
--- a/tests/test_s3tables.py
+++ b/tests/test_s3tables.py
@@ -10,9 +10,11 @@ Operations covered:
Shapes verified against `botocore.data.s3tables.2024-12-01.service-2`.
"""
+import contextlib
import json
import os
import urllib.error
+import urllib.parse
import urllib.request
import uuid as _uuid_mod
@@ -1160,3 +1162,89 @@ def test_iceberg_unknown_path_answers_404_envelope():
assert e.code == 404
doc = json.loads(e.read())
assert doc["error"]["type"] == "NotFoundException"
+
+
+def _iceberg_call(path, method="GET", payload=None):
+ try:
+ return 200, _iceberg_json(path, method, payload)
+ except urllib.error.HTTPError as exc:
+ return exc.code, json.loads(exc.read().decode("utf-8") or "{}")
+
+
+def _arn_prefix(arn):
+ return urllib.parse.quote(arn, safe="")
+
+
+def test_s3tables_iceberg_rest_scopes_each_catalog_to_its_warehouse_arn(s3tables):
+ """Two catalogs, each with its table-bucket ARN as warehouse; the REST
+ {prefix} "is always your url-encoded table bucket ARN"."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ arns = [s3tables.create_table_bucket(name=f"wh-{n}-{suffix}")["arn"] for n in ("std", "qual")]
+ try:
+ for arn in arns:
+ p = _arn_prefix(arn)
+ assert _iceberg_call(f"/iceberg/v1/{p}/namespaces", "POST", {"namespace": ["ns"]})[0] == 200
+ status, created = _iceberg_call(f"/iceberg/v1/{p}/namespaces/ns/tables", "POST", {
+ "name": "t", "schema": {"type": "struct", "schema-id": 0,
+ "fields": [{"id": 1, "name": "id", "type": "long", "required": False}]}})
+ assert status == 200, created
+ for arn in arns:
+ p = _arn_prefix(arn)
+ bucket = arn.rsplit("/", 1)[-1]
+ status, loaded = _iceberg_call(f"/iceberg/v1/{p}/namespaces/ns/tables/t")
+ assert status == 200
+ assert loaded["metadata-location"].startswith(f"s3://{bucket}/")
+ assert _iceberg_call(f"/iceberg/v1/{p}/namespaces/ns/tables")[1]["identifiers"] == [
+ {"namespace": ["ns"], "name": "t"}]
+ finally:
+ for arn in arns:
+ with contextlib.suppress(Exception):
+ s3tables.delete_table(tableBucketARN=arn, namespace="ns", name="t")
+ s3tables.delete_namespace(tableBucketARN=arn, namespace="ns")
+ s3tables.delete_table_bucket(tableBucketARN=arn)
+
+
+def test_s3tables_iceberg_rest_sequence_numbers_and_requirements(s3tables):
+ arn = s3tables.create_table_bucket(name=f"seq-{_uuid_mod.uuid4().hex[:8]}")["arn"]
+ p = _arn_prefix(arn)
+ table = f"/iceberg/v1/{p}/namespaces/ns/tables/t"
+ try:
+ _iceberg_call(f"/iceberg/v1/{p}/namespaces", "POST", {"namespace": ["ns"]})
+ _iceberg_call(f"/iceberg/v1/{p}/namespaces/ns/tables", "POST", {
+ "name": "t", "format-version": 2, "schema": {"type": "struct", "schema-id": 0, "fields": [
+ {"id": 1, "name": "id", "type": "long", "required": False}]}})
+
+ def append(seq, snap_id, parent, expected_ref):
+ snapshot = {"snapshot-id": snap_id, "sequence-number": seq, "timestamp-ms": 1_700_000_000_000 + seq,
+ "manifest-list": f"s3://x/{snap_id}.avro", "summary": {"operation": "append"}}
+ if parent is not None:
+ snapshot["parent-snapshot-id"] = parent
+ return _iceberg_call(table, "POST", {
+ "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": expected_ref}],
+ "updates": [{"action": "add-snapshot", "snapshot": snapshot},
+ {"action": "set-snapshot-ref", "ref-name": "main", "type": "branch",
+ "snapshot-id": snap_id}]})
+
+ for seq in (1, 2, 3): # sequential Spark appends
+ status, body = append(seq, 100 + seq, (99 + seq) if seq > 1 else None, (99 + seq) if seq > 1 else None)
+ assert status == 200, body
+ assert body["metadata"]["last-sequence-number"] == seq
+ assert _iceberg_call(table)[1]["metadata"]["last-sequence-number"] == 3
+
+ # A writer that loaded the table before the last commit is refused.
+ status, body = append(3, 200, 102, 102)
+ assert status == 409
+ assert body["error"]["type"] == "CommitFailedException"
+ assert body["error"]["message"] == "Requirement failed: branch main has changed: expected id 102 != 103"
+
+ # A snapshot not newer than the table's last sequence number is refused.
+ status, body = _iceberg_call(table, "POST", {"updates": [{"action": "add-snapshot", "snapshot": {
+ "snapshot-id": 300, "sequence-number": 3, "parent-snapshot-id": 103, "timestamp-ms": 1_800_000_000_000,
+ "manifest-list": "s3://x/300.avro", "summary": {"operation": "append"}}}]})
+ assert status == 400
+ assert body["error"]["message"] == "Cannot add snapshot with sequence number 3 older than last sequence number 3"
+ finally:
+ with contextlib.suppress(Exception):
+ s3tables.delete_table(tableBucketARN=arn, namespace="ns", name="t")
+ s3tables.delete_namespace(tableBucketARN=arn, namespace="ns")
+ s3tables.delete_table_bucket(tableBucketARN=arn)
diff --git a/tests/test_ses.py b/tests/test_ses.py
index 47286879..4d405786 100644
--- a/tests/test_ses.py
+++ b/tests/test_ses.py
@@ -1722,3 +1722,17 @@ def test_ses_identity_notifications_not_published_without_topic(ses, sns, ses_no
Source=sender, Destination={"ToAddresses": ["[email protected]"]}, Message=_NOTIFY_MSG)
assert drain(1) == []
+
+
+def test_ses_send_email_rejects_non_ascii_address(ses):
+ ses.verify_email_identity(EmailAddress="[email protected]")
+ for to in ("us\[email protected]", "user@\u00e9xample.com"):
+ with pytest.raises(ClientError) as exc:
+ ses.send_email(Source="[email protected]", Destination={"ToAddresses": [to]},
+ Message={"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}})
+ assert exc.value.response["Error"]["Code"] == "InvalidParameterValue"
+ assert exc.value.response["Error"]["Message"] == "Missing final '@domain'"
+ ses.verify_email_identity(EmailAddress="[email protected]")
+ ses.send_email(Source="[email protected]", Destination={"ToAddresses": ["[email protected]"]},
+ Message={"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}})
+
diff --git a/tests/test_sns.py b/tests/test_sns.py
index 657ffec3..4836e1fc 100644
--- a/tests/test_sns.py
+++ b/tests/test_sns.py
@@ -2329,3 +2329,59 @@ def test_sns_to_sqs_delivery_waits_for_queue_delay(sns, sqs):
finally:
sns.delete_topic(TopicArn=topic)
sqs.delete_queue(QueueUrl=url)
+
+
+def _filter_queue(sns, sqs, name, policy, scope=None):
+ topic = sns.create_topic(Name=name)["TopicArn"]
+ url = sqs.create_queue(QueueName=name)["QueueUrl"]
+ qarn = sqs.get_queue_attributes(QueueUrl=url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(QueueUrl=url, Attributes={"Policy": json.dumps(sqs_policy_allow_sns(qarn, topic))})
+ attrs = {"RawMessageDelivery": "true", "FilterPolicy": json.dumps(policy)}
+ if scope:
+ attrs["FilterPolicyScope"] = scope
+ sns.subscribe(TopicArn=topic, Protocol="sqs", Endpoint=qarn, Attributes=attrs)
+ return topic, url
+
+
+def _bodies(sqs, url):
+ return sorted(m["Body"] for m in sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=10).get("Messages", []))
+
+
+def test_sns_filter_suffix_and_equals_ignore_case(sns, sqs):
+ for op, policy, match, other in (("suffix", {"f": [{"suffix": ".png"}]}, "a.png", "a.jpg"),
+ ("eqic", {"f": [{"equals-ignore-case": "RED"}]}, "red", "blue")):
+ name = f"op-{op}-{_uuid_mod.uuid4().hex[:8]}"
+ topic, url = _filter_queue(sns, sqs, name, policy)
+ for v in (match, other):
+ sns.publish(TopicArn=topic, Message=v, MessageAttributes={"f": {"DataType": "String", "StringValue": v}})
+ assert _bodies(sqs, url) == [match]
+
+
+def test_sns_filter_policy_scope_message_body(sns, sqs):
+ name = f"body-filter-{_uuid_mod.uuid4().hex[:8]}"
+ policy = {"kind": ["wanted"], "detail": {"size": [{"numeric": [">", 10]}]}, "tags": [{"suffix": "-x"}]}
+ topic, url = _filter_queue(sns, sqs, name, policy, scope="MessageBody")
+ good = json.dumps({"kind": "wanted", "detail": {"size": 11}, "tags": ["a", "b-x"]})
+ for body in (good, json.dumps({"kind": "other", "detail": {"size": 11}, "tags": ["b-x"]}),
+ json.dumps({"kind": "wanted", "detail": {"size": 5}, "tags": ["b-x"]}), "not json"):
+ sns.publish(TopicArn=topic, Message=body)
+ assert _bodies(sqs, url) == [good]
+
+
+def test_sns_filter_exists_false(sns, sqs):
+ name = f"exists-false-{_uuid_mod.uuid4().hex[:8]}"
+ topic, url = _filter_queue(sns, sqs, name, {"store": [{"exists": False}]})
+ sns.publish(TopicArn=topic, Message="no-store", MessageAttributes={"other": {"DataType": "String", "StringValue": "x"}})
+ sns.publish(TopicArn=topic, Message="has-store", MessageAttributes={"store": {"DataType": "String", "StringValue": "fans"}})
+ sns.publish(TopicArn=topic, Message="no-attributes")
+ assert _bodies(sqs, url) == ["no-store"]
+
+
+def test_sns_filter_wildcard_and_cidr(sns, sqs):
+ for op, policy, match, other in (("wild", {"f": [{"wildcard": "*ball"}]}, "baseball", "rugby"),
+ ("cidr", {"f": [{"cidr": "10.0.0.0/24"}]}, "10.0.0.255", "10.1.1.0")):
+ name = f"op-{op}-{_uuid_mod.uuid4().hex[:8]}"
+ topic, url = _filter_queue(sns, sqs, name, policy)
+ for v in (match, other):
+ sns.publish(TopicArn=topic, Message=v, MessageAttributes={"f": {"DataType": "String", "StringValue": v}})
+ assert _bodies(sqs, url) == [match]
diff --git a/tests/test_sqs.py b/tests/test_sqs.py
index 460370cc..de59e41a 100644
--- a/tests/test_sqs.py
+++ b/tests/test_sqs.py
@@ -2317,3 +2317,81 @@ def test_sqs_receive_max_number_of_messages_out_of_range(sqs, value):
"Reason: Must be between 1 and 10, if provided.")
finally:
sqs.delete_queue(QueueUrl=url)
+
+
+class _SqsClock:
+ def __init__(self, start):
+ self.now = start
+
+ def time(self):
+ return self.now
+
+
+def _sqs_inproc(monkeypatch):
+ import asyncio
+ import time as _time
+
+ from ministack.core.responses import set_request_account_id, set_request_region
+ set_request_account_id("000000000000")
+ set_request_region("us-east-1")
+ clock = _SqsClock(_time.time())
+ monkeypatch.setattr(sqs_svc.time, "time", clock.time)
+
+ def create(name, **attrs):
+ return sqs_svc._act_create_queue(
+ {"QueueName": name, "Attributes": {k: str(v) for k, v in attrs.items()}}, "")["QueueUrl"]
+
+ def counts(url):
+ a = sqs_svc._act_get_queue_attributes({"QueueUrl": url, "AttributeNames": ["All"]}, url)["Attributes"]
+ return int(a["ApproximateNumberOfMessages"]), int(a["ApproximateNumberOfMessagesNotVisible"])
+
+ def receive(url, **kw):
+ return asyncio.run(sqs_svc._act_receive_message({"QueueUrl": url, "WaitTimeSeconds": 0, **kw}, url))
+
+ return clock, create, counts, receive
+
+
+def test_sqs_retention_expires_messages(monkeypatch):
+ clock, create, counts, receive = _sqs_inproc(monkeypatch)
+ url = create(f"ret-{_uuid_mod.uuid4().hex[:8]}", MessageRetentionPeriod=60, VisibilityTimeout=120)
+ sqs_svc._act_send_message({"QueueUrl": url, "MessageBody": "a"}, url)
+ sqs_svc._act_send_message({"QueueUrl": url, "MessageBody": "b"}, url)
+ receive(url, MaxNumberOfMessages=1) # one message in flight
+ clock.now += 59
+ assert counts(url) == (1, 1)
+ clock.now += 1
+ assert counts(url) == (0, 0)
+ # Lowering the period expires messages already in the queue.
+ sqs_svc._act_send_message({"QueueUrl": url, "MessageBody": "c"}, url)
+ sqs_svc._act_set_queue_attributes({"QueueUrl": url, "Attributes": {"MessageRetentionPeriod": "120"}}, url)
+ clock.now += 70
+ assert counts(url) == (1, 0)
+ sqs_svc._act_set_queue_attributes({"QueueUrl": url, "Attributes": {"MessageRetentionPeriod": "60"}}, url)
+ assert counts(url) == (0, 0)
+
+
[email protected]("fifo", [False, True])
+def test_sqs_dlq_move_enqueue_time_and_source_arn(monkeypatch, fifo):
+ clock, create, counts, receive = _sqs_inproc(monkeypatch)
+ sfx = ".fifo" if fifo else ""
+ extra = {"FifoQueue": "true", "ContentBasedDeduplication": "true"} if fifo else {}
+ dlq = create(f"dlq-{_uuid_mod.uuid4().hex[:8]}{sfx}", MessageRetentionPeriod=120, **extra)
+ dlq_arn = sqs_svc._act_get_queue_attributes({"QueueUrl": dlq, "AttributeNames": ["QueueArn"]}, dlq)["Attributes"]["QueueArn"]
+ src = create(f"src-{_uuid_mod.uuid4().hex[:8]}{sfx}", VisibilityTimeout=30, **extra,
+ RedrivePolicy=json.dumps({"maxReceiveCount": 1, "deadLetterTargetArn": dlq_arn}))
+ src_arn = sqs_svc._act_get_queue_attributes({"QueueUrl": src, "AttributeNames": ["QueueArn"]}, src)["Attributes"]["QueueArn"]
+ send = {"QueueUrl": src, "MessageBody": "x"}
+ if fifo:
+ send["MessageGroupId"] = "g"
+ sent = sqs_svc._act_send_message(send, src)
+ sent_at = clock.now
+ receive(src) # receive count 1
+ clock.now += 31 # visibility timeout over
+ assert receive(src).get("Messages", []) == [] # the sweep moves it to the DLQ
+ got = receive(dlq, AttributeNames=["All"])["Messages"][0]
+ assert got["MessageId"] == sent["MessageId"]
+ assert got["Attributes"]["DeadLetterQueueSourceArn"] == src_arn
+ clock.now = sent_at + 120 # 120 s after the original send
+ remaining = sum(counts(dlq))
+ # Standard keeps the original enqueue time (expired); FIFO reset it on the move (still there).
+ assert remaining == (1 if fifo else 0)