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(apigateway): v1 Lambda-proxy binary body support via binaryMediaTypes (#767)
rmlassetera1609d3220e0
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.pyindex 2d2bc891..a451ccfd 100644--- a/ministack/services/apigateway_v1.py+++ b/ministack/services/apigateway_v1.py@@ -896,7 +896,8 @@ async def handle_execute(api_id, stage_name, method, path, headers, body, query_if int_type in ("AWS_PROXY", "AWS"):return await _invoke_lambda_proxy_v1(integration, api_id, stage_name, stage, resource, path, method,- headers, body, query_params, path_params+ headers, body, query_params, path_params,+ binary_media_types=api.get("binaryMediaTypes") or [],)elif int_type in ("HTTP_PROXY", "HTTP"):return await _invoke_http_proxy_v1(@@ -908,7 +909,26 @@ async def handle_execute(api_id, stage_name, method, path, headers, body, query_return 500, {"Content-Type": "application/json"}, json.dumps({"message": f"Unsupported integration type: {int_type}"}).encode()-async def _invoke_lambda_proxy_v1(integration, api_id, stage_name, stage, resource, request_path, method, headers, body, query_params, path_params):+def _media_type_matches(media_type, binary_media_types):+ """Whether a request media type matches any configured ``binaryMediaTypes``.++ Configured patterns may use wildcards (``*/*``, ``type/*``); the request+ value is matched literally against them. A request value of ``*/*`` therefore+ does NOT match a specific configured type — verified against real AWS.+ """+ mt = (media_type or "").split(";", 1)[0].strip().lower()+ if not mt:+ return False+ for pat in binary_media_types or []:+ pat = pat.strip().lower()+ if pat == mt or pat == "*/*":+ return True+ if pat.endswith("/*") and "/" in mt and mt.split("/", 1)[0] == pat[:-2]:+ return True+ return False+++async def _invoke_lambda_proxy_v1(integration, api_id, stage_name, stage, resource, request_path, method, headers, body, query_params, path_params, binary_media_types=None):"""Invoke Lambda with API Gateway v1 payload format 1.0."""uri = integration.get("uri", "")# Supported URI formats:@@ -935,6 +955,17 @@ async def _invoke_lambda_proxy_v1(integration, api_id, stage_name, stage, resourrequest_time = datetime.datetime.utcnow().strftime("%d/%b/%Y:%H:%M:%S +0000")request_id = new_uuid()+ # A request body whose Content-Type matches a configured binaryMediaType is+ # delivered base64-encoded with isBase64Encoded=true; otherwise as a UTF-8+ # string. Verified against real AWS.+ if body:+ if _media_type_matches(headers.get("content-type"), binary_media_types):+ req_body, req_is_base64 = base64.b64encode(body).decode("ascii"), True+ else:+ req_body, req_is_base64 = body.decode("utf-8", errors="replace"), False+ else:+ req_body, req_is_base64 = None, False+event = {"version": "1.0","resource": resource["path"],@@ -966,8 +997,8 @@ async def _invoke_lambda_proxy_v1(integration, api_id, stage_name, stage, resour"httpMethod": method,"apiId": api_id,},- "body": body.decode("utf-8", errors="replace") if body else None,- "isBase64Encoded": False,+ "body": req_body,+ "isBase64Encoded": req_is_base64,}lambda_response, err = await _call_lambda(func_name, event, qualifier=qualifier)@@ -1004,7 +1035,13 @@ async def _invoke_lambda_proxy_v1(integration, api_id, stage_name, stage, resourdel resp_headers[existing]resp_headers[k] = list(v)resp_body = lambda_response.get("body", "")- if isinstance(resp_body, str):+ # A base64 response body (isBase64Encoded) is decoded to raw bytes only when+ # the request Accept matches a configured binaryMediaType; otherwise the+ # base64 string is passed through as text. Verified against real AWS.+ if (lambda_response.get("isBase64Encoded") and isinstance(resp_body, str)+ and _media_type_matches(headers.get("accept"), binary_media_types)):+ resp_body = base64.b64decode(resp_body)+ elif isinstance(resp_body, str):resp_body = resp_body.encode("utf-8")elif isinstance(resp_body, dict):resp_body = json.dumps(resp_body, ensure_ascii=False).encode("utf-8")diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.pyindex 9a21868a..f8eca41e 100644--- a/tests/test_apigatewayv1.py+++ b/tests/test_apigatewayv1.py@@ -701,6 +701,96 @@ def test_apigwv1_execute_lambda_proxy_header_case_override(apigw_v1, lam):lam.delete_function(FunctionName=fname)+def test_apigwv1_execute_lambda_proxy_binary_media_types(apigw_v1, lam):+ """REST API (v1) binary support keyed off `binaryMediaTypes`.++ Verified against real AWS: a request body whose Content-Type matches a+ configured binaryMediaType is delivered base64 (isBase64Encoded=true); a+ base64 response body is decoded only when the request Accept also matches.+ """+ import base64 as _b64+ import hashlib+ import json as _json+ import urllib.request as _urlreq+ import uuid as _uuid++ fname = f"intg-v1-binmedia-{_uuid.uuid4().hex[:8]}"+ code = (+ b"import json, base64, hashlib\n"+ b"def handler(event, context):\n"+ b" qs = event.get('queryStringParameters') or {}\n"+ b" if qs.get('mode') == 'resp':\n"+ b" return {'statusCode': 200, 'isBase64Encoded': True,\n"+ b" 'headers': {'Content-Type': 'application/octet-stream'},\n"+ b" 'body': base64.b64encode(bytes(range(8))).decode('ascii')}\n"+ b" b = event.get('body'); isb = bool(event.get('isBase64Encoded'))\n"+ b" if b is None: raw = b''\n"+ b" elif isb: raw = base64.b64decode(b)\n"+ b" else: raw = b.encode('utf-8', 'surrogateescape')\n"+ b" return {'statusCode': 200, 'headers': {'Content-Type': 'application/json'},\n"+ b" 'body': json.dumps({'isB64': isb, 'sha': hashlib.sha256(raw).hexdigest()})}\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_v1.create_rest_api(+ name=f"v1-binmedia-{fname}", binaryMediaTypes=["application/octet-stream"],+ )["id"]+ root = next(r for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")+ resource_id = apigw_v1.create_resource(+ restApiId=api_id, parentId=root["id"], pathPart="echo",+ )["id"]+ apigw_v1.put_method(+ restApiId=api_id, resourceId=resource_id, httpMethod="ANY", authorizationType="NONE",+ )+ apigw_v1.put_integration(+ restApiId=api_id, resourceId=resource_id, httpMethod="ANY",+ type="AWS_PROXY", integrationHttpMethod="POST",+ uri=f"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:{fname}/invocations",+ )+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]+ apigw_v1.create_stage(restApiId=api_id, stageName="test", deploymentId=dep_id)++ base = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/test/echo"+ host = f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"++ # Request: Content-Type matches binaryMediaTypes -> base64-encoded body.+ payload = bytes(range(256))+ req = _urlreq.Request(base, data=payload, method="POST")+ req.add_header("Host", host)+ req.add_header("Content-Type", "application/octet-stream")+ got = _json.loads(_urlreq.urlopen(req).read())+ assert got["isB64"] is True+ assert got["sha"] == hashlib.sha256(payload).hexdigest()++ # Request: Content-Type does NOT match -> UTF-8 string.+ req2 = _urlreq.Request(base, data=b'{"x":1}', method="POST")+ req2.add_header("Host", host)+ req2.add_header("Content-Type", "application/json")+ assert _json.loads(_urlreq.urlopen(req2).read())["isB64"] is False++ # Response: Accept matches binaryMediaTypes -> base64 decoded to raw bytes.+ req3 = _urlreq.Request(base + "?mode=resp", method="GET")+ req3.add_header("Host", host)+ req3.add_header("Accept", "application/octet-stream")+ assert _urlreq.urlopen(req3).read() == bytes(range(8))++ # Response: Accept does NOT match -> literal base64 string passed through.+ req4 = _urlreq.Request(base + "?mode=resp", method="GET")+ req4.add_header("Host", host)+ req4.add_header("Accept", "application/json")+ assert _urlreq.urlopen(req4).read() == _b64.b64encode(bytes(range(8)))++ apigw_v1.delete_rest_api(restApiId=api_id)+ lam.delete_function(FunctionName=fname)++@pytest.mark.skipif(not shutil.which("curl"), reason="provided bootstrap uses curl for Runtime API")def test_apigwv1_execute_lambda_proxy_provided_runtime(apigw_v1, lam):"""execute-api AWS_PROXY must run provided.* zips via lambda_svc (Go/terraform parity)."""