Skip to content

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

Regionalize Kinesis state stores (#1069)

Ian Oberstb3e77b0e26bf
diff --git a/ministack/services/kinesis.py b/ministack/services/kinesis.py
index 76dd64e2..cd40edab 100644
--- a/ministack/services/kinesis.py
+++ b/ministack/services/kinesis.py
@@ -23,6 +23,7 @@ import time
from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.responses import (
+ AccountRegionScopedDict,
AccountScopedDict,
error_response_json,
get_account_id,
@@ -39,9 +40,9 @@ ITERATOR_EXPIRY_SECONDS = 300
from ministack.core.persistence import PERSIST_STATE, load_state
-_streams = AccountScopedDict()
-_shard_iterators = AccountScopedDict()
-_consumers = AccountScopedDict()
+_streams = AccountRegionScopedDict()
+_shard_iterators = AccountRegionScopedDict()
+_consumers = AccountRegionScopedDict()
_sequence_counter = 0
_sequence_lock = threading.Lock()
@@ -51,14 +52,117 @@ _sequence_lock = threading.Lock()
def get_state():
return {
"streams": copy.deepcopy(_streams),
+ "shard_iterators": copy.deepcopy(_shard_iterators),
"consumers": copy.deepcopy(_consumers),
}
def restore_state(data):
if data:
- _streams.update(data.get("streams", {}))
- _consumers.update(data.get("consumers", {}))
+ _restore_stream_store(data.get("streams", {}))
+ _restore_shard_iterator_store(data.get("shard_iterators", {}))
+ _restore_consumer_store(data.get("consumers", {}))
+
+
+def _kinesis_arn_scope(value, default_account_id: str | None = None) -> tuple[str, str]:
+ try:
+ spec = parse_arn(value)
+ except ArnParseError:
+ return default_account_id or get_account_id(), get_region()
+ if spec.service != "kinesis":
+ return default_account_id or get_account_id(), get_region()
+ return spec.account_id or default_account_id or get_account_id(), spec.region or get_region()
+
+
+def _stream_record_scope(stream: dict, default_account_id: str | None = None) -> tuple[str, str]:
+ return _kinesis_arn_scope(stream.get("StreamARN", ""), default_account_id)
+
+
+def _consumer_record_scope(consumer: dict, default_account_id: str | None = None) -> tuple[str, str]:
+ return _kinesis_arn_scope(
+ consumer.get("ConsumerARN") or consumer.get("StreamARN", ""),
+ default_account_id,
+ )
+
+
+def _shard_iterator_record_scope(state: dict, default_account_id: str | None = None) -> tuple[str, str]:
+ stream_arn = state.get("stream_arn")
+ if stream_arn:
+ return _kinesis_arn_scope(stream_arn, default_account_id)
+
+ stream_name = state.get("stream")
+ if stream_name:
+ expected_account_id = default_account_id or get_account_id()
+ for (account_id, region, name), _stream in _streams.all_items():
+ if account_id == expected_account_id and name == stream_name:
+ return account_id, region
+ return default_account_id or get_account_id(), get_region()
+
+
+def _restore_stream_store(data) -> None:
+ if isinstance(data, AccountRegionScopedDict):
+ _streams.update(data)
+ return
+ if isinstance(data, AccountScopedDict):
+ for (account_id, name), stream in data._data.items():
+ restored_account_id, region = _stream_record_scope(stream, account_id)
+ _streams.set_scoped(restored_account_id, region, name, copy.deepcopy(stream))
+ return
+ if isinstance(data, dict):
+ for key, stream in data.items():
+ if isinstance(key, tuple) and len(key) == 3:
+ account_id, region, name = key
+ elif isinstance(key, tuple) and len(key) == 2:
+ account_id, name = key
+ account_id, region = _stream_record_scope(stream, account_id)
+ else:
+ name = key
+ account_id, region = _stream_record_scope(stream)
+ _streams.set_scoped(account_id, region, name, copy.deepcopy(stream))
+
+
+def _restore_shard_iterator_store(data) -> None:
+ if isinstance(data, AccountRegionScopedDict):
+ _shard_iterators.update(data)
+ return
+ if isinstance(data, AccountScopedDict):
+ for (account_id, token), state in data._data.items():
+ restored_account_id, region = _shard_iterator_record_scope(state, account_id)
+ _shard_iterators.set_scoped(restored_account_id, region, token, copy.deepcopy(state))
+ return
+ if isinstance(data, dict):
+ for key, state in data.items():
+ if isinstance(key, tuple) and len(key) == 3:
+ account_id, region, token = key
+ elif isinstance(key, tuple) and len(key) == 2:
+ account_id, token = key
+ account_id, region = _shard_iterator_record_scope(state, account_id)
+ else:
+ token = key
+ account_id, region = _shard_iterator_record_scope(state)
+ _shard_iterators.set_scoped(account_id, region, token, copy.deepcopy(state))
+
+
+def _restore_consumer_store(data) -> None:
+ if isinstance(data, AccountRegionScopedDict):
+ _consumers.update(data)
+ return
+ if isinstance(data, AccountScopedDict):
+ for (account_id, consumer_arn), consumer in data._data.items():
+ restored_account_id, region = _consumer_record_scope(consumer, account_id)
+ _consumers.set_scoped(restored_account_id, region, consumer_arn, copy.deepcopy(consumer))
+ return
+ if isinstance(data, dict):
+ for key, consumer in data.items():
+ if isinstance(key, tuple) and len(key) == 3:
+ account_id, region, consumer_arn = key
+ elif isinstance(key, tuple) and len(key) == 2:
+ account_id, consumer_arn = key
+ account_id, region = _consumer_record_scope(consumer, account_id)
+ else:
+ consumer_arn = key
+ account_id, region = _consumer_record_scope(consumer)
+ _consumers.set_scoped(account_id, region, consumer_arn, copy.deepcopy(consumer))
try:
@@ -659,6 +763,7 @@ def _get_shard_iterator(data):
token = new_uuid()
_shard_iterators[token] = {
"stream": resolved_name,
+ "stream_arn": stream["StreamARN"],
"shard_id": shard_id,
"position": position,
"created_at": time.time(),
@@ -722,6 +827,7 @@ def _get_records(data):
next_token = new_uuid()
_shard_iterators[next_token] = {
"stream": state["stream"],
+ "stream_arn": state.get("stream_arn") or stream.get("StreamARN"),
"shard_id": state["shard_id"],
"position": new_pos,
"created_at": time.time(),
diff --git a/tests/test_kinesis.py b/tests/test_kinesis.py
index d88890f7..77d6230a 100644
--- a/tests/test_kinesis.py
+++ b/tests/test_kinesis.py
@@ -14,12 +14,12 @@ from botocore.exceptions import ClientError
_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"
-def _regional_kin(region_name):
+def _regional_kin(region_name, account_id="test"):
endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
return boto3.client(
"kinesis",
endpoint_url=endpoint,
- aws_access_key_id="test",
+ aws_access_key_id=account_id,
aws_secret_access_key="test",
region_name=region_name,
config=Config(region_name=region_name, retries={"mode": "standard"}),
@@ -130,6 +130,45 @@ def test_kinesis_stream_arn_rejects_foreign_region_without_name_fallback(kin):
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+def test_kinesis_same_name_streams_are_region_scoped(kin):
+ west = _regional_kin("us-west-2")
+ stream_name = f"kin-region-scope-{_uuid_mod.uuid4().hex[:8]}"
+
+ kin.create_stream(StreamName=stream_name, ShardCount=1)
+ west.create_stream(StreamName=stream_name, ShardCount=1)
+
+ east_desc = kin.describe_stream(StreamName=stream_name)["StreamDescription"]
+ west_desc = west.describe_stream(StreamName=stream_name)["StreamDescription"]
+
+ assert east_desc["StreamARN"] == f"arn:aws:kinesis:us-east-1:000000000000:stream/{stream_name}"
+ assert west_desc["StreamARN"] == f"arn:aws:kinesis:us-west-2:000000000000:stream/{stream_name}"
+ assert stream_name in kin.list_streams()["StreamNames"]
+ assert stream_name in west.list_streams()["StreamNames"]
+
+
+def test_kinesis_stream_names_do_not_fallback_across_region_or_account(kin):
+ owner_account = "111111111111"
+ west_owner = _regional_kin("us-west-2", account_id=owner_account)
+ east_owner = _regional_kin("us-east-1", account_id=owner_account)
+ west_default = _regional_kin("us-west-2")
+ stream_name = f"kin-no-fallback-{_uuid_mod.uuid4().hex[:8]}"
+
+ west_owner.create_stream(StreamName=stream_name, ShardCount=1)
+ west_arn = west_owner.describe_stream(StreamName=stream_name)["StreamDescription"]["StreamARN"]
+
+ with pytest.raises(ClientError) as exc:
+ east_owner.describe_stream(StreamName=stream_name)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+ with pytest.raises(ClientError) as exc:
+ west_default.describe_stream(StreamName=stream_name)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+ with pytest.raises(ClientError) as exc:
+ kin.describe_stream(StreamARN=west_arn)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
def test_kinesis_tags_v2(kin):
kin.create_stream(StreamName="kin-tag-v2", ShardCount=1)
kin.add_tags_to_stream(StreamName="kin-tag-v2", Tags={"env": "test", "team": "data"})
@@ -280,6 +319,86 @@ def test_kinesis_consumer_arns_reject_foreign_region_without_exact_key_fallback(
assert west.describe_stream_consumer(ConsumerARN=consumer_arn)["ConsumerDescription"]["ConsumerName"] == consumer_name
+def test_kinesis_restore_legacy_account_scoped_state_uses_arn_region():
+ from ministack.core.responses import (
+ AccountScopedDict,
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+ )
+ from ministack.services import kinesis as _kin
+
+ original_account = get_account_id()
+ original_region = get_region()
+ account_id = "000000000000"
+ stream_name = "LegacyKinesisStream"
+ stream_arn = f"arn:aws:kinesis:us-west-2:{account_id}:stream/{stream_name}"
+ consumer_arn = f"{stream_arn}/consumer/legacy-consumer:1700000000"
+
+ legacy_streams = AccountScopedDict()
+ legacy_streams._data[(account_id, stream_name)] = {
+ "StreamName": stream_name,
+ "StreamARN": stream_arn,
+ "StreamStatus": "ACTIVE",
+ "StreamModeDetails": {"StreamMode": "PROVISIONED"},
+ "RetentionPeriodHours": 24,
+ "shards": {},
+ "tags": {},
+ "CreationTimestamp": 1700000000,
+ "EncryptionType": "NONE",
+ }
+ legacy_iterators = AccountScopedDict()
+ legacy_iterators._data[(account_id, "legacy-iterator-with-arn")] = {
+ "stream": stream_name,
+ "stream_arn": stream_arn,
+ "shard_id": "shardId-000000000000",
+ "position": 0,
+ "created_at": 1700000000,
+ }
+ legacy_iterators._data[(account_id, "legacy-iterator-with-stream-name")] = {
+ "stream": stream_name,
+ "shard_id": "shardId-000000000000",
+ "position": 0,
+ "created_at": 1700000000,
+ }
+ legacy_consumers = AccountScopedDict()
+ legacy_consumers._data[(account_id, consumer_arn)] = {
+ "ConsumerARN": consumer_arn,
+ "ConsumerName": "legacy-consumer",
+ "ConsumerStatus": "ACTIVE",
+ "ConsumerCreationTimestamp": 1700000000,
+ "StreamARN": stream_arn,
+ }
+
+ _kin.reset()
+ try:
+ set_request_account_id(account_id)
+ set_request_region("us-east-1")
+
+ _kin.restore_state({
+ "streams": legacy_streams,
+ "shard_iterators": legacy_iterators,
+ "consumers": legacy_consumers,
+ })
+
+ assert _kin._streams.get_scoped(account_id, "us-east-1", stream_name) is None
+ assert _kin._streams.get_scoped(account_id, "us-west-2", stream_name)["StreamARN"] == stream_arn
+ assert _kin._shard_iterators.get_scoped(
+ account_id, "us-west-2", "legacy-iterator-with-arn"
+ )["stream_arn"] == stream_arn
+ stream_name_iterator = _kin._shard_iterators.get_scoped(
+ account_id, "us-west-2", "legacy-iterator-with-stream-name"
+ )
+ assert stream_name_iterator["stream"] == stream_name
+ assert "stream_arn" not in stream_name_iterator
+ assert _kin._consumers.get_scoped(account_id, "us-west-2", consumer_arn)["ConsumerARN"] == consumer_arn
+ finally:
+ _kin.reset()
+ set_request_account_id(original_account)
+ set_request_region(original_region)
+
+
def test_kinesis_at_timestamp_iterator(kin):
"""AT_TIMESTAMP shard iterator returns records after the given timestamp."""
kin.create_stream(StreamName="qa-kin-ts", ShardCount=1)
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index a0480f0d..ebaa37bc 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -728,11 +728,11 @@ def test_kinesis_consumers_survive_warm_boot():
mod.reset()
-# ── kms._keys / kms._aliases ───────────────────────────────────────────
-
-def test_kms_region_scoped_stores_survive_warm_boot_in_original_scope():
- import base64
+def test_kinesis_shard_iterators_survive_warm_boot_in_original_scope():
+ """Live shard iterators must round-trip through JSON persistence without
+ becoming visible to other accounts or regions."""
import json
+ import time
from ministack.core.responses import (
get_account_id,
@@ -741,51 +741,72 @@ def test_kms_region_scoped_stores_survive_warm_boot_in_original_scope():
set_request_region,
)
- mod = _get_module("kms")
+ mod = _get_module("kinesis")
original_account = get_account_id()
original_region = get_region()
account_id = "111111111111"
- alias_name = "alias/warm-kms-region"
-
- def _body(response):
- return json.loads(response[2])
+ region = "us-west-2"
+ stream_name = "warm-boot-stream"
+ stream_arn = f"arn:aws:kinesis:{region}:{account_id}:stream/{stream_name}"
+ shard_id = "shardId-000000000000"
+ token = "live-iterator-token"
+ now = time.time()
mod.reset()
try:
set_request_account_id(account_id)
- set_request_region("us-west-2")
+ set_request_region(region)
+ mod._streams[stream_name] = {
+ "StreamName": stream_name,
+ "StreamARN": stream_arn,
+ "StreamStatus": "ACTIVE",
+ "StreamModeDetails": {"StreamMode": "PROVISIONED"},
+ "RetentionPeriodHours": 24,
+ "shards": {
+ shard_id: {
+ "records": [{
+ "SequenceNumber": "1",
+ "ApproximateArrivalTimestamp": now,
+ "Data": b"warm-boot-record",
+ "PartitionKey": "pk1",
+ }],
+ "starting_hash_key": "0",
+ "ending_hash_key": str(2**128 - 1),
+ "starting_sequence_number": "1",
+ "parent_shard_id": None,
+ "adjacent_parent_shard_id": None,
+ },
+ },
+ "tags": {},
+ "CreationTimestamp": now,
+ "EncryptionType": "NONE",
+ }
+ mod._shard_iterators[token] = {
+ "stream": stream_name,
+ "stream_arn": stream_arn,
+ "shard_id": shard_id,
+ "position": 0,
+ "created_at": now,
+ }
- created = _body(mod._create_key({
- "KeySpec": "SYMMETRIC_DEFAULT",
- "KeyUsage": "ENCRYPT_DECRYPT",
- "Description": "warm boot KMS key",
- }))
- key_id = created["KeyMetadata"]["KeyId"]
- key_arn = created["KeyMetadata"]["Arn"]
- mod._create_alias({"AliasName": alias_name, "TargetKeyId": key_id})
- encrypted = _body(mod._encrypt({
- "KeyId": key_id,
- "Plaintext": b"warm-kms-region",
- }))
-
- _round_trip_dict(mod, "kms")
-
- assert mod._resolve_key(key_id)["Arn"] == key_arn
- assert mod._resolve_key(alias_name)["KeyId"] == key_id
- decrypted = _body(mod._decrypt({
- "CiphertextBlob": encrypted["CiphertextBlob"],
- "KeyId": key_id,
- }))
- assert base64.b64decode(decrypted["Plaintext"]) == b"warm-kms-region"
+ _round_trip_dict(mod, "kinesis")
+
+ assert token in mod._shard_iterators
+ status, _, body = mod._get_records({"ShardIterator": token, "Limit": 1})
+ assert status == 200
+ payload = json.loads(body)
+ assert payload["Records"][0]["PartitionKey"] == "pk1"
+ assert payload["NextShardIterator"] in mod._shard_iterators
set_request_region("us-east-1")
- assert mod._resolve_key(key_id) is None
- assert mod._resolve_key(alias_name) is None
+ assert token not in mod._shard_iterators
+ status, _, body = mod._get_records({"ShardIterator": token})
+ assert status == 400
+ assert json.loads(body)["__type"] == "ExpiredIteratorException"
set_request_account_id("222222222222")
- set_request_region("us-west-2")
- assert mod._resolve_key(key_id) is None
- assert mod._resolve_key(alias_name) is None
+ set_request_region(region)
+ assert token not in mod._shard_iterators
finally:
mod.reset()
set_request_account_id(original_account)