Skip to content

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

fix(apigatewayv2): the request path keeps a %25 escape (#1920)

Jeff Heller662a52dc3fbd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a6e19e7e..d7f25a4f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **CloudFormation — `AWS::Lambda::Version` updates `FunctionScalingConfig` in place** — a stack update re-ran the create, which published a new version for every change; a `FunctionScalingConfig` change now keeps the version, also when the update rolls back. Contributed by @iot-rocket.
### Fixed
+- **API Gateway v2 (HTTP API) — the request path keeps a `%25` escape** — the path was the server's full percent-decode, which also turns `%25` into `%`, so `/items/a%252Eb` reached the Lambda's `rawPath` as `/items/a%2Eb`. Observed on a deployed HTTP API in us-east-1, reached through CloudFront: the Lambda's `rawPath` is `/items/a%252Eb`, while other escapes such as `%2E` are decoded (`a%2Eb` arrives as `a.b`). The HTTP API path now keeps `%25` and decodes the rest as before; `rawPath`, `requestContext.http.path`, `pathParameters` and route matching all use it, so they still agree with each other. REST APIs are unchanged.
- **Step Functions — JSONPath Choice rules read execution context** — `Variable` and supported variable-to-variable comparison paths now resolve `$$.` against the context object, including inside `And`, `Or`, and `Not`. A Choice can check the original execution input after earlier states replace the current input.
- **CloudFormation — `AWS::EC2::VPCGatewayAttachment` updates in place** — a changed `InternetGatewayId` or `VpnGatewayId` moves the attachment under the same `IGW|vpc-…` / `VGW|vpc-…` physical id, `VpnGatewayId` is attached at all, and a `VpcId` change leaves the gateway attached to the new VPC, or to the old one when the update rolls back.
diff --git a/ministack/app.py b/ministack/app.py
index fff334fc..75eb8160 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -1733,7 +1733,8 @@ def _resolve_custom_domain_request(host: str, path: str):
async def _handle_execute_api_request(
- host: str, path: str, method: str, headers: dict, body: bytes, query_params: dict
+ host: str, path: str, method: str, headers: dict, body: bytes, query_params: dict,
+ raw_path: str | None = None,
):
"""Handle API Gateway execute-api data plane requests (Host-based,
path-based, and registered custom domains)."""
@@ -1796,6 +1797,13 @@ async def _handle_execute_api_request(
apigw_v2 = _get_module("apigateway")
if apigw_v2.find_api_scope(api_id) is None:
return 404, {"Content-Type": "application/json"}, json.dumps({"message": "Not Found"}).encode()
+ if raw_path is not None and path.endswith(execute_path):
+ # `path` is the server's full decode, which also turns %25 into "%";
+ # an HTTP API keeps that one escape in rawPath.
+ prefix = path[: len(path) - len(execute_path)]
+ http_api_path = apigw_v2.decode_http_api_path(raw_path)
+ if http_api_path.startswith(prefix):
+ execute_path = http_api_path[len(prefix):]
return await apigw_v2.handle_execute(api_id, stage, execute_path, method, headers, body, query_params)
except Exception as e:
logger.exception("Error in execute-api dispatch: %s", e)
@@ -2113,6 +2121,7 @@ async def _handle_special_data_plane_request(
body: bytes,
query_params: dict,
request_id: str,
+ raw_path: str | None = None,
):
"""Handle special-case service entrypoints before the generic router."""
# Iceberg REST catalog — /iceberg/* is served by two catalogs that share the
@@ -2147,7 +2156,9 @@ async def _handle_special_data_plane_request(
return _with_data_plane_headers(response, request_id)
host = headers.get("host", "")
- if response := await _handle_execute_api_request(host, path, method, headers, body, query_params):
+ if response := await _handle_execute_api_request(
+ host, path, method, headers, body, query_params, raw_path=raw_path
+ ):
return _with_data_plane_headers(response, request_id, wildcard_cors=False)
if response := await _handle_lambda_url_request(host, path, method, headers, body, query_params):
return _with_data_plane_headers(response, request_id, wildcard_cors=False)
@@ -2713,7 +2724,10 @@ async def app(scope, receive, send):
if await _send_if_handled(
send,
- await _handle_special_data_plane_request(method, path, headers, body, query_params, request_id),
+ await _handle_special_data_plane_request(
+ method, path, headers, body, query_params, request_id,
+ raw_path=scope["raw_path"].decode("ascii") if scope.get("raw_path") else None,
+ ),
receive,
):
return
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index 15b5fe2d..28459bcb 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -68,6 +68,30 @@ _PORT = os.environ.get("GATEWAY_PORT", "4566")
logger = logging.getLogger("apigateway")
+_PCT_RUN_RE = re.compile(r"(?:%[0-9A-Fa-f]{2})+")
+
+
+def decode_http_api_path(raw_path: str) -> str:
+ """Decode a request path the way an HTTP API builds ``rawPath``: every escape
+ decodes except ``%25``, so ``a%252Eb`` arrives as ``a%252Eb``, not ``a%2Eb``."""
+
+ def _decode(match):
+ run, out, pending = match.group(0), [], bytearray()
+ for i in range(0, len(run), 3):
+ byte = int(run[i + 1 : i + 3], 16)
+ if byte == 0x25:
+ if pending:
+ out.append(pending.decode("utf-8", "replace"))
+ pending.clear()
+ out.append("%25")
+ else:
+ pending.append(byte)
+ if pending:
+ out.append(pending.decode("utf-8", "replace"))
+ return "".join(out)
+
+ return _PCT_RUN_RE.sub(_decode, raw_path)
+
def _timeout_from_env(env_name: str, default_seconds: float) -> float:
"""Read a positive float timeout from an env var; fall back on missing /
diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.py
index 3a708eec..732181dd 100644
--- a/tests/test_apigatewayv2.py
+++ b/tests/test_apigatewayv2.py
@@ -1369,6 +1369,47 @@ def test_apigw_raw_query_string_percent_encoded(apigw, lam):
lam.delete_function(FunctionName=fname)
+def test_apigw_raw_path_keeps_percent25_escape(apigw, lam):
+ """rawPath decodes escapes but never %25, so a%252Eb is not turned into a%2Eb."""
+ import urllib.request as _urlreq
+ import uuid as _uuid
+
+ fname = f"intg-rawpath-{_uuid.uuid4().hex[:8]}"
+ code = (
+ "import json\n"
+ "def handler(event, context):\n"
+ " return {'statusCode': 200, 'body': json.dumps({'rawPath': event.get('rawPath')})}\n"
+ )
+ lam.create_function(
+ FunctionName=fname, Runtime="python3.12", Role=_LAMBDA_ROLE,
+ Handler="index.handler", Code={"ZipFile": _make_zip(code)},
+ )
+ api_id = apigw.create_api(Name=f"rawpath-api-{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="GET /items/{proxy+}", Target=f"integrations/{int_id}")
+ apigw.create_stage(ApiId=api_id, StageName="$default")
+ host = f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"
+
+ def raw_path(segment):
+ req = _urlreq.Request(f"http://{host}/$default/items/{segment}", method="GET")
+ req.add_header("Host", host)
+ return json.loads(_urlreq.urlopen(req).read())["rawPath"]
+
+ try:
+ assert raw_path("a%252Eb") == "/items/a%252Eb"
+ assert raw_path("a%2Eb") == "/items/a.b"
+ req = _urlreq.Request(f"http://{host}/items/a%252Eb", method="GET")
+ req.add_header("Host", host)
+ assert json.loads(_urlreq.urlopen(req).read())["rawPath"] == "/items/a%252Eb"
+ finally:
+ apigw.delete_api(ApiId=api_id)
+ lam.delete_function(FunctionName=fname)
+
+
def test_apigw_multiple_path_parameters(apigw, lam):
"""Multiple path parameters in one route should all be extracted."""
import urllib.request as _urlreq