Skip to content

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

fix: four shadowed definitions and eight port-bound tests (#1714)

iot-rocket280885171832
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dfc50977..6ab301eb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to MiniStack will be documented here.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
Versioning follows [Semantic Versioning](https://semver.org/).
+## [Unreleased]
+
+### Fixed
+- **IAM — one `_account_from_arn`, with the contract the condition evaluator documents** — the module carried two top-level definitions of the helper under the same name, so the later one silently won and the guards the documented one describes (a bare `*`, a value that is not an ARN at all, an AWS-owned `arn:aws:iam::aws:policy/...`) were not the ones in force when `aws:ResourceAccount` resolved a resource's account. They are folded into one definition that keeps both contracts: the field is returned only when it holds an account id, twelve digits, and only from a value that is an ARN. No request the emulator serves changes behaviour, because both callers pass an ARN whose account is twelve digits; the parametrized test gained the two cases that tell the former definitions apart. Contributed by @iot-rocket.
+- **Test harness — the suite runs on a non-default `GATEWAY_PORT`** — eight tests compared a value a service had built from `GATEWAY_PORT` against a hard-coded `4566`, so the suite passed only on the default port. That is the port a contributor moves off to run a private server rather than resetting a shared one, which is exactly when the failures appear and look like real regressions. The ESM tests now key their queues through `sqs._queue_url()`, the AppSync and Glue assertions read the port from one place in `tests/conftest.py`, and the three files pass on any port. No user-visible behavior changes. Contributed by @iot-rocket.
+
## [1.5.11] — 2026-09-13
### Added
diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.py
index 1d70487b..c65ced6c 100644
--- a/ministack/core/iam_evaluator.py
+++ b/ministack/core/iam_evaluator.py
@@ -132,19 +132,24 @@ def _resource_matches(resource_arn: str, resources: list[str],
# Condition evaluation
# ---------------------------------------------------------------------------
+_ACCOUNT_ID_RE = re.compile(r"^\d{12}$")
+
+
def _account_from_arn(arn: str) -> str | None:
"""The account field of an ARN, or None when the ARN carries none: ``*``,
partition-only ARNs such as S3 (``arn:aws:s3:::bucket``), AWS-owned ARNs
- (``arn:aws:iam::aws:policy/...``) and malformed values."""
+ (``arn:aws:iam::aws:policy/...``) and malformed values.
+
+ An account id is twelve digits, so anything else standing in that field —
+ ``aws`` on an AWS-owned ARN, a service name, an empty segment — reads as
+ "this ARN names no account" rather than as an account called ``aws``.
+ """
if not arn or arn == "*" or not arn.startswith("arn:"):
return None
parts = arn.split(":", 5)
if len(parts) < 6:
return None
- account = parts[4]
- if not account or account == "aws":
- return None
- return account
+ return parts[4] if _ACCOUNT_ID_RE.fullmatch(parts[4]) else None
def _resolve_condition_key(key: str, ctx: EvalContext) -> Any:
@@ -638,7 +643,6 @@ def _resolve_managed_policy_document(policy_arn: str,
# Access-key resolution — the credentials and principals MiniStack issued
# ---------------------------------------------------------------------------
-_ACCOUNT_ID_RE = re.compile(r"^\d{12}$")
_SESSION_TOKEN_NOT_CHECKED = object()
@@ -691,13 +695,6 @@ def _invalid_session_token() -> CredentialResolutionError:
)
-def _account_from_arn(arn: str) -> str | None:
- parts = arn.split(":")
- if len(parts) > 4 and _ACCOUNT_ID_RE.fullmatch(parts[4]):
- return parts[4]
- return None
-
-
def _principal_type(arn: str, recorded_type: str) -> str:
if recorded_type:
return recorded_type
diff --git a/tests/conftest.py b/tests/conftest.py
index 8a613d31..7fd5a67f 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -21,6 +21,14 @@ from botocore.config import Config
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
ENDPOINT_HOST = urlparse(ENDPOINT).hostname
+# The port the services advertise themselves on, read the way they read it: an
+# `or` chain, so an empty string falls through exactly as it does in
+# ministack/app.py. A test asserting on a value a service built from this has
+# to use the same source. MINISTACK_ENDPOINT above can be set independently, so
+# deriving the port from it would agree only by coincidence. Note that some
+# services read GATEWAY_PORT alone, without the EDGE_PORT fallback; this
+# constant is for the ones that render an advertised endpoint.
+GATEWAY_PORT = os.environ.get("GATEWAY_PORT") or os.environ.get("EDGE_PORT") or "4566"
REGION = "us-east-1"
_default_kwargs = dict(
diff --git a/tests/test_appsync_events.py b/tests/test_appsync_events.py
index 97a2cdd8..066a6f0a 100644
--- a/tests/test_appsync_events.py
+++ b/tests/test_appsync_events.py
@@ -29,6 +29,7 @@ from urllib.parse import urlparse
import boto3
import pytest
from botocore.exceptions import ClientError
+from conftest import GATEWAY_PORT
_ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
_PORT = urlparse(_ENDPOINT).port or 4566
@@ -211,7 +212,7 @@ async def _invoke_asgi_http(
"query_string": b"",
"headers": headers,
"client": ("127.0.0.1", 55555),
- "server": ("127.0.0.1", 4566),
+ "server": ("127.0.0.1", int(GATEWAY_PORT)),
}
body_sent = False
@@ -671,7 +672,7 @@ def test_unsigned_api_key_publish_discovers_event_api_host_region(monkeypatch):
api_id = created["apiId"]
custom_pub_host = created["dns"]["HTTP"]
assert custom_pub_host == (
- f"{api_id}.appsync-api.internal-edge-1:4566"
+ f"{api_id}.appsync-api.internal-edge-1:{GATEWAY_PORT}"
)
ns_msgs = await _invoke_asgi_http(
@@ -1133,7 +1134,7 @@ def test_websocket_accepts_region_shaped_configured_custom_host(monkeypatch):
api_id = created["apiId"]
custom_host = created["dns"]["REALTIME"]
assert custom_host == (
- f"{api_id}.appsync-realtime-api.internal-edge-1:4566"
+ f"{api_id}.appsync-realtime-api.internal-edge-1:{GATEWAY_PORT}"
)
set_request_region("us-east-1")
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index 665fbf7e..2718c745 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -2914,11 +2914,6 @@ def _post_form(url, data, headers=None, follow_redirects=True):
return e.code, _lower_headers(e.headers), e.read()
-class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):
- def redirect_request(self, req, fp, code, msg, headers, newurl):
- raise urllib.error.HTTPError(newurl, code, msg, headers, fp)
-
-
# ---------------------------------------------------------------------------
# Tests — /oauth2/authorize
# ---------------------------------------------------------------------------
diff --git a/tests/test_glue.py b/tests/test_glue.py
index e03b544b..aad1de2f 100644
--- a/tests/test_glue.py
+++ b/tests/test_glue.py
@@ -9,6 +9,7 @@ import boto3
import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
+from conftest import GATEWAY_PORT
import ministack.core.responses as _responses
from ministack.core.router import detect_service
@@ -2525,7 +2526,7 @@ def test_glue_spark_container_env_points_sdk_at_ministack(tmp_path, monkeypatch)
_glue._execute_spark_docker(run, {"Timeout": 1}, "envjob", {}, str(script), _FakeDocker())
env = created["environment"]
- assert env["AWS_ENDPOINT_URL"] == "http://host.docker.internal:4566"
+ assert env["AWS_ENDPOINT_URL"] == f"http://host.docker.internal:{GATEWAY_PORT}"
# The SDK endpoint and the Spark S3A endpoint must agree.
s3a = [c for c in created["command"] if isinstance(c, str) and c.startswith("spark.hadoop.fs.s3a.endpoint=")]
assert s3a == [f"spark.hadoop.fs.s3a.endpoint={env['AWS_ENDPOINT_URL']}"]
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index a0e603f9..ddb77b8f 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -458,6 +458,8 @@ class TestResourceAccountCondition:
("arn:aws:sqs:us-east-1:222222222222:q", "222222222222"),
("not-an-arn", None),
("arn:aws:sqs", None), # too short
+ ("arn:aws:sqs:us-east-1:12345:q", None), # not twelve digits
+ ("a:b:c:d:123456789012:e", None), # twelve digits, not an ARN
])
def test_account_from_arn(self, arn, expected):
from ministack.core.iam_evaluator import _account_from_arn
diff --git a/tests/test_iot_jobs.py b/tests/test_iot_jobs.py
index 5b627197..de321e6e 100644
--- a/tests/test_iot_jobs.py
+++ b/tests/test_iot_jobs.py
@@ -1247,12 +1247,6 @@ def _frames_by_topic(received):
return {topic: json.loads(payload) for topic, payload in received}
-def _assert_epoch_seconds(value):
- """Stamps must be whole epoch seconds — milliseconds are off by 1000x."""
- assert isinstance(value, int)
- assert abs(value - time.time()) < 5 * 60
-
-
def test_jobs_mqtt_create_job_notifies_and_get_lists(iot_client, iot_data_client):
"""CreateJob publishes notify (per-status aggregate) + notify-next (full
execution incl. the jobDocument as an object) to each target thing; a
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index d9d5539b..b8f4a1cb 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -3,11 +3,10 @@ import contextlib
import io
import json
import os
+import shutil
import socket
import sys
import threading
-import shutil
-import sys
import time
import urllib.error as _urlerr
import urllib.request as _urlreq
@@ -4925,7 +4924,7 @@ def test_lambda_sqs_poller_does_not_tail_match_foreign_region_event_source(monke
_sqs._queues.clear()
queue_name = "esm-runtime-region-guard"
- queue_url = f"http://localhost:4566/000000000000/{queue_name}"
+ queue_url = _sqs._queue_url(queue_name)
_sqs._queues[queue_url] = {
"name": queue_name,
"messages": [{
@@ -5181,7 +5180,7 @@ def test_poll_sqs_returns_true_when_batch_processed(esm_poll_state, monkeypatch)
_lsvc, _sqs, _kin, _ddb = esm_poll_state
queue_name = "esm-drain-signal"
- queue_url = f"http://localhost:4566/000000000000/{queue_name}"
+ queue_url = _sqs._queue_url(queue_name)
_sqs._queues[queue_url] = {
"name": queue_name,
"messages": [{
@@ -5304,7 +5303,7 @@ def test_poll_sqs_returns_false_when_invoke_fails(esm_poll_state, monkeypatch):
_lsvc, _sqs, _kin, _ddb = esm_poll_state
queue_name = "esm-drain-signal-failure"
- queue_url = f"http://localhost:4566/000000000000/{queue_name}"
+ queue_url = _sqs._queue_url(queue_name)
_sqs._queues[queue_url] = {
"name": queue_name,
"messages": [{
@@ -5355,7 +5354,7 @@ def test_poll_sqs_backs_off_failing_esm_without_starving_other_esms(esm_poll_sta
_lsvc, _sqs, _kin, _ddb = esm_poll_state
def make_queue(name):
- queue_url = f"http://localhost:4566/000000000000/{name}"
+ queue_url = _sqs._queue_url(name)
_sqs._queues[queue_url] = {
"name": name,
"messages": [{
@@ -5453,7 +5452,7 @@ def test_poll_sqs_record_carries_trace_header_and_fifo_attributes(esm_poll_state
_lsvc, _sqs, _kin, _ddb = esm_poll_state
queue_name = "esm-trace-attrs"
- queue_url = f"http://localhost:4566/000000000000/{queue_name}"
+ queue_url = _sqs._queue_url(queue_name)
trace = "Root=1-6893a2b4-aaaabbbbccccddddeeeeffff;Parent=0123456789abcdef;Sampled=1"
base = {
"md5_body": "", "sent_at": time.time(), "visible_at": 0,
@@ -5521,7 +5520,7 @@ def test_poll_sqs_retries_esm_after_backoff_expires(esm_poll_state, monkeypatch)
_lsvc, _sqs, _kin, _ddb = esm_poll_state
queue_name = "esm-drain-signal-recovers"
- queue_url = f"http://localhost:4566/000000000000/{queue_name}"
+ queue_url = _sqs._queue_url(queue_name)
_sqs._queues[queue_url] = {
"name": queue_name,
"messages": [{
@@ -6235,7 +6234,7 @@ def test_route_async_failure_to_sqs_dlq():
set_request_account_id("000000000000")
set_request_region("us-east-1")
# Create a queue directly in the internal state
- url = "http://localhost:4566/000000000000/dlq-test"
+ url = _sqs._queue_url("dlq-test")
arn = "arn:aws:sqs:us-east-1:000000000000:dlq-test"
_sqs._queues[url] = {
"messages": [], "attributes": {"QueueArn": arn},
@@ -6377,7 +6376,7 @@ def test_route_async_failure_to_sqs_does_not_tail_match_foreign_region():
original_region = get_region()
set_request_account_id("000000000000")
set_request_region("us-east-1")
- url = "http://localhost:4566/000000000000/dlq-region-guard"
+ url = _sqs._queue_url("dlq-region-guard")
arn = "arn:aws:sqs:us-east-1:000000000000:dlq-region-guard"
_sqs._queues[url] = {
"messages": [], "attributes": {"QueueArn": arn},