Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
Prerelease/v1.5.33 (#2437)
Nahuel Nuceraffe664a07b80
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 78a5655d..528a2d0a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,7 +20,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **Lambda — two MiniStacks on one host no longer remove each other's function code** — the provided-runtime and Docker-executor extraction caches lived at fixed paths in the shared temp directory, so a second instance on the same host deleted a tree the first was still running from ("leftover from a previous process") and its `reset()` removed the first one's caches; an invocation then failed with `No such file or directory: .../bootstrap`. Both caches are now named for the instance's `GATEWAY_PORT`. Contributed by @skialpine.### Added- **CloudFormation — `AWS::Athena::WorkGroup`** — a template with a workgroup failed with "Unrecognized resource types"; the workgroup is now created with its `Description`, `State`, `Tags` and `WorkGroupConfiguration`, updated in place when they change, replaced when `Name` changes, and deleted with the stack. `Ref` returns the name and `Fn::GetAtt` `CreationTime` and the effective engine version, as the template reference describes. Reported by @mishukdutta-cz.-- **Kinesis — stream and consumer resource policies** — `PutResourcePolicy`, `GetResourcePolicy` and `DeleteResourcePolicy` answered `InvalidAction`; they now store a policy per stream or consumer, persisted and dropped with it, with AWS's checks in AWS's order: the ARN's region (`InvalidArgumentException` "The region specified in the ARN '<arn>' does not match the endpoint region"), the policy ("Policy validation error: This policy contains invalid Json", "Missing required field Version" or "Statement", and per statement the actions a stream or consumer can share and a `Resource` equal to the ARN, with the statement's line and column), then the resource ("Stream <name> under account <id> not found."). `GetResourcePolicy` without a policy answers `{"Policy": "{}"}` and `DeleteResourcePolicy` "No resource policy found for resource ARN <arn>.". Cross-account event source mappings are not covered yet. Reported by @Jolley71717.+- **Kinesis — stream and consumer resource policies** — `PutResourcePolicy`, `GetResourcePolicy` and `DeleteResourcePolicy` answered `InvalidAction`; they now store a policy per stream or consumer, persisted and dropped with it, with AWS's checks in AWS's order: the ARN's region (`InvalidArgumentException` "The region specified in the ARN '<arn>' does not match the endpoint region"), the policy ("Policy validation error: This policy contains invalid Json", "Missing required field Version" or "Statement", and per statement the actions a stream or consumer can share and a `Resource` equal to the ARN, with the statement's line and column), then the resource ("Stream <name> under account <id> not found."). `GetResourcePolicy` without a policy answers `{"Policy": "{}"}` and `DeleteResourcePolicy` "No resource policy found for resource ARN <arn>.". A stream policy may also share `kinesis:DescribeStream`. Reported by @Jolley71717.- **OpenSearch — engine containers run with a 512 MB heap** — every container MiniStack starts for a domain or Serverless collection used the image's 1 GB heap, too much for a small machine with several of them; each now runs with `-Xms512m -Xmx512m`, the heap OpenSearch's sample docker-compose uses. Contributed by @skialpine.### Fixed@@ -44,7 +44,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **ALB — an OPTIONS request reaches the target** — the gateway answered every preflight to a load balancer address with its own wildcard CORS response. The request is now forwarded to the target like any other method. Contributed by @skialpine.- **ALB — the query string reaches HTTP targets unchanged** — it was rebuilt from the first value of each key, so `?page=1&page=2` arrived as `?page=1`. The request's own query string is now forwarded, including from a CloudFront distribution whose origin is the load balancer. Contributed by @skialpine.- **ALB — instance and IP targets receive the client's `Host`** — they got their own address as `Host`. They now get the client's, as an Application Load Balancer sends it: on a listener on port 80 or 443 without a port, on any other listener with the listener's port in place of any port the client sent; `routing.http.preserve_host_header.enabled` sends it unmodified. Lambda targets keep the `Host` exactly as sent, and authentication uses the client's `Host`. Contributed by @skialpine.-- **Lambda — a Kinesis event source mapping in another region or account answers as AWS does** — `CreateEventSourceMapping` now refuses another region's stream with "Event source region must match Lambda region <region>" and another account's with "Received Exception while reading from provided stream. No account found for the given parameters". Reported by @Jolley71717.+- **Lambda — Kinesis event source mappings across accounts** — a mapping to another account's stream was refused as invalid; a function can now map a stream in another account in the same region, read from the owner's account. `CreateEventSourceMapping` reads the stream first, as AWS does, and answers "Received Exception while reading from provided stream. " followed by why it can't: "No account found for the given parameters", "Stream <name> under account <id> not found.", or, under `AUTH=true`, the read the stream's resource policy doesn't allow the function's execution role (`DescribeStream`, `DescribeStreamSummary`, `GetRecords`, `GetShardIterator`, `ListShards`). The policy is checked again on every poll, so revoking it stops delivery. Another region's stream answers "Event source region must match Lambda region <region>". Reported by @Jolley71717.## [1.5.32] — 2026-10-23diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.pyindex eaf5fdc4..6cc41540 100644--- a/ministack/core/iam_evaluator.py+++ b/ministack/core/iam_evaluator.py@@ -794,6 +794,7 @@ _RESOURCE_POLICY_LOOKUPS = {"ecr": ("ecr", "repository_policy_for_arn"),"kms": ("kms", "key_policy_for_arn"),"apigateway": ("apigateway_v1", "rest_api_policy_for_arn"),+ "kinesis": ("kinesis", "stream_policy_for_arn"),}# A key policy must allow even the owner's own users and roles.diff --git a/ministack/services/kinesis.py b/ministack/services/kinesis.pyindex 6d51fdbc..c4fb4b79 100644--- a/ministack/services/kinesis.py+++ b/ministack/services/kinesis.py@@ -1420,10 +1420,11 @@ def _cbor_response(data: dict, status: int = 200):# Resource policies (codes and messages as AWS answered them, us-east-1, 2026-10-26)# ----------------------------------------------------------------------------# The actions a policy may share (Kinesis Data Streams developer guide, "Controlling access").+# The actions a policy may share (Kinesis Data Streams developer guide, "Controlling access", and+# DescribeStream, which its cross-account Lambda section says to include)._POLICY_ACTIONS = {- "stream": {"kinesis:DescribeStreamSummary", "kinesis:GetRecords", "kinesis:GetShardIterator",- "kinesis:ListShards", "kinesis:PutRecord", "kinesis:PutRecords"},+ "stream": {"kinesis:DescribeStream", "kinesis:DescribeStreamSummary", "kinesis:GetRecords",+ "kinesis:GetShardIterator", "kinesis:ListShards", "kinesis:PutRecord", "kinesis:PutRecords"},"consumer": {"kinesis:DescribeStreamConsumer", "kinesis:SubscribeToShard"},}@@ -1525,6 +1526,40 @@ def _policy_resource(resource_arn, policy=None):return kind, None+def stream_policy_for_arn(resource_arn):+ """The resource policy and owner account of a stream or consumer, for the IAM evaluator; looked up+ in the ARN's own account and region, since a cross-account caller's scope is its own account."""+ from ministack.core.responses import request_scope++ account_id, region = _kinesis_arn_scope(resource_arn)+ with request_scope(account_id, region):+ if not (_resolve_stream_by_arn(resource_arn) or _consumer_from_arn(resource_arn)):+ return None+ return _resource_policies.get(resource_arn) or "", account_id+++# What an event source mapping reads from a stream (Lambda developer guide, Kinesis permissions).+_MAPPING_READ_ACTIONS = ("kinesis:DescribeStream", "kinesis:DescribeStreamSummary", "kinesis:GetRecords",+ "kinesis:GetShardIterator", "kinesis:ListShards")+++def mapping_read_denied(stream_arn, role_arn, function_name, mapping_account):+ """The first read a cross-account mapping's execution role may not make on the stream, or None.+ Only the stream's resource policy can grant another account."""+ from ministack.core.iam_evaluator import EvalContext, evaluate_resource_policy++ found = stream_policy_for_arn(stream_arn)+ policy = found[0] if found else ""+ role_name = role_arn.rsplit("/", 1)[-1] if ":role/" in role_arn else ""+ session = f"arn:aws:sts::{mapping_account}:assumed-role/{role_name}/{function_name}"+ for action in _MAPPING_READ_ACTIONS:+ ctx = EvalContext(principal_arn=session, principal_type="AssumedRole", principal_account=mapping_account,+ action=action, resource_arn=stream_arn, region=_kinesis_arn_scope(stream_arn)[1])+ if not policy or evaluate_resource_policy(policy, ctx).decision != "Allow":+ return session, action+ return None++def _put_resource_policy(data):resource_arn, policy = data.get("ResourceARN"), data.get("Policy")_kind, err = _policy_resource(resource_arn, policy if isinstance(policy, str) else "")diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex e5367bd6..bf9874c6 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -1150,9 +1150,10 @@ def _validate_event_source_arn(event_source_arn: str):if spec.service == "kinesis" and spec.region != get_region():return None, _invalid_parameter_value(f"Event source region must match Lambda region {get_region()}")if spec.service == "kinesis" and spec.account_id != get_account_id():- # Another account's stream is not readable here; this is what AWS answers when it cannot read it.- return None, _invalid_parameter_value(- "Received Exception while reading from provided stream. No account found for the given parameters")+ # Another account's stream is read through its resource policy; _create_esm checks it can be read.+ if not _kinesis_stream_name_from_arn_spec(spec):+ return None, _invalid_parameter_value(f"Invalid event source ARN: {event_source_arn}")+ return spec, Nonescope_err = _require_same_account_region_arn(spec, event_source_arn, "event source")if scope_err:return None, scope_err@@ -7201,6 +7202,31 @@ def _validate_scaling_config(data: dict, source_arn: str = ""):return None+def _cross_account_stream_read_error(stream_arn: str, func_name: str, qualifier: str | None):+ """Why a mapping cannot read another account's stream, as AWS answers when it tries, or None."""+ from ministack.app import AUTH+ from ministack.services import kinesis as _kin++ spec = parse_arn(stream_arn)+ prefix = "Received Exception while reading from provided stream. "+ if not any(account == spec.account_id for (account, _region, _name), _s in _kin._streams.all_items()):+ return _invalid_parameter_value(prefix + "No account found for the given parameters")+ name = _kinesis_stream_name_from_arn_spec(spec)+ stream = _kin._streams.get_scoped(spec.account_id, spec.region, name)+ if not stream or stream.get("StreamARN") != stream_arn:+ return _invalid_parameter_value(prefix + f"Stream {name} under account {spec.account_id} not found.")+ if AUTH:+ func_rec, _cfg = _get_func_record_for_qualifier(func_name, qualifier)+ role = ((func_rec or {}).get("config") or {}).get("Role", "")+ denied = _kin.mapping_read_denied(stream_arn, role, func_name, get_account_id())+ if denied:+ session, action = denied+ return _invalid_parameter_value(+ prefix + f"User: {session} is not authorized to perform: {action} on resource: {stream_arn} "+ f"because no resource-based policy allows the {action} action")+ return None++def _create_esm(data: dict):err = _validate_scaling_config(data, data.get("EventSourceArn", ""))if err:@@ -7217,6 +7243,10 @@ def _create_esm(data: dict):event_source_spec, err = _validate_event_source_arn(event_source_arn)if err:return err+ if event_source_spec.service == "kinesis" and event_source_spec.account_id != get_account_id():+ err = _cross_account_stream_read_error(event_source_arn, func_name, qualifier)+ if err:+ return errenabled = data.get("Enabled", True)if isinstance(enabled, str):@@ -7677,6 +7707,17 @@ def _run_sqs_batch(esm, func_rec, event, batch, queue_url, queue_name):logger.info("ESM: Lambda %s output:\n%s", func_name, log_output)+def _cross_account_read_blocked(stream_arn, func_rec, func_name) -> bool:+ """Under AUTH=true the stream's policy must still allow the function's role on every pass."""+ from ministack.app import AUTH+ from ministack.services import kinesis as _kin++ if not AUTH:+ return False+ role = (func_rec.get("config") or {}).get("Role", "")+ return _kin.mapping_read_denied(stream_arn, role, func_name, get_account_id()) is not None++def _poll_kinesis():"""Returns True if any shard advanced past a batch this pass (successfullyinvoked, or filtered out entirely)."""@@ -7695,11 +7736,7 @@ def _poll_kinesis():source_spec = parse_arn(source_arn)except ArnParseError:continue- if (- source_spec.service != "kinesis"- or source_spec.account_id != get_account_id()- or source_spec.region != get_region()- ):+ if source_spec.service != "kinesis" or source_spec.region != get_region():continuestream_name = _kinesis_stream_name_from_arn_spec(source_spec)if not stream_name:@@ -7711,9 +7748,12 @@ def _poll_kinesis():if func_rec is None:continue- stream = _kin._streams.get(stream_name)+ # A cross-account mapping reads the stream in its owner's account, while its policy allows it.+ stream = _kin._streams.get_scoped(source_spec.account_id, source_spec.region, stream_name)if not stream or stream.get("StreamARN") != source_arn or stream["StreamStatus"] != "ACTIVE":continue+ if source_spec.account_id != get_account_id() and _cross_account_read_blocked(source_arn, func_rec, func_name):+ continueesm_id = esm["UUID"]if _esm_backoff_until.get(esm_id, 0) > time.time():diff --git a/tests/test_kinesis.py b/tests/test_kinesis.pyindex 0589fd9b..e9148088 100644--- a/tests/test_kinesis.py+++ b/tests/test_kinesis.py@@ -1073,3 +1073,82 @@ def test_kinesis_esm_filter_criteria_match_decoded_data_and_metadata(lam, kin, llam.delete_event_source_mapping(UUID=esm)lam.delete_function(FunctionName=fn)kin.delete_stream(StreamName=stream)+++def _account_client(service, account):+ return boto3.client(service, endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),+ aws_access_key_id=account, aws_secret_access_key="test", region_name="us-east-1")+++def test_kinesis_esm_reads_a_stream_in_another_account(lam, logs, auth_enabled):+ """A function in one account maps a stream in another (same region); records reach it. Under AUTH=true+ the stream's resource policy must allow the function's execution role."""+ if auth_enabled:+ pytest.skip("account selection by access key needs AUTH unset")+ owner = _account_client("kinesis", "111111111111")+ stream = f"xacct-{_uuid_mod.uuid4().hex[:8]}"+ owner.create_stream(StreamName=stream, ShardCount=1)+ arn = owner.describe_stream_summary(StreamName=stream)["StreamDescriptionSummary"]["StreamARN"]+ for n in range(3):+ owner.put_record(StreamName=stream, Data=f"rec-{n}".encode(), PartitionKey="pk")++ fn = f"xacct-fn-{_uuid_mod.uuid4().hex[:8]}"+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", _FILTER_HANDLER)+ lam.create_function(FunctionName=fn, Runtime="python3.12", Role=_LAMBDA_ROLE,+ Handler="index.handler", Code={"ZipFile": buf.getvalue()})+ try:+ missing = arn.rsplit("/", 1)[0] + "/no-such-stream"+ with pytest.raises(ClientError) as exc:+ lam.create_event_source_mapping(FunctionName=fn, EventSourceArn=missing, StartingPosition="LATEST")+ assert exc.value.response["Error"]["Message"] == (+ "Received Exception while reading from provided stream. "+ "Stream no-such-stream under account 111111111111 not found.")+ esm = lam.create_event_source_mapping(FunctionName=fn, EventSourceArn=arn,+ StartingPosition="TRIM_HORIZON")["UUID"]+ received, deadline = [], time.time() + 30+ while time.time() < deadline and len(received) < 3:+ try:+ events = logs.filter_log_events(logGroupName=f"/aws/lambda/{fn}")["events"]+ except ClientError:+ events = []+ received = [line[len("XREC "):] for e in events for line in e["message"].splitlines()+ if line.startswith("XREC ")]+ time.sleep(0.5)+ assert received == ["rec-0", "rec-1", "rec-2"]+ lam.delete_event_source_mapping(UUID=esm)+ finally:+ lam.delete_function(FunctionName=fn)+ owner.delete_stream(StreamName=stream)+++def test_kinesis_mapping_read_needs_every_read_in_the_stream_policy():+ """The stream policy must allow the function's role session every read a mapping makes."""+ from ministack.core.responses import request_scope+ from ministack.services import kinesis as kmod++ owner, consumer, name = "111111111111", "222222222222", f"pol-{_uuid_mod.uuid4().hex[:8]}"+ arn = f"arn:aws:kinesis:us-east-1:{owner}:stream/{name}"+ role = f"arn:aws:iam::{consumer}:role/reader"+ with request_scope(owner, "us-east-1"):+ kmod._create_stream({"StreamName": name, "ShardCount": 1})+ try:+ assert kmod.mapping_read_denied(arn, role, "fn", consumer)[1] == "kinesis:DescribeStream"+ reads = ["kinesis:DescribeStream", "kinesis:DescribeStreamSummary", "kinesis:GetRecords",+ "kinesis:GetShardIterator", "kinesis:ListShards"]++ def grant(actions):+ with request_scope(owner, "us-east-1"):+ kmod._resource_policies[arn] = json.dumps({"Version": "2012-10-17", "Statement": [{+ "Effect": "Allow", "Principal": {"AWS": role}, "Action": actions, "Resource": arn}]})++ grant(reads[:-1])+ assert kmod.mapping_read_denied(arn, role, "fn", consumer)[1] == "kinesis:ListShards"+ grant(reads)+ assert kmod.mapping_read_denied(arn, role, "fn", consumer) is None+ assert kmod.mapping_read_denied(arn, f"arn:aws:iam::{consumer}:role/other", "fn", consumer) is not None+ finally:+ with request_scope(owner, "us-east-1"):+ kmod._resource_policies.pop(arn, None)+ kmod._streams.pop(name, None)diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex f92722cb..4b0cd8fe 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -15775,7 +15775,8 @@ def test_lambda_code_caches_belong_to_this_instance():@pytest.mark.parametrize("event_source_arn, message", [("arn:aws:kinesis:us-west-2:000000000000:stream/esm-kinesis-source","Event source region must match Lambda region us-east-1"),- ("arn:aws:kinesis:us-east-1:111111111111:stream/esm-kinesis-source",+ # An account that holds nothing in this MiniStack, as AWS answered for an account that does not exist.+ ("arn:aws:kinesis:us-east-1:987654321098:stream/esm-kinesis-source","Received Exception while reading from provided stream. No account found for the given parameters"),])def test_lambda_create_esm_kinesis_scope_messages_follow_aws(lam, event_source_arn, message):