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
fix(router): route by host pattern only for hosts the stack serves (#1597)
iot-rocket588ae8790c64
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dc57d27d..9d6f817b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added- **ALB — the `authenticate-oidc` listener action authenticates** — a rule accepted the action's `Type` and silently discarded its `AuthenticateOidcConfig`, so an OIDC-protected service tested against MiniStack passed while every request reached the target unauthenticated. The flow now runs end to end as AWS documents it: an unauthenticated request is redirected to the `AuthorizationEndpoint` with `state`, the callback at `/oauth2/idpresponse` exchanges the code at the `TokenEndpoint` and fetches the claims from the `UserInfoEndpoint`, and the session is written to the client as `AWSELBAuthSessionCookie` shards sized so the whole Set-Cookie pair fits the 4096-byte browser ceiling. Later requests reassemble and validate the shards and reach the target with `x-amzn-oidc-identity`, `x-amzn-oidc-accesstoken` and `x-amzn-oidc-data` — the last as the user claims in AWS's signed-JWT shape (`kid`, `signer`, `iss`, `client`, `exp` in the header; the provider's ID token is never passed to the backend), with any client-supplied copies of those headers stripped so an identity cannot be forged even under `OnUnauthenticatedRequest=allow`. `SessionCookieName`, `SessionTimeout`, `Scope` and all three `OnUnauthenticatedRequest` modes are honoured; an unmatched or expired callback answers `401` per the 15-minute login bound; `ClientSecret` is held for the exchange and never echoed from `Describe*`. Two data-plane fixes came with it: a rule's actions now run as a chain in `Order` (dispatch executed only `Actions[0]`, so authenticate-then-forward could not work), and `ModifyListener` now updates the auto-created default rule the data plane actually serves. `authenticate-cognito` answers `501` rather than forwarding a request nobody authenticated. Contributed by @dhanesh.+- **Router — an unregistered `Host` is no longer routed by service-token substring** — the host-pattern step of `detect_service()` ran the unanchored `iot\.`, `logs\.`, `email\.`, `lambda\.` … regexes over any `Host` the earlier steps (X-Amz-Target, SigV4 credential scope, query `Action`, path) had not classified, so a request for `probe.iot.example.com` answered `Unsupported IoT path` and `logs.example.com` landed in CloudWatch Logs — a customer domain behind a proxy, or a health check with a made-up `Host`, was read as an AWS endpoint. Host patterns are now consulted only for hosts the stack serves: a single label (`ministack`, `localhost`, a compose service name), a two-label alias (`s3.dev`), an IP literal, or a name under `localhost`, `localhost.localstack.cloud`, `amazonaws.com`, `MINISTACK_HOST`, the container hostname or the new comma-separated `MINISTACK_EXTRA_HOST_SUFFIXES`, matched at a label boundary. Every other `Host` falls through to the default as before. On a served host each bare service token is anchored at a label start (`(^|\.)iot\.`), so `probe-iot.localhost` is not IoT either; `<bucket>.s3.<region>`, `<api-id>.execute-api.<region>`, `<prefix>-ats.iot.<region>`, `streams.dynamodb.` and the other AWS shapes route exactly as they did. Contributed by @iot-rocket.- **IAM — the AWS-managed policies a CDK, SAM or Serverless deployment attaches resolve by their real ARNs** — the seeded catalogue filed the Lambda execution-role policies under `arn:aws:iam::aws:policy/<Name>` while AWS publishes them under `…:policy/service-role/<Name>`, the only ARN those tools emit, so `GetPolicy` on the real ARN answered `NoSuchEntity` and under `AUTH=true` a role that attached one carried no permissions from it; `AWSCloudFormationReadOnlyAccess` (the CDK deploy role's read grant), `CloudWatchLambdaInsightsExecutionRolePolicy`, `service-role/AmazonAPIGatewayPushToCloudWatchLogs` and `service-role/AWSIoTThingsRegistration` were missing altogether, which denied `cdk deploy` its first `DescribeStacks` under enforcement. The catalogue now carries them under their real path with the documents from the AWS Managed Policy Reference, reports `PolicyName` and `Path` as AWS does (so `ListPolicies` with `PathPrefix=/service-role/` finds them), adds the SQS, Kinesis and DynamoDB Lambda execution-role policies, and keeps the four path-less ARNs earlier versions seeded as aliases of the real record. Contributed by @iot-rocket.- **IAM enforcement — the `aws:ResourceAccount` condition key resolves** — with `AUTH=true` a statement conditioned on `aws:ResourceAccount` (or its `s3:ResourceAccount` alias) never matched: the key was unknown to the evaluator, an unknown key is a no-match, and the statement's Allow never applied. CDK's own bootstrap template conditions the file-publishing role's S3 grant on exactly this key, so every `cdk deploy` under enforcement failed at asset publishing with "Bucket ... exists, but we dont have access to it". The key now resolves to the account that owns the resource — the requesting account, since MiniStack hosts one account per request and models no cross-account access, unless the resource ARN carries a different account field, which wins. A condition naming another account still denies, and every other unknown global key keeps denying. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex d4e7e7c6..7dd390fa 100644--- a/README.md+++ b/README.md@@ -798,6 +798,7 @@ end-to-end without any client config.|----------|---------|-------------|| `GATEWAY_PORT` | `4566` | Port to listen on. Also accepts `EDGE_PORT` (LocalStack compatibility alias) || `MINISTACK_HOST` | `localhost` | Hostname used in response URLs (SQS queues, SNS subscriptions, API Gateway endpoints, Lambda layers) |+| `MINISTACK_EXTRA_HOST_SUFFIXES` | _(unset)_ | Comma-separated domain suffixes MiniStack is reachable under besides `localhost`, `*.localhost` / `localhost.localstack.cloud`, `amazonaws.com`, `MINISTACK_HOST`, the container hostname, two-label aliases and IP literals. Routing by host name (`s3.<suffix>`, `<api-id>.execute-api.<suffix>`) applies only to served hosts; any other `Host` is routed by the request alone || `MINISTACK_ACCOUNT_ID` | `000000000000` | Default AWS account ID. Overridden per-request when `AWS_ACCESS_KEY_ID` is a 12-digit number (see [Multi-Tenancy](#multi-tenancy)) || `MINISTACK_REGION` | `us-east-1` | AWS region reported in ARNs and service responses across all services || `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING`, `ERROR` |diff --git a/ministack/core/router.py b/ministack/core/router.pyindex 9aee28bb..f5b7b609 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -7,9 +7,11 @@ Routes incoming requests to the correct service handler based on:- URL path patterns (e.g., /2015-03-31/functions for Lambda)"""+import ipaddressimport loggingimport osimport re+import socketfrom urllib.parse import unquotefrom ministack.core.arn import ArnParseError, parse_arn@@ -475,6 +477,109 @@ _OPENSEARCH_PATH_PREFIXES = tuple()+# Host-header routing (step 5 of detect_service) is restricted to hosts the+# stack is reachable under. Real AWS endpoints are ``<service>.<region>.+# amazonaws.com``; local deployments answer under ``localhost``,+# ``*.localhost`` / ``localhost.localstack.cloud``, the bare container name,+# a two-label alias (``s3.dev``, ``sqs.internal``), an IP literal,+# ``MINISTACK_HOST`` and whatever the operator adds through+# ``MINISTACK_EXTRA_HOST_SUFFIXES`` (comma-separated; ``s3.<suffix>``,+# ``<api-id>.execute-api.<suffix>``, ``<prefix>-ats.iot.<region>.<suffix>``).+# Anything else — a customer domain fronted by a proxy, a probe with a+# made-up Host — is never an AWS endpoint, so its labels carry no routing+# information.+_BUILTIN_HOST_SUFFIXES = (+ "localhost",+ "localhost.localstack.cloud",+ "amazonaws.com",+ "amazonaws.com.cn",+)+++def _container_hostname() -> str:+ try:+ return socket.gethostname().lower()+ except OSError:+ return ""+++_CONTAINER_HOSTNAME = _container_hostname()+++def _served_host_suffixes() -> tuple:+ """Suffixes (lower-case, no port) a Host header may end with to qualify for+ host-pattern routing. Read per call so tests and init scripts can change the+ environment without a restart; the work is a handful of dict lookups."""+ suffixes = list(_BUILTIN_HOST_SUFFIXES)+ for value in (+ os.environ.get("MINISTACK_HOST", ""),+ os.environ.get("HOSTNAME", ""),+ _CONTAINER_HOSTNAME,+ ):+ value = _strip_host_port(value)+ if value:+ suffixes.append(value)+ for value in os.environ.get("MINISTACK_EXTRA_HOST_SUFFIXES", "").split(","):+ value = _strip_host_port(value).strip(".")+ if value:+ suffixes.append(value)+ return tuple(suffixes)+++def _strip_host_port(host: str) -> str:+ """``example.com:4566`` -> ``example.com``; ``[::1]:4566`` -> ``::1``.+ Lower-cases and trims whitespace."""+ host = (host or "").strip().lower()+ if host.startswith("["):+ end = host.find("]")+ return host[1:end] if end > 0 else host+ if host.count(":") == 1:+ return host.rsplit(":", 1)[0]+ return host # bare IPv6 without brackets, or no port+++def _host_served_by_stack(host: str) -> bool:+ """True when ``host`` names this stack: no Host at all, a single label+ (``ministack``, ``localhost``, a compose service name), a two-label alias+ (``s3.dev``), an IPv4/IPv6 literal, or a name under one of the served+ suffixes at a label boundary (``s3.localhost.localstack.cloud`` yes,+ ``notlocalhost`` no). A customer domain has at least three labels."""+ hostname = _strip_host_port(host)+ if not hostname or "." not in hostname:+ return True+ try:+ ipaddress.ip_address(hostname)+ return True+ except ValueError:+ pass+ hostname = hostname.rstrip(".")+ if hostname.count(".") == 1:+ return True # ``<service>.<lan-suffix>`` alias, the LocalStack-era shape+ for suffix in _served_host_suffixes():+ if hostname == suffix or hostname.endswith("." + suffix):+ return True+ return False+++_ANCHORED_HOST_PATTERNS: dict = {}+++def _anchored_host_pattern(pattern: str) -> "re.Pattern":+ r"""Compile a ``host_patterns`` entry so a bare service token matches only at+ the start of a label. ``iot\.`` becomes ``(^|\.)iot\.`` — it still matches+ ``a1-ats.iot.us-east-1.amazonaws.com`` but no longer ``notiot.example``.+ Entries that already anchor themselves (``^es\.``) or begin at a dot+ (``\.s3\.``) are compiled as written."""+ compiled = _ANCHORED_HOST_PATTERNS.get(pattern)+ if compiled is None:+ anchored = pattern+ if pattern[:1].isalnum():+ anchored = r"(^|\.)" + pattern+ compiled = re.compile(anchored)+ _ANCHORED_HOST_PATTERNS[pattern] = compiled+ return compiled++def detect_service(method: str, path: str, headers: dict, query_params: dict) -> str:"""Detect which AWS service a request is targeting."""host = headers.get("host", "")@@ -1046,11 +1151,17 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->if "granite" in path_lower or "cloudwatch" in path_lower:return "monitoring"- # 5. Check host header patterns- for svc, patterns in SERVICE_PATTERNS.items():- for hp in patterns.get("host_patterns", []):- if re.search(hp, host):- return svc+ # 5. Check host header patterns — only for hosts this stack actually+ # serves. The patterns are service tokens (``iot\.``, ``logs\.``,+ # ``email\.`` ...) and a customer domain that happens to contain one+ # (``probe.iot.example.com``, ``logs.example.com``) must not be routed+ # into that service; it falls through to the default like any other+ # unclassified request. Each token is matched at a label boundary.+ if _host_served_by_stack(host):+ for svc, patterns in SERVICE_PATTERNS.items():+ for hp in patterns.get("host_patterns", []):+ if _anchored_host_pattern(hp).search(host):+ return svc# 6a. A Query-protocol call to a service we don't implement (redshift,# elasticbeanstalk, cloudsearch, sdb, importexport, ...) is a POST to thediff --git a/tests/test_router.py b/tests/test_router.pyindex 8cbe7423..9c9c95d4 100644--- a/tests/test_router.py+++ b/tests/test_router.py@@ -144,3 +144,207 @@ def test_iot_jobs_data_host_routes_before_iot(host):assert detect_service("GET", "/things/t1/jobs/$next", {"host": host}, {}) == "iot-jobs-data"+++# --- Step 5: host-header routing ------------------------------------------+#+# The ``host_patterns`` regexes are service tokens (``iot\.``, ``logs\.``,+# ``email\.`` ...). They are consulted only for hosts the stack actually+# serves, and each token has to sit at a label boundary. The expectations below+# were captured from the router *before* the guard existed, so they pin that+# AWS-shaped hosts route exactly as they always did.++# ``<token>.<suffix>`` -> service, for every ``host_patterns`` entry whose+# token can stand alone as the first label.+_TOKEN_ROUTES = {+ "account": "account", "acm": "acm", "airflow": "airflow", "aos": "opensearch",+ "apigateway": "apigateway", "appconfig": "appconfig",+ "appconfigdata": "appconfigdata", "appsync": "appsync",+ "appsync-api": "appsync-events", "appsync-realtime-api": "appsync-events",+ "athena": "athena", "autoscaling": "autoscaling", "backup": "backup",+ "batch": "batch", "bedrock": "bedrock", "bedrock-runtime": "bedrock-runtime",+ "cloudcontrolapi": "cloudcontrol", "cloudformation": "cloudformation",+ "cloudfront": "cloudfront", "cloudfront-kvs": "cloudfront-keyvaluestore",+ "cloudtrail": "cloudtrail", "codebuild": "codebuild",+ "cognito-identity": "cognito-identity", "cognito-idp": "cognito-idp",+ "config": "config", "cur": "cur", "dsql": "dsql", "dynamodb": "dynamodb",+ "ec2": "ec2", "ecr": "ecr", "ecs": "ecs", "eks": "eks",+ "elasticache": "elasticache", "elasticfilesystem": "elasticfilesystem",+ "elasticloadbalancing": "elasticloadbalancing",+ "elasticmapreduce": "elasticmapreduce", "email": "ses", "es": "opensearch",+ "events": "events", "execute-api": "apigateway", "firehose": "firehose",+ "glue": "glue", "iam": "iam", "inspector2": "inspector2", "iot": "iot",+ "kafka": "kafka", "kinesis": "kinesis", "kinesis-firehose": "firehose",+ "kms": "kms", "lambda": "lambda", "lambda-microvms": "lambda-microvms",+ "logs": "logs", "mediaconnect": "mediaconnect", "monitoring": "monitoring",+ "mq": "mq", "opensearch": "opensearch", "organizations": "organizations",+ "pipes": "pipes", "rds": "rds", "rds-data": "rds-data",+ "resource-groups": "resource-groups", "route53": "route53", "s3": "s3",+ "s3files": "s3files", "s3tables": "s3tables", "scheduler": "scheduler",+ "secretsmanager": "secretsmanager", "servicediscovery": "servicediscovery",+ "sns": "sns", "sqs": "sqs", "ssm": "ssm", "states": "states", "sts": "sts",+ "tagging": "tagging", "transfer": "transfer", "waf": "waf", "wafv2": "wafv2",+ "waf-regional": "waf-regional",+ # multi-label tokens+ "streams.dynamodb": "dynamodbstreams", "api.ecr": "ecr",+ "jobs.iot": "iot-jobs-data", "data-ats.iot": "iot-data", "data.iot": "iot-data",+ # tokens that are *not* a service by themselves — stay on the default+ "email-smtp": "s3",+}++_SERVED_SUFFIXES = (+ "eu-central-1.amazonaws.com",+ "eu-central-1.localhost.localstack.cloud",+ "localhost.localstack.cloud:4566",+ "us-east-1.localhost:4566",+ "localhost:4566", # the short form: sts.localhost:4566+)++# A two-label alias (``s3.dev``, the LocalStack-era shape) is served as well;+# only the single-label tokens fit it — ``streams.dynamodb.dev`` has three+# labels and is a customer domain like any other.+_ALIAS_SUFFIX = "dev"++# Shapes that carry a resource id or a legacy/dualstack spelling in front of+# the token, plus a few AWS hosts no pattern claims (must stay on the default).+_EXPLICIT_HOST_ROUTES = [+ ("mybucket.s3.eu-central-1.amazonaws.com", "s3"),+ ("mybucket.s3.localhost.localstack.cloud:4566", "s3"),+ ("mybucket.s3-eu-west-1.amazonaws.com", "s3"),+ ("s3-eu-west-1.amazonaws.com", "s3"),+ ("mybucket.s3-website-us-east-1.amazonaws.com", "s3"),+ ("s3-fips.us-east-1.amazonaws.com", "s3"),+ ("s3.cn-north-1.amazonaws.com.cn", "s3"),+ ("sqs.cn-north-1.amazonaws.com.cn", "sqs"),+ ("abcd1234.execute-api.eu-central-1.amazonaws.com", "apigateway"),+ ("abcd1234.execute-api.localhost:4566", "apigateway"),+ ("abcd1234.execute-api.us-east-1.localhost.localstack.cloud:4566", "apigateway"),+ ("a1b2c3-ats.iot.eu-central-1.amazonaws.com", "iot"),+ ("a1b2c3-ats.iot.us-east-1.localhost:4566", "iot"),+ ("a1b2c3.credentials.iot.eu-central-1.amazonaws.com", "iot"),+ ("a1b2c3.data-ats.iot.eu-central-1.amazonaws.com", "iot-data"),+ ("a1b2c3.data.iot.eu-central-1.amazonaws.com", "iot-data"),+ ("a1b2c3.jobs.iot.eu-central-1.amazonaws.com", "iot-jobs-data"),+ ("a1b2c3.data.jobs.iot.eu-central-1.amazonaws.com", "iot-jobs-data"),+ ("lambda-microvms.localhost:4566", "lambda-microvms"),+ ("myfn.lambda-microvms.localhost.localstack.cloud:4566", "lambda-microvms"),+ ("123456789012.dkr.ecr.eu-central-1.amazonaws.com", "ecr"),+ ("abcd1234.appsync-api.eu-central-1.amazonaws.com", "appsync-events"),+ ("abcd1234.appsync-realtime-api.eu-central-1.amazonaws.com", "appsync-events"),+ ("waf.amazonaws.com", "waf"),+ ("sts.amazonaws.com", "sts"),+ ("iam.amazonaws.com", "iam"),+ ("route53.amazonaws.com", "route53"),+ ("cloudfront.amazonaws.com", "cloudfront"),+ ("search-mydomain-abc.eu-central-1.es.amazonaws.com", "s3"),+ ("vpc-mydomain.eu-central-1.es.amazonaws.com", "s3"),+ ("mydomain.auth.eu-central-1.amazoncognito.com", "s3"),+ ("queue.amazonaws.com", "s3"),+ ("localhost:4566", "s3"),+ ("localhost", "s3"),+ ("127.0.0.1:4566", "s3"),+ ("ministack:4566", "s3"),+ ("ministack-core:4566", "s3"),+ ("", "s3"),+]+++ ("host", "expected"),+ [+ (f"{token}.{suffix}", svc)+ for token, svc in _TOKEN_ROUTES.items()+ for suffix in _SERVED_SUFFIXES+ ]+ + [+ (f"{token}.{_ALIAS_SUFFIX}", svc)+ for token, svc in _TOKEN_ROUTES.items()+ if "." not in token+ ]+ + _EXPLICIT_HOST_ROUTES,+)+def test_aws_shaped_hosts_route_as_before(host, expected):+ assert detect_service("GET", "/status", {"host": host}, {}) == expected++[email protected]("host", [+ "probe.iot.example.com",+ "logs.example.com",+ "email.corp.example",+ "status.lambda.example.com",+ "console.example.com",+ "s3.iot-example.local", # not served until the operator says so+ "iot.example.com:4566",+])+def test_foreign_hosts_are_not_routed_by_service_token(host):+ """A customer domain is never an AWS endpoint: a Host the stack does not+ serve carries no routing information, however its labels are spelled."""+ assert detect_service("GET", "/status", {"host": host}, {}) == "s3"++[email protected](("host", "expected"), [+ ("s3.ministack:4566", "s3"),+ ("iot.localhost:4566", "iot"),+ ("sqs.dev", "sqs"), # two labels: an alias, not a customer domain+ ("dynamodb.dev:4566", "dynamodb"),+ ("iot.127.0.0.1.nip.io", "s3"), # a dotted name, not an IP literal+ ("logs.ministack.internal", "s3"), # three labels, not served+])+def test_guard_boundaries(host, expected):+ assert detect_service("GET", "/status", {"host": host}, {}) == expected++[email protected]("host", [+ "probe-iot.localhost:4566", # token after a hyphen+ "notlogs.localhost:4566", # token inside a label+ "myemail.localhost.localstack.cloud",+])+def test_served_host_tokens_match_only_at_label_start(host):+ assert detect_service("GET", "/status", {"host": host}, {}) == "s3"+++def test_served_host_prefers_the_multi_label_token():+ # ``appconfig.`` used to also match ``config\.`` by substring; ordering+ # saved it. With anchored tokens the second pattern no longer fires.+ assert detect_service(+ "GET", "/status", {"host": "appconfig.us-east-1.localhost:4566"}, {}+ ) == "appconfig"++[email protected]("host", [+ "ministack",+ "ministack-core:4566",+ "127.0.0.1:4566",+ "[::1]:4566",+])+def test_stack_hosts_without_service_labels_fall_to_default(host):+ assert detect_service("GET", "/status", {"host": host}, {}) == "s3"+++def test_extra_host_suffixes_env_opens_pattern_routing(monkeypatch):+ monkeypatch.delenv("MINISTACK_EXTRA_HOST_SUFFIXES", raising=False)+ assert detect_service("GET", "/status", {"host": "s3.iot-example.local"}, {}) == "s3"+ assert detect_service("GET", "/status", {"host": "iot.iot-example.local"}, {}) == "s3"++ monkeypatch.setenv("MINISTACK_EXTRA_HOST_SUFFIXES", "corp.example, iot-example.local")+ assert detect_service("GET", "/status", {"host": "iot.iot-example.local"}, {}) == "iot"+ assert detect_service(+ "GET", "/status", {"host": "a1-ats.iot.eu-central-1.iot-example.local:4566"}, {}+ ) == "iot"+ assert detect_service("GET", "/status", {"host": "logs.corp.example"}, {}) == "logs"+ # label boundary: ``notiot-example.local`` is not under ``iot-example.local``+ assert detect_service("GET", "/status", {"host": "iot.notiot-example.local"}, {}) == "s3"+++def test_ministack_host_env_is_a_served_suffix(monkeypatch):+ monkeypatch.setenv("MINISTACK_HOST", "aws.dev.example")+ assert detect_service("GET", "/status", {"host": "sqs.aws.dev.example:4566"}, {}) == "sqs"+ assert detect_service(+ "GET", "/status", {"host": "abcd1234.execute-api.aws.dev.example"}, {}+ ) == "apigateway"+ assert detect_service("GET", "/status", {"host": "sqs.other.example"}, {}) == "s3"+++def test_container_hostname_is_a_served_suffix(monkeypatch):+ monkeypatch.setenv("HOSTNAME", "core-7f3a")+ assert detect_service("GET", "/status", {"host": "sns.core-7f3a:4566"}, {}) == "sns"