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(apigatewayv2): a doubled leading slash still selects the route (#1917)
Jeff Heller9e9d2c680c09
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6f1cd3d8..a0c000e2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **CloudFormation — `AWS::ServiceDiscovery::HttpNamespace`, `PrivateDnsNamespace`, `PublicDnsNamespace`, `Service` and `Instance`** — a template declaring any of them, as the CDK ECS constructs do for Cloud Map, failed validation with `Unrecognized resource types`. They now create, update and delete through the Cloud Map service, so a DNS namespace from a stack gets its Route 53 hosted zone. `Ref` and `Fn::GetAtt` return the values in the CloudFormation reference; Description, the SOA TTL, a service's `DnsConfig`, `HealthCheckConfig` and `ServiceAttributes`, and instance attributes change in place, while the properties the reference marks as replacing (including `HealthCheckCustomConfig`) replace the resource. Two Cloud Map API changes come with this: namespaces store and update `Properties.DnsProperties.SOA.TTL`, and `DeleteNamespace` removes the namespace's hosted zone, as on AWS. Contributed by @fabio-andre-rodrigues.### Fixed+- **API Gateway v2 — a doubled leading slash still selects the route** — an HTTP API request to `//items/abc` matched no route and got the gateway's `404 {"message":"Not Found"}`. On AWS such a request selects the route: observed on a deployed HTTP API in us-east-1 (its default `execute-api` endpoint) with only `ANY /<prefix>/{proxy+}` routes and no `$default` or `ANY /{proxy+}`, where `//<prefix>/<id>` reached the prefix route's Lambda. Route selection and `pathParameters` now ignore the extra leading slashes; `rawPath` is left as received (not verified against AWS).- **IAM — customer-managed permissions use the explicit account** — policy evaluation now resolves the complete policy ARN in the principal's account, so a different ambient request account cannot hide that policy or supply a foreign account's document. Permissions continue to follow the policy's current default version.- **ECS — optional task-definition fields stay omitted** — registering an EC2 task definition without task-level `cpu`, `memory`, or `requiresCompatibilities` no longer invents `256`, `512`, or `["EC2"]` in register, describe, and deregister responses. Explicitly supplied values remain in the definition.diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.pyindex 12c10000..15b5fe2d 100644--- a/ministack/services/apigateway.py+++ b/ministack/services/apigateway.py@@ -1299,7 +1299,9 @@ async def _handle_execute_in_scope(if stage not in api_stages and stage != "$default":return 404, {"Content-Type": "application/json"}, json.dumps({"message": f"Stage '{stage}' not found"}).encode()- route = _match_route(api_id, method, path)+ # AWS selects the route of a path with extra leading slashes as if it had one.+ route_path_in = "/" + path.lstrip("/")+ route = _match_route(api_id, method, route_path_in)if not route:# AWS's body for an unmatched HTTP API route: compact JSON.return (@@ -1314,7 +1316,7 @@ async def _handle_execute_in_scope(rk_parts = route_key.split(" ", 1)if len(rk_parts) == 2:route_path = rk_parts[1]- path_params = _extract_path_params(route_path, path) if route_path else {}+ path_params = _extract_path_params(route_path, route_path_in) if route_path else {}stage_vars = _get_stage_variables(api_id, stage)auth_type = (route.get("authorizationType") or "NONE").upper()diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.pyindex 7b3bbf4b..3a708eec 100644--- a/tests/test_apigatewayv2.py+++ b/tests/test_apigatewayv2.py@@ -1105,6 +1105,44 @@ def test_apigw_path_param_route(apigw, lam):apigw.delete_api(ApiId=api_id)lam.delete_function(FunctionName=fname)+def test_apigw_execute_leading_double_slash_selects_route(apigw, lam):+ """A doubled leading slash still selects the route, as on AWS."""+ import urllib.request as _urlreq+ import uuid as _uuid++ fname = f"intg-dbl-slash-{_uuid.uuid4().hex[:8]}"+ code = (+ b"import json\n"+ b"def handler(event, context):\n"+ b" return {'statusCode': 200, 'body': json.dumps(event.get('pathParameters'))}\n"+ )+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ lam.create_function(+ FunctionName=fname,+ Runtime="python3.12",+ Role="arn:aws:iam::000000000000:role/test-role",+ Handler="index.handler",+ Code={"ZipFile": buf.getvalue()},+ )+ api_id = apigw.create_api(Name=f"dbl-slash-{fname}", ProtocolType="HTTP")["ApiId"]+ int_id = apigw.create_integration(+ ApiId=api_id,+ IntegrationType="AWS_PROXY",+ IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{fname}",+ PayloadFormatVersion="2.0",+ )["IntegrationId"]+ apigw.create_route(ApiId=api_id, RouteKey="ANY /items/{proxy+}", Target=f"integrations/{int_id}")+ apigw.create_stage(ApiId=api_id, StageName="$default")++ resp = _urlreq.urlopen(f"http://localhost:{_EXECUTE_PORT}/_aws/execute-api/{api_id}/$default//items/abc123")+ assert resp.status == 200+ assert json.loads(resp.read()) == {"proxy": "abc123"}++ apigw.delete_api(ApiId=api_id)+ lam.delete_function(FunctionName=fname)+def test_apigw_path_parameters_in_event(apigw, lam):"""API Gateway v2 should populate pathParameters in the Lambda event."""import urllib.request as _urlreq