Skip to content

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

Add region-scoped DynamoDB metadata state

Ian Oberst5ac9d525890f
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index 18025ee6..2730675f 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -74,27 +74,27 @@ from ministack.core.persistence import PERSIST_STATE, load_state
# validate spec.region == request region) rejected them — a self-contradiction
# (B7). Legacy account-scoped persistence migrates via the table's TableArn.
_tables = AccountRegionScopedDict()
-_tags = AccountScopedDict()
-_ttl_settings = AccountScopedDict()
-_pitr_settings = AccountScopedDict()
+_tags = AccountRegionScopedDict()
+_ttl_settings = AccountRegionScopedDict()
+_pitr_settings = AccountRegionScopedDict()
# Kinesis streaming destinations — TableName -> list of
# {"StreamArn": str, "DestinationStatus": "ACTIVE"|"DISABLED",
# "ApproximateCreationDateTimePrecision": "MILLISECOND"|"MICROSECOND"}.
# ACTIVE entries get each _emit_stream_event record fanned out via
# kinesis.put_record_internal; DISABLED entries stay on the describe
# response (matching the ~24 h AWS retention window for readability).
-_kinesis_destinations = AccountScopedDict()
+_kinesis_destinations = AccountRegionScopedDict()
# Contributor Insights — key is "TableName" or "TableName/index/IndexName".
# Value: {"ContributorInsightsStatus": "ENABLED"|"DISABLED",
# "LastUpdateDateTime": float epoch, "ContributorInsightsRuleList": [str, ...]}.
-_backups = AccountScopedDict() # BackupArn -> BackupDescription dict
-_contributor_insights = AccountScopedDict()
+_backups = AccountRegionScopedDict() # BackupArn -> BackupDescription dict
+_contributor_insights = AccountRegionScopedDict()
# Resource-based policies — ResourceArn -> {"Policy": str, "RevisionId": str}.
-_resource_policies = AccountScopedDict()
+_resource_policies = AccountRegionScopedDict()
# Export tasks — ExportArn -> ExportDescription dict.
-_exports = AccountScopedDict()
+_exports = AccountRegionScopedDict()
# Import tasks — ImportArn -> ImportTableDescription dict.
-_imports = AccountScopedDict()
+_imports = AccountRegionScopedDict()
_lock = threading.Lock()
@@ -115,6 +115,74 @@ def get_state():
}
+def _table_name_from_metadata_key(key) -> str:
+ if not isinstance(key, str):
+ return str(key)
+ return key.split("/index/", 1)[0]
+
+
+def _metadata_value_region(value) -> str | None:
+ if isinstance(value, str) and value.startswith("arn:"):
+ try:
+ spec = parse_arn(value)
+ except ArnParseError:
+ return None
+ return spec.region or None
+ if isinstance(value, dict):
+ for nested in value.values():
+ region = _metadata_value_region(nested)
+ if region:
+ return region
+ if isinstance(value, (list, tuple, set)):
+ for nested in value:
+ region = _metadata_value_region(nested)
+ if region:
+ return region
+ return None
+
+
+def _legacy_regions_for_table_metadata(account_id: str, key, value=None) -> list[str]:
+ table_name = _table_name_from_metadata_key(key)
+ regions = sorted({
+ region
+ for (stored_account_id, region, stored_table_name), _table in _tables.all_items()
+ if stored_account_id == account_id and stored_table_name == table_name
+ })
+ value_region = _metadata_value_region(value)
+ if value_region and (not regions or value_region in regions):
+ return [value_region]
+ if len(regions) == 1:
+ return regions
+ if regions:
+ return regions
+ return [get_region()]
+
+
+def _restore_table_name_metadata(store: AccountRegionScopedDict, data) -> None:
+ if isinstance(data, AccountRegionScopedDict):
+ store.update(data)
+ return
+ if isinstance(data, AccountScopedDict):
+ for (account_id, key), value in data._data.items():
+ for region in _legacy_regions_for_table_metadata(account_id, key, value):
+ store.set_scoped(account_id, region, key, copy.deepcopy(value))
+ return
+ if isinstance(data, dict):
+ for key, value in data.items():
+ if isinstance(key, tuple) and len(key) == 3:
+ account_id, _region, original_key = key
+ regions = [_region]
+ elif isinstance(key, tuple) and len(key) == 2:
+ account_id, original_key = key
+ regions = _legacy_regions_for_table_metadata(account_id, original_key, value)
+ else:
+ account_id = get_account_id()
+ original_key = key
+ regions = _legacy_regions_for_table_metadata(account_id, original_key, value)
+ for region in regions:
+ store.set_scoped(account_id, region, original_key, copy.deepcopy(value))
+
+
def restore_state(data):
if data:
_tables.update(data.get("tables", {}))
@@ -128,10 +196,10 @@ def restore_state(data):
if sse and "Status" not in sse and ("Enabled" in sse or "KMSMasterKeyId" in sse):
tbl["SSEDescription"] = _sse_description_from_spec(sse)
_tags.update(data.get("tags", {}))
- _ttl_settings.update(data.get("ttl_settings", {}))
- _pitr_settings.update(data.get("pitr_settings", {}))
- _kinesis_destinations.update(data.get("kinesis_destinations", {}))
- _contributor_insights.update(data.get("contributor_insights", {}))
+ _restore_table_name_metadata(_ttl_settings, data.get("ttl_settings", {}))
+ _restore_table_name_metadata(_pitr_settings, data.get("pitr_settings", {}))
+ _restore_table_name_metadata(_kinesis_destinations, data.get("kinesis_destinations", {}))
+ _restore_table_name_metadata(_contributor_insights, data.get("contributor_insights", {}))
_backups.update(data.get("backups", {}))
_resource_policies.update(data.get("resource_policies", {}))
_exports.update(data.get("exports", {}))
@@ -443,7 +511,7 @@ def _validate_item(item: dict, pk_name: str | None = None, sk_name: str | None =
# DynamoDB Streams: table_name -> list of stream records
# Each record follows the DynamoDB Streams event format consumed by Lambda ESMs.
-_stream_records = AccountScopedDict()
+_stream_records = AccountRegionScopedDict()
_stream_seq_counter = 0
_stream_seq_lock = threading.Lock()
@@ -560,13 +628,13 @@ def _ttl_reaper():
now = time.time()
try:
with _lock:
- for table_name, setting in list(_ttl_settings.items()):
+ for (account_id, region, table_name), setting in list(_ttl_settings.all_items()):
if setting.get("TimeToLiveStatus") != "ENABLED":
continue
attr = setting.get("AttributeName", "")
if not attr:
continue
- table = _tables.get(table_name)
+ table = _tables.get_scoped(account_id, region, table_name)
if not table:
continue
for pk_val, sk_map in list(table["items"].items()):
@@ -2931,7 +2999,7 @@ def _transact_write_items(data):
return json_response(result)
-_txn_idempotency = AccountScopedDict()
+_txn_idempotency = AccountRegionScopedDict()
def _transact_get_items(data):
@@ -5665,3 +5733,9 @@ def reset():
_pitr_settings.clear()
_stream_records.clear()
_kinesis_destinations.clear()
+ _backups.clear()
+ _contributor_insights.clear()
+ _resource_policies.clear()
+ _exports.clear()
+ _imports.clear()
+ _txn_idempotency.clear()
diff --git a/ministack/services/dynamodb_streams.py b/ministack/services/dynamodb_streams.py
index fd9b5dde..f98f4325 100644
--- a/ministack/services/dynamodb_streams.py
+++ b/ministack/services/dynamodb_streams.py
@@ -12,7 +12,7 @@ import json
import logging
from ministack.core.arn import ArnParseError, parse_arn
-from ministack.core.responses import error_response_json, json_response
+from ministack.core.responses import error_response_json, get_account_id, get_region, json_response
from ministack.services import dynamodb as _ddb
logger = logging.getLogger("dynamodb_streams")
@@ -54,14 +54,29 @@ async def handle_request(method, path, headers, body, query_params):
# Helpers
# ---------------------------------------------------------------------------
-def _encode_iterator(table_name: str, shard_id: str, position: int) -> str:
+def _encode_iterator(
+ table_name: str,
+ shard_id: str,
+ position: int,
+ *,
+ account_id: str | None = None,
+ region: str | None = None,
+ stream_arn: str | None = None,
+) -> str:
"""Encode an opaque shard iterator.
The token is intentionally opaque: callers must treat it as bytes and pass
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 = json.dumps({"t": table_name, "s": shard_id, "p": position}, separators=(",", ":"))
+ payload_data = {"t": table_name, "s": shard_id, "p": position}
+ if account_id:
+ payload_data["a"] = account_id
+ if region:
+ payload_data["r"] = region
+ if stream_arn:
+ payload_data["arn"] = stream_arn
+ payload = json.dumps(payload_data, separators=(",", ":"))
return base64.urlsafe_b64encode(payload.encode("utf-8")).decode("ascii")
@@ -76,8 +91,8 @@ def _decode_iterator(token: str) -> dict | None:
return None
-def _table_from_stream_arn(stream_arn: str) -> str | None:
- """Extract the table name from a stream ARN of the form
+def _stream_source(stream_arn: str):
+ """Extract the parsed spec and table name from a stream ARN of the form
``arn:aws:dynamodb:{region}:{account}:table/{name}/stream/{label}``.
Invalid or out-of-shape stream ARNs map to ``None`` so describe/list paths
@@ -87,7 +102,7 @@ def _table_from_stream_arn(stream_arn: str) -> str | None:
spec = parse_arn(stream_arn)
except ArnParseError:
return None
- if spec.service != "dynamodb":
+ if spec.service != "dynamodb" or not spec.region or not spec.account_id:
return None
parts = spec.resource.split("/")
if (
@@ -98,22 +113,47 @@ def _table_from_stream_arn(stream_arn: str) -> str | None:
or not parts[3]
):
return None
- return parts[1]
+ return spec, parts[1]
+
+def _table_from_stream_arn(stream_arn: str) -> str | None:
+ source = _stream_source(stream_arn)
+ if source is None:
+ return None
+ return source[1]
-def _records_for(table_name: str) -> list:
+
+def _request_stream_source(stream_arn: str):
+ source = _stream_source(stream_arn)
+ if source is None:
+ return None
+ spec, table_name = source
+ if spec.account_id != get_account_id() or spec.region != get_region():
+ return None
+ return spec, table_name
+
+
+def _records_for(account_id: str, region: str, table_name: str) -> list:
"""Return the raw list of stream records for a table, or an empty list.
Reads directly from the dynamodb module so TransactWriteItems,
BatchWriteItem, and the single-item ops all stay in sync automatically.
"""
- return _ddb._stream_records.get(table_name, [])
+ return _ddb._stream_records.get_scoped(account_id, region, table_name, [])
-def _enabled_stream_info(table_name: str) -> dict | None:
+def _enabled_stream_info(
+ table_name: str,
+ *,
+ account_id: str | None = None,
+ region: str | None = None,
+) -> dict | None:
"""Return a dict describing a table's current stream, or ``None`` when
the table does not have an enabled stream."""
- table = _ddb._tables.get(table_name)
+ if account_id is None or region is None:
+ table = _ddb._tables.get(table_name)
+ else:
+ table = _ddb._tables.get_scoped(account_id, region, table_name)
if not table:
return None
spec = table.get("StreamSpecification")
@@ -178,19 +218,20 @@ def _describe_stream(data):
if not stream_arn:
return error_response_json("ValidationException", "StreamArn is required", 400)
- table_name = _table_from_stream_arn(stream_arn)
- if not table_name:
+ source = _request_stream_source(stream_arn)
+ if source is None:
return error_response_json(
"ResourceNotFoundException", f"Stream not found: {stream_arn}", 400
)
+ spec, table_name = source
- info = _enabled_stream_info(table_name)
+ info = _enabled_stream_info(table_name, account_id=spec.account_id, region=spec.region)
if info is None or info["StreamArn"] != stream_arn:
return error_response_json(
"ResourceNotFoundException", f"Stream not found: {stream_arn}", 400
)
- records = _records_for(table_name)
+ records = _records_for(spec.account_id, spec.region, table_name)
starting_seq = records[0]["dynamodb"]["SequenceNumber"] if records else None
shard: dict = {
@@ -200,7 +241,7 @@ def _describe_stream(data):
if starting_seq:
shard["SequenceNumberRange"]["StartingSequenceNumber"] = starting_seq
- table = _ddb._tables.get(table_name, {})
+ table = _ddb._tables.get_scoped(spec.account_id, spec.region, table_name, {})
key_schema = table.get("KeySchema", [])
# AWS shard pagination: Limit caps the number of Shards returned (max 100),
@@ -245,19 +286,20 @@ def _get_shard_iterator(data):
400,
)
- table_name = _table_from_stream_arn(stream_arn)
- if not table_name:
+ source = _request_stream_source(stream_arn)
+ if source is None:
return error_response_json(
"ResourceNotFoundException", f"Stream not found: {stream_arn}", 400
)
+ spec, table_name = source
- info = _enabled_stream_info(table_name)
+ info = _enabled_stream_info(table_name, account_id=spec.account_id, region=spec.region)
if info is None or info["StreamArn"] != stream_arn:
return error_response_json(
"ResourceNotFoundException", f"Stream not found: {stream_arn}", 400
)
- records = _records_for(table_name)
+ records = _records_for(spec.account_id, spec.region, table_name)
position = 0
if iterator_type == "TRIM_HORIZON":
position = 0
@@ -283,7 +325,14 @@ def _get_shard_iterator(data):
)
position = idx if iterator_type == "AT_SEQUENCE_NUMBER" else idx + 1
- iterator = _encode_iterator(table_name, shard_id, position)
+ iterator = _encode_iterator(
+ table_name,
+ shard_id,
+ position,
+ account_id=spec.account_id,
+ region=spec.region,
+ stream_arn=stream_arn,
+ )
return json_response({"ShardIterator": iterator})
@@ -306,18 +355,34 @@ def _get_records(data):
table_name = decoded["t"]
shard_id = decoded.get("s", _DEFAULT_SHARD_ID)
position = int(decoded.get("p", 0))
+ account_id = decoded.get("a", get_account_id())
+ region = decoded.get("r", get_region())
+ stream_arn = decoded.get("arn")
+
+ if account_id != get_account_id() or region != get_region():
+ return error_response_json(
+ "ValidationException", "ShardIterator is not valid", 400
+ )
- if _enabled_stream_info(table_name) is None:
+ info = _enabled_stream_info(table_name, account_id=account_id, region=region)
+ if info is None or (stream_arn and info["StreamArn"] != stream_arn):
return error_response_json(
"ExpiredIteratorException",
"Iterator references a stream that is no longer enabled",
400,
)
- records = _records_for(table_name)
+ records = _records_for(account_id, region, table_name)
page = records[position:position + limit]
next_position = position + len(page)
- next_iterator = _encode_iterator(table_name, shard_id, next_position)
+ next_iterator = _encode_iterator(
+ table_name,
+ shard_id,
+ next_position,
+ account_id=account_id,
+ region=region,
+ stream_arn=stream_arn,
+ )
return json_response({
"Records": page,
diff --git a/ministack/services/pipes.py b/ministack/services/pipes.py
index b882dd33..a82d2224 100644
--- a/ministack/services/pipes.py
+++ b/ministack/services/pipes.py
@@ -134,11 +134,17 @@ def _poll_once():
if _arn_service(source_arn) != "dynamodb" or _arn_service(target_arn) != "sns":
continue
- table_name = _table_name_from_stream_arn(source_arn)
- if not table_name:
+ source = _dynamodb_stream_source(source_arn)
+ if source is None:
+ continue
+ source_spec, table_name = source
+ pipe_account_id = _pipe_account_id(pipe)
+ if source_spec.account_id != pipe_account_id:
continue
- records = stream_records.get(table_name, [])
+ records = stream_records.get_scoped(
+ pipe_account_id, source_spec.region, table_name, []
+ )
pos = int(_positions.get(pipe["Arn"], 0))
if pos < 0:
pos = 0
@@ -184,12 +190,18 @@ def _arn_service(arn: str) -> str:
def _table_name_from_stream_arn(stream_arn: str) -> str:
"""Return a DynamoDB table name for Pipes runtime dispatch, or empty string."""
+ source = _dynamodb_stream_source(stream_arn)
+ return "" if source is None else source[1]
+
+
+def _dynamodb_stream_source(stream_arn: str):
+ """Return the parsed source ARN and table name for a DynamoDB stream."""
try:
spec = parse_arn(stream_arn)
except ArnParseError:
- return ""
+ return None
if spec.service != "dynamodb":
- return ""
+ return None
parts = spec.resource.split("/")
if (
len(parts) < 4
@@ -198,18 +210,37 @@ def _table_name_from_stream_arn(stream_arn: str) -> str:
or not parts[1]
or not parts[3]
):
- return ""
- return parts[1]
+ return None
+ return spec, parts[1]
+
+
+def _pipe_account_id(pipe: dict) -> str:
+ try:
+ spec = parse_arn(pipe.get("Arn", ""))
+ except ArnParseError:
+ return get_account_id()
+ if spec.service != "pipes" or not spec.account_id:
+ return get_account_id()
+ return spec.account_id
def _initial_position(pipe: dict) -> int:
from ministack.services import dynamodb as _ddb
- table_name = _table_name_from_stream_arn(pipe.get("Source", ""))
- if not table_name:
+ source = _dynamodb_stream_source(pipe.get("Source", ""))
+ if source is None:
+ return 0
+ source_spec, table_name = source
+ pipe_account_id = _pipe_account_id(pipe)
+ if source_spec.account_id != pipe_account_id:
return 0
- records = getattr(_ddb, "_stream_records", {}).get(table_name, [])
+ stream_records = getattr(_ddb, "_stream_records", None)
+ if stream_records is None:
+ return 0
+ records = stream_records.get_scoped(
+ pipe_account_id, source_spec.region, table_name, []
+ )
if pipe.get("StartingPosition") == "TRIM_HORIZON":
return 0
return len(records)
diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.py
index 603c1a55..44d61679 100644
--- a/tests/test_dynamodb.py
+++ b/tests/test_dynamodb.py
@@ -26,6 +26,36 @@ def _ddb_client(region_name: str):
)
+def _ddb_streams_client(region_name: str):
+ return boto3.client(
+ "dynamodbstreams",
+ endpoint_url=_ENDPOINT,
+ aws_access_key_id="test",
+ aws_secret_access_key="test",
+ region_name=region_name,
+ config=Config(region_name=region_name, retries={"mode": "standard"}),
+ )
+
+
+def _create_table(client, name: str, *, stream_enabled: bool = False):
+ try:
+ client.delete_table(TableName=name)
+ except Exception:
+ pass
+ kwargs = {
+ "TableName": name,
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
+ "BillingMode": "PAY_PER_REQUEST",
+ }
+ if stream_enabled:
+ kwargs["StreamSpecification"] = {
+ "StreamEnabled": True,
+ "StreamViewType": "NEW_AND_OLD_IMAGES",
+ }
+ return client.create_table(**kwargs)
+
+
def _make_zip(code: str) -> bytes:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
@@ -80,6 +110,284 @@ def test_dynamodb_tables_are_region_isolated_by_name(ddb):
except ClientError:
pass
+
+def test_dynamodb_same_name_table_metadata_is_region_scoped(ddb):
+ east = _ddb_client("us-east-1")
+ west = _ddb_client("us-west-2")
+ name = f"region-meta-{_uuid_mod.uuid4().hex[:8]}"
+
+ east_arn = _create_table(east, name)["TableDescription"]["TableArn"]
+ west_arn = _create_table(west, name)["TableDescription"]["TableArn"]
+ try:
+ east.tag_resource(ResourceArn=east_arn, Tags=[{"Key": "region", "Value": "east"}])
+ west.tag_resource(ResourceArn=west_arn, Tags=[{"Key": "region", "Value": "west"}])
+ assert east.list_tags_of_resource(ResourceArn=east_arn)["Tags"] == [
+ {"Key": "region", "Value": "east"}
+ ]
+ assert west.list_tags_of_resource(ResourceArn=west_arn)["Tags"] == [
+ {"Key": "region", "Value": "west"}
+ ]
+
+ east.update_time_to_live(
+ TableName=name,
+ TimeToLiveSpecification={"Enabled": True, "AttributeName": "east_expires_at"},
+ )
+ west_ttl = west.describe_time_to_live(TableName=name)["TimeToLiveDescription"]
+ assert west_ttl["TimeToLiveStatus"] == "DISABLED"
+
+ west.update_time_to_live(
+ TableName=name,
+ TimeToLiveSpecification={"Enabled": True, "AttributeName": "west_expires_at"},
+ )
+ assert east.describe_time_to_live(TableName=name)["TimeToLiveDescription"]["AttributeName"] == "east_expires_at"
+ assert west.describe_time_to_live(TableName=name)["TimeToLiveDescription"]["AttributeName"] == "west_expires_at"
+
+ east.update_continuous_backups(
+ TableName=name,
+ PointInTimeRecoverySpecification={"PointInTimeRecoveryEnabled": True},
+ )
+ east_pitr = east.describe_continuous_backups(TableName=name)[
+ "ContinuousBackupsDescription"
+ ]["PointInTimeRecoveryDescription"]
+ west_pitr = west.describe_continuous_backups(TableName=name)[
+ "ContinuousBackupsDescription"
+ ]["PointInTimeRecoveryDescription"]
+ assert east_pitr["PointInTimeRecoveryStatus"] == "ENABLED"
+ assert west_pitr["PointInTimeRecoveryStatus"] == "DISABLED"
+
+ east.update_contributor_insights(TableName=name, ContributorInsightsAction="ENABLE")
+ assert east.describe_contributor_insights(TableName=name)["ContributorInsightsStatus"] == "ENABLED"
+ assert west.describe_contributor_insights(TableName=name)["ContributorInsightsStatus"] == "DISABLED"
+
+ stream_arn = f"arn:aws:kinesis:us-east-1:000000000000:stream/{name}"
+ east.enable_kinesis_streaming_destination(TableName=name, StreamArn=stream_arn)
+ assert west.describe_kinesis_streaming_destination(TableName=name)[
+ "KinesisDataStreamDestinations"
+ ] == []
+ finally:
+ for client in (east, west):
+ try:
+ client.delete_table(TableName=name)
+ except ClientError:
+ pass
+
+
+def test_dynamodb_stream_records_are_region_scoped_for_same_name_tables(ddb):
+ east = _ddb_client("us-east-1")
+ west = _ddb_client("us-west-2")
+ east_streams = _ddb_streams_client("us-east-1")
+ west_streams = _ddb_streams_client("us-west-2")
+ name = f"region-stream-{_uuid_mod.uuid4().hex[:8]}"
+
+ east_arn = _create_table(east, name, stream_enabled=True)["TableDescription"]["LatestStreamArn"]
+ west_arn = _create_table(west, name, stream_enabled=True)["TableDescription"]["LatestStreamArn"]
+ try:
+ east.put_item(TableName=name, Item={"pk": {"S": "east-only"}})
+
+ east_shard = east_streams.describe_stream(StreamArn=east_arn)["StreamDescription"]["Shards"][0]["ShardId"]
+ west_shard = west_streams.describe_stream(StreamArn=west_arn)["StreamDescription"]["Shards"][0]["ShardId"]
+ east_iter = east_streams.get_shard_iterator(
+ StreamArn=east_arn,
+ ShardId=east_shard,
+ ShardIteratorType="TRIM_HORIZON",
+ )["ShardIterator"]
+ west_iter = west_streams.get_shard_iterator(
+ StreamArn=west_arn,
+ ShardId=west_shard,
+ ShardIteratorType="TRIM_HORIZON",
+ )["ShardIterator"]
+
+ assert len(east_streams.get_records(ShardIterator=east_iter)["Records"]) == 1
+ assert west_streams.get_records(ShardIterator=west_iter)["Records"] == []
+
+ with pytest.raises(ClientError) as exc:
+ west_streams.get_records(ShardIterator=east_iter)
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+ finally:
+ for client in (east, west):
+ try:
+ client.delete_table(TableName=name)
+ except ClientError:
+ pass
+
+
+def test_dynamodb_regional_listing_metadata_does_not_cross_regions(ddb):
+ east = _ddb_client("us-east-1")
+ west = _ddb_client("us-west-2")
+ name = f"region-list-{_uuid_mod.uuid4().hex[:8]}"
+ import_name = f"region-import-{_uuid_mod.uuid4().hex[:8]}"
+
+ east_arn = _create_table(east, name)["TableDescription"]["TableArn"]
+ _create_table(west, name)
+ backup_arn = None
+ try:
+ backup_arn = east.create_backup(TableName=name, BackupName="snapshot")["BackupDetails"]["BackupArn"]
+ west_backups = west.list_backups(TableName=name).get("BackupSummaries", [])
+ assert backup_arn not in {summary["BackupArn"] for summary in west_backups}
+
+ export_arn = east.export_table_to_point_in_time(
+ TableArn=east_arn,
+ S3Bucket="region-state-export",
+ )["ExportDescription"]["ExportArn"]
+ west_exports = west.list_exports().get("ExportSummaries", [])
+ assert export_arn not in {summary["ExportArn"] for summary in west_exports}
+
+ import_arn = east.import_table(
+ S3BucketSource={"S3Bucket": "region-state-import"},
+ InputFormat="DYNAMODB_JSON",
+ TableCreationParameters={
+ "TableName": import_name,
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
+ "BillingMode": "PAY_PER_REQUEST",
+ },
+ )["ImportTableDescription"]["ImportArn"]
+ west_imports = west.list_imports().get("ImportSummaryList", [])
+ assert import_arn not in {summary["ImportArn"] for summary in west_imports}
+ finally:
+ if backup_arn:
+ try:
+ east.delete_backup(BackupArn=backup_arn)
+ except ClientError:
+ pass
+ for client, table_name in ((east, name), (west, name), (east, import_name)):
+ try:
+ client.delete_table(TableName=table_name)
+ except ClientError:
+ pass
+
+
+def test_dynamodb_restore_legacy_table_name_metadata_uses_table_arn_region():
+ from ministack.core.responses import AccountScopedDict, set_request_account_id, set_request_region
+ from ministack.services import dynamodb as ddb_service
+
+ account_id = "000000000000"
+ table_name = f"legacy-meta-{_uuid_mod.uuid4().hex[:8]}"
+ table_arn = f"arn:aws:dynamodb:us-west-2:{account_id}:table/{table_name}"
+
+ set_request_account_id(account_id)
+ set_request_region("us-east-1")
+ ddb_service.reset()
+ tables = AccountScopedDict()
+ tables[table_name] = {
+ "TableName": table_name,
+ "TableArn": table_arn,
+ "items": {},
+ }
+ ttl_settings = AccountScopedDict()
+ ttl_settings[table_name] = {
+ "TimeToLiveStatus": "ENABLED",
+ "AttributeName": "expires_at",
+ }
+ pitr_settings = AccountScopedDict()
+ pitr_settings[table_name] = True
+ kinesis_destinations = AccountScopedDict()
+ kinesis_destinations[table_name] = [
+ {"StreamArn": f"arn:aws:kinesis:us-west-2:{account_id}:stream/{table_name}"}
+ ]
+ contributor_insights = AccountScopedDict()
+ contributor_insights[f"{table_name}/index/GSI"] = {
+ "ContributorInsightsStatus": "ENABLED",
+ }
+
+ try:
+ ddb_service.restore_state({
+ "tables": tables,
+ "ttl_settings": ttl_settings,
+ "pitr_settings": pitr_settings,
+ "kinesis_destinations": kinesis_destinations,
+ "contributor_insights": contributor_insights,
+ })
+
+ assert ddb_service._ttl_settings.get_scoped(account_id, "us-west-2", table_name)[
+ "AttributeName"
+ ] == "expires_at"
+ assert ddb_service._ttl_settings.get_scoped(account_id, "us-east-1", table_name) is None
+ assert ddb_service._pitr_settings.get_scoped(account_id, "us-west-2", table_name) is True
+ assert ddb_service._kinesis_destinations.get_scoped(account_id, "us-west-2", table_name)
+ assert ddb_service._contributor_insights.get_scoped(
+ account_id,
+ "us-west-2",
+ f"{table_name}/index/GSI",
+ )
+ finally:
+ ddb_service.reset()
+
+
+def test_dynamodb_restore_ambiguous_legacy_metadata_uses_value_arn_region():
+ from ministack.core.responses import (
+ AccountRegionScopedDict,
+ AccountScopedDict,
+ set_request_account_id,
+ set_request_region,
+ )
+ from ministack.services import dynamodb as ddb_service
+
+ account_id = "000000000000"
+ table_name = f"legacy-ambiguous-{_uuid_mod.uuid4().hex[:8]}"
+
+ set_request_account_id(account_id)
+ set_request_region("us-east-1")
+ ddb_service.reset()
+ tables = AccountRegionScopedDict()
+ tables.set_scoped(
+ account_id,
+ "us-east-1",
+ table_name,
+ {
+ "TableName": table_name,
+ "TableArn": f"arn:aws:dynamodb:us-east-1:{account_id}:table/{table_name}",
+ "items": {},
+ },
+ )
+ tables.set_scoped(
+ account_id,
+ "us-west-2",
+ table_name,
+ {
+ "TableName": table_name,
+ "TableArn": f"arn:aws:dynamodb:us-west-2:{account_id}:table/{table_name}",
+ "items": {},
+ },
+ )
+ ttl_settings = AccountScopedDict()
+ ttl_settings[table_name] = {
+ "TimeToLiveStatus": "ENABLED",
+ "AttributeName": "expires_at",
+ }
+ kinesis_destinations = AccountScopedDict()
+ kinesis_destinations[table_name] = [
+ {"StreamArn": f"arn:aws:kinesis:us-west-2:{account_id}:stream/{table_name}"}
+ ]
+
+ try:
+ ddb_service.restore_state({
+ "tables": tables,
+ "ttl_settings": ttl_settings,
+ "kinesis_destinations": kinesis_destinations,
+ })
+
+ assert ddb_service._kinesis_destinations.get_scoped(
+ account_id, "us-east-1", table_name
+ ) is None
+ assert ddb_service._kinesis_destinations.get_scoped(
+ account_id, "us-west-2", table_name
+ ) == [{"StreamArn": f"arn:aws:kinesis:us-west-2:{account_id}:stream/{table_name}"}]
+ assert ddb_service._ttl_settings.get_scoped(account_id, "us-east-1", table_name)[
+ "AttributeName"
+ ] == "expires_at"
+ assert ddb_service._ttl_settings.get_scoped(account_id, "us-west-2", table_name)[
+ "AttributeName"
+ ] == "expires_at"
+
+ east_ttl = ddb_service._ttl_settings.get_scoped(account_id, "us-east-1", table_name)
+ west_ttl = ddb_service._ttl_settings.get_scoped(account_id, "us-west-2", table_name)
+ east_ttl["AttributeName"] = "changed"
+ assert west_ttl["AttributeName"] == "expires_at"
+ finally:
+ ddb_service.reset()
+
+
def test_dynamodb_scan(ddb):
try:
ddb.delete_table(TableName="ScanTable")
diff --git a/tests/test_pipes.py b/tests/test_pipes.py
index 3a8c3308..f60e0e66 100644
--- a/tests/test_pipes.py
+++ b/tests/test_pipes.py
@@ -1,3 +1,5 @@
+from ministack.core.responses import _request_region
+from ministack.services import dynamodb as _ddb
from ministack.services import pipes as _pipes
@@ -16,3 +18,98 @@ def test_pipes_stream_table_name_parser_requires_dynamodb_stream_arn():
missing_stream_arn = "arn:aws:dynamodb:us-east-1:000000000000:table/PipeTable"
assert _pipes._table_name_from_stream_arn(wrong_service_arn) == ""
assert _pipes._table_name_from_stream_arn(missing_stream_arn) == ""
+
+
+def test_pipes_dynamodb_stream_reads_use_source_arn_region(monkeypatch):
+ _pipes.reset()
+ _ddb._stream_records.clear()
+ region_token = _request_region.set("us-east-1")
+ try:
+ table_name = "PipeTable"
+ source_region = "us-west-2"
+ source_arn = (
+ f"arn:aws:dynamodb:{source_region}:000000000000:"
+ f"table/{table_name}/stream/2026-05-22T00:00:00.000"
+ )
+ target_arn = "arn:aws:sns:us-east-1:000000000000:PipeTopic"
+ pipe_arn = "arn:aws:pipes:us-east-1:000000000000:pipe/PipeName"
+ record = {"eventID": "evt-1", "eventSource": "aws:dynamodb"}
+
+ _ddb._stream_records.set_scoped(
+ "000000000000", source_region, table_name, [record]
+ )
+ _pipes._pipes["PipeName"] = {
+ "Name": "PipeName",
+ "Arn": pipe_arn,
+ "Source": source_arn,
+ "Target": target_arn,
+ "CurrentState": "RUNNING",
+ "StartingPosition": "TRIM_HORIZON",
+ }
+ _pipes._positions[pipe_arn] = 0
+
+ assert _pipes._initial_position({
+ "Source": source_arn,
+ "StartingPosition": "LATEST",
+ }) == 1
+ assert _pipes._initial_position({
+ "Source": source_arn,
+ "StartingPosition": "TRIM_HORIZON",
+ }) == 0
+
+ delivered = []
+
+ def _record_publish(topic_arn, pipe, published_record):
+ delivered.append((topic_arn, pipe["Arn"], published_record))
+
+ monkeypatch.setattr(_pipes, "_publish_record_to_sns", _record_publish)
+
+ _pipes._poll_once()
+
+ assert delivered == [(target_arn, pipe_arn, record)]
+ assert _pipes._positions[pipe_arn] == 1
+ finally:
+ _request_region.reset(region_token)
+ _pipes.reset()
+ _ddb._stream_records.clear()
+
+
+def test_pipes_dynamodb_stream_read_rejects_cross_account_source(monkeypatch):
+ _pipes.reset()
+ _ddb._stream_records.clear()
+ try:
+ table_name = "PipeTable"
+ source_arn = (
+ "arn:aws:dynamodb:us-west-2:111111111111:"
+ f"table/{table_name}/stream/2026-05-22T00:00:00.000"
+ )
+ target_arn = "arn:aws:sns:us-east-1:000000000000:PipeTopic"
+ pipe_arn = "arn:aws:pipes:us-east-1:000000000000:pipe/PipeName"
+ record = {"eventID": "evt-1", "eventSource": "aws:dynamodb"}
+
+ _ddb._stream_records.set_scoped("111111111111", "us-west-2", table_name, [record])
+ _pipes._pipes["PipeName"] = {
+ "Name": "PipeName",
+ "Arn": pipe_arn,
+ "Source": source_arn,
+ "Target": target_arn,
+ "CurrentState": "RUNNING",
+ "StartingPosition": "TRIM_HORIZON",
+ }
+ _pipes._positions[pipe_arn] = 0
+
+ delivered = []
+ monkeypatch.setattr(
+ _pipes,
+ "_publish_record_to_sns",
+ lambda topic_arn, pipe, published_record: delivered.append(published_record),
+ )
+
+ assert _pipes._initial_position(_pipes._pipes["PipeName"]) == 0
+ _pipes._poll_once()
+
+ assert delivered == []
+ assert _pipes._positions[pipe_arn] == 0
+ finally:
+ _pipes.reset()
+ _ddb._stream_records.clear()