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(apigw): three WebSocket API issues (#2385)
Nahuel Nucera946773aef96e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1807edc9..e4242175 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **IoT — thing-group membership authorized on the group and the thing** — with `AUTH=true`, `AddThingToThingGroup` and `RemoveThingFromThingGroup` were authorized on `thinggroup/addThingToThingGroup` (the request path), so a policy granting exactly the thing group and the thing was denied; both calls are now checked on the thing group and then the thing named in the body (by name or ARN), and a denial names the resource that failed. Contributed by @iot-rocket.- **API Gateway — `AWS_IAM` methods refuse an `Authorization` header that is not SigV4** — under `AUTH=true` a REST API method with `AWS_IAM` authorization served a bearer token or an algorithm in lower case, and answered the SigV4a algorithm name without a signed `x-amz-region-set` or an unknown `AWS4-` algorithm with `UnrecognizedClientException`; it now answers 403 `IncompleteSignatureException` with API Gateway's message for each, while a method without `AWS_IAM` still serves such calls. Contributed by @iot-rocket.- **S3 — access point policies and unsigned requests** — an access point policy was stored but never applied, and an unsigned request through an access point was served. With `AUTH=true` a request through an access point alias or ARN is allowed on the access point by an identity policy or the access point policy (a Deny in either refuses it), and an unsigned one gets 400 `InvalidRequest`; S3 Control calls on the access point are unaffected. Contributed by @iot-rocket.+- **API Gateway v2 — WebSocket connections, image functions and dropped fields** — `DeleteConnection` answered 204 but left the socket open; it now sends the client a close frame, `GetConnection` and `PostToConnection` answer 410 `GoneException`, and `$disconnect` runs after the close. A WebSocket route whose Lambda is a container image or a runtime other than Python or Node.js answered an empty 200 without running it; the function now runs. Routes keep `RouteResponseSelectionExpression` and `ModelSelectionExpression`, and stages keep `AccessLogSettings`, `ClientCertificateId` and `DeploymentId`, also from CloudFormation. Reported by @cupidchan.- **Lambda — layers from other accounts that MiniStack doesn't hold** — a function attaching a third-party public layer, such as Datadog's `arn:aws:lambda:<region>:464622532012:layer:Datadog-Extension-ARM:<n>`, was refused with `AccessDeniedException`, where AWS attaches it. A layer version from another account that MiniStack does not hold now resolves as an empty layer with a warning in the log: `CreateFunction` and `UpdateFunctionConfiguration` attach it as `Arn` and `CodeSize` 0, `GetLayerVersionByArn` and `GetLayerVersion` by ARN return `LayerArn`, `LayerVersionArn`, `Version` and `Content.CodeSize` 0, and the layer does not run, even if a version is published under that ARN later. This replaces the name list for AWS-published extensions. A made-up ARN looks like a real one offline, so any 12-digit account, layer name and version that could exist on AWS resolve, where AWS answers `AccessDeniedException` for one that does not exist. A version of 0, a version with a leading zero and a name longer than 140 characters can't exist, and `CreateFunction`, `UpdateFunctionConfiguration` and `GetLayerVersionByArn` refuse them with that `AccessDeniedException`, as on AWS. A layer MiniStack holds still needs its grant, so a version it does not hold or grant is refused, and a layer from another region is still refused. `GetLayerVersion` now refuses a `LayerName` longer than 140 characters, a layer ARN included, with AWS's `ValidationException` before checking the version; `GetLayerVersionByArn` has no such limit, as on AWS. Contributed by @kharabasz.- **CloudFront — `CreateFunction` tags** — the request's `Tags` were dropped, so `ListTagsForResource` on the new function's ARN was empty and Terraform re-planned `tags_all` on `aws_cloudfront_function`; they are now stored, a tag without `Value` is listed with an empty one, a refused create stores none, and `DeleteFunction` removes them so a function created again under the same name starts without them. `CreateFunction` and `UpdateFunction` answer invalid base64 code with `MalformedInput` "Invalid Base64 encoding", and `CreateFunction` now refuses what AWS refuses, before the name lookup: a missing or empty `FunctionCode`, a missing `FunctionConfig` or `Runtime`, an unknown runtime, a missing or empty `Name`, and a tag key that is missing, empty, over 128 characters or outside letters, numbers, spaces and `_ . : / = + - @` (values over 256 characters or outside the same set), listed together (at most ten) in one `MalformedXML`; and after it, `InvalidTagging` for a repeated key, an `aws:` key or more than 50 tags. Contributed by @kharabasz.- **CloudWatch — `PutMetricAlarm` and `PutCompositeAlarm` tags on create** — `Tags` were dropped when either call created an alarm, so Terraform re-planned `tags_all` on `aws_cloudwatch_metric_alarm` and `aws_cloudwatch_composite_alarm`; they are now stored over CBOR, JSON 1.0 and Query, keeping empty values and the last value of a repeated key, and they are still ignored when the call updates an existing alarm, as on AWS (use `TagResource` / `UntagResource`). Both calls now refuse what AWS refuses, before anything is stored (`PutCompositeAlarm` before its `AlarmRule` checks): a wrong JSON type in `Tags` (`MalformedInput`), a missing or empty `Key`, a missing `Value`, a key over 128 or a value over 256 characters, or a `DatapointsToAlarm` below 1, listed together (at most ten) in one `ValidationError`, on create a key or value with characters outside letters, numbers, spaces and `_ . : / = + - @` or too long in UTF-16 units, an `aws:` key on create (`PutMetricAlarm` 403 `AccessDenied`, `PutCompositeAlarm` `ValidationError` "Invalid System Tag"), and more than 50 tags on create. Query error messages are now XML-escaped. Contributed by @kharabasz.diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.pyindex 9b5be9e7..1c7422de 100644--- a/ministack/services/apigateway.py+++ b/ministack/services/apigateway.py@@ -1988,6 +1988,10 @@ def _ws_route_authorization_error(api_id, route_key, authorization_type):return _apigw_error("BadRequestException", message, 400) if message else None+_ROUTE_SELECTION_EXPRESSIONS = ("modelSelectionExpression", "routeResponseSelectionExpression")+_STAGE_OPTIONAL_FIELDS = ("accessLogSettings", "clientCertificateId", "deploymentId")++def _create_route(api_id, data):if api_id not in _apis:return _api_not_found(api_id)@@ -2010,6 +2014,9 @@ def _create_route(api_id, data):route["requestModels"] = data["requestModels"]if data.get("requestParameters"):route["requestParameters"] = data["requestParameters"]+ for k in _ROUTE_SELECTION_EXPRESSIONS:+ if data.get(k):+ route[k] = data[k]_routes.setdefault(api_id, {})[route_id] = routereturn _apigw_response(route, 201)@@ -2063,7 +2070,7 @@ def _update_route(api_id, route_id, data):route.pop("authorizationScopes", None)else:route[k] = v- for rk in ("requestModels", "requestParameters"):+ for rk in ("requestModels", "requestParameters", *_ROUTE_SELECTION_EXPRESSIONS):if rk not in data:continuev = data.get(rk)@@ -2181,6 +2188,7 @@ def _create_stage(api_id, data):"routeSettings": data.get("routeSettings", {}),"tags": data.get("tags", {}),}+ stage.update({k: data[k] for k in _STAGE_OPTIONAL_FIELDS if data.get(k)})_stages.setdefault(api_id, {})[stage_name] = stageif data.get("tags"):_api_tags[_api_resource_arn(api_id, "stages", stage_name)] = dict(data.get("tags", {}))@@ -2212,6 +2220,13 @@ def _update_stage(api_id, stage_name, data):"defaultRouteSettings", "routeSettings"):if k in data:stage[k] = data[k]+ for k in _STAGE_OPTIONAL_FIELDS:+ if k not in data:+ continue+ if data[k]:+ stage[k] = data[k]+ else:+ stage.pop(k, None)stage["lastUpdatedDate"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())return _apigw_response(stage)@@ -3050,8 +3065,11 @@ async def _invoke_ws_lambda(api_id: str, account_id: str, region: str, route: diif result.get("status") == "error":return {"statusCode": 500, "body": result.get("error", "")}return result.get("result", {})- # Image/unsupported runtime stub — success without body.- return {"statusCode": 200, "body": ""}+ # Image and other runtimes run through the central dispatcher, as HTTP API routes do.+ exec_record = lambda_svc._execution_record_for_config(func_data, func_config)+ result = await run_reentrant(lambda_svc._execute_function_with_config_scope, exec_record, event,+ thread_name="ministack-apigw-ws-invoke")+ return lambda_svc.lambda_execute_result_to_api_proxy_response(result)[0]_WS_DENY_REASONS = {@@ -3276,9 +3294,16 @@ async def handle_websocket(scope, receive, send, api_id: str, path_override: strdisconnect_code = 1005 # 1005 = "no status rcvd" per RFC 6455, matches AWS defaultdisconnect_reason = ""+ # DeleteConnection sets close_event; the server then closes the socket.+ closed_by_delete = asyncio.ensure_future(close_event.wait())try:while True:- message = await receive()+ receiving = asyncio.ensure_future(receive())+ await asyncio.wait({receiving, closed_by_delete}, return_when=asyncio.FIRST_COMPLETED)+ if not receiving.done():+ receiving.cancel()+ break+ message = receiving.result()mtype = message.get("type")if mtype == "websocket.disconnect":disconnect_code = int(message.get("code", 1005) or 1005)@@ -3317,12 +3342,17 @@ async def handle_websocket(scope, receive, send, api_id: str, path_override: strawait send({"type": "websocket.send", "text": str(body)})finally:close_event.set()+ closed_by_delete.cancel()try:await drain_taskexcept Exception:pass_ws_connections.pop(connection_id, None)- # Fire $disconnect route best-effort.+ # "The $disconnect route is executed after the connection is closed."+ try:+ await send({"type": "websocket.close", "code": 1000})+ except Exception:+ passdisconnect_route = _match_ws_route(api_id, "$disconnect")if disconnect_route is not None:try:@@ -3335,10 +3365,6 @@ async def handle_websocket(scope, receive, send, api_id: str, path_override: str)except Exception:logger.exception("error firing $disconnect")- try:- await send({"type": "websocket.close", "code": 1000})- except Exception:- passfinally:try:_request_region.reset(region_token)@@ -3367,7 +3393,7 @@ async def handle_connections_api(method: str, api_id: str, stage: str,"""conn = _ws_connections.get(connection_id)if not conn or conn.get("apiId") != api_id:- return 410, {"Content-Type": "application/json"}, json.dumps(+ return 410, {"Content-Type": "application/json", "x-amzn-ErrorType": "GoneException"}, json.dumps({"message": "GoneException"}).encode()@@ -3391,6 +3417,7 @@ async def handle_connections_api(method: str, api_id: str, stage: str,return 200, {"Content-Type": "application/json"}, json.dumps(payload).encode()if method == "DELETE":+ _ws_connections.pop(connection_id, None)ev = conn.get("close_event")if ev is not None:try:diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 22e6f1ff..d4f5e2ec 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -10837,9 +10837,19 @@ def _apigw_v2_stage_props(props):"description": props.get("Description", ""),"defaultRouteSettings": props.get("DefaultRouteSettings", {}),"routeSettings": props.get("RouteSettings", {}),+ "accessLogSettings": _apigw_v2_access_log_settings(props.get("AccessLogSettings")),+ "clientCertificateId": props.get("ClientCertificateId"),+ "deploymentId": props.get("DeploymentId"),}+def _apigw_v2_access_log_settings(settings):+ if not settings:+ return None+ return {k: settings[key] for k, key in (("destinationArn", "DestinationArn"), ("format", "Format"))+ if settings.get(key)}++def _apigw_v2_stage_create(logical_id, props, stack_name):api_id = props.get("ApiId", "")stage_name = props.get("StageName", "$default")@@ -11064,6 +11074,8 @@ def _apigw_v2_route_props(props):"operationName": props.get("OperationName", ""),"requestModels": props.get("RequestModels", {}),"requestParameters": props.get("RequestParameters", {}),+ "modelSelectionExpression": props.get("ModelSelectionExpression"),+ "routeResponseSelectionExpression": props.get("RouteResponseSelectionExpression"),}diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.pyindex 15704269..1c79cc5d 100644--- a/tests/test_apigatewayv2.py+++ b/tests/test_apigatewayv2.py@@ -2898,31 +2898,57 @@ def test_ws_get_connection_returns_metadata(apigw, lam):ws.close()-def test_ws_delete_connection_closes_socket(apigw, lam):- """@connections DeleteConnection terminates the WS session."""+def test_ws_delete_connection_closes_socket(apigw, lam, sqs):+ """DeleteConnection sends the client a close frame, forgets the connection and runs $disconnect."""+ import urllib.errorimport urllib.request- api_id, _ = _wire_ws_api(apigw, lam, name_suffix="delc")- ws = _WSClient("localhost", _EXECUTE_PORT, "/prod",- headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"})+ qname = _v2_auth_counter_queue(sqs)+ disconnect = (_V2_AUTH_MARK_PRELUDE + (+ f"def handler(event, context):\n _mark('{qname}')\n return {{'statusCode': 200}}\n").encode()).decode()+ api_id, _ = _wire_ws_api(apigw, lam, name_suffix="delc", disconnect_code=disconnect)+ host = f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"+ warmed = _v2_auth_count(sqs, qname) # _make_fn's warm-up call+ ws = _WSClient("localhost", _EXECUTE_PORT, "/prod", headers={"Host": host})try:ws.send(json.dumps({"action": "x"}))- reply = ws.recv()- conn_id = json.loads(reply)["connectionId"]-- url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/prod/@connections/{conn_id}"- req = urllib.request.Request(- url, method="DELETE",- headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"},- )- r = urllib.request.urlopen(req, timeout=30)- assert r.status in (200, 204)+ conn_id = json.loads(ws.recv())["connectionId"]+ url = f"http://{host}/prod/@connections/{conn_id}"+ r = urllib.request.urlopen(urllib.request.Request(url, method="DELETE", headers={"Host": host}), timeout=30)+ assert r.status == 204- # Give the server a moment to close, then subsequent recv returns None.- time.sleep(0.5)- assert ws.recv(timeout=1.5) is None+ ws._sock.settimeout(5)+ assert ws._recv_frame()[0] == 0x8+ with pytest.raises(urllib.error.HTTPError) as exc_info:+ urllib.request.urlopen(urllib.request.Request(url, method="GET", headers={"Host": host}), timeout=30)+ assert exc_info.value.code == 410+ assert exc_info.value.headers["x-amzn-ErrorType"] == "GoneException"+ deadline = time.time() + 30+ while _v2_auth_count(sqs, qname) < warmed + 1 and time.time() < deadline:+ time.sleep(0.5)+ assert _v2_auth_count(sqs, qname) == warmed + 1finally:ws.close()+ _v2_auth_delete_queue(sqs, qname)+++def test_ws_route_and_stage_keep_their_optional_fields(apigw):+ api_id = apigw.create_api(Name="ws-fields", ProtocolType="WEBSOCKET")["ApiId"]+ route = apigw.create_route(ApiId=api_id, RouteKey="send", RouteResponseSelectionExpression="$default",+ ModelSelectionExpression="$request.body.type")+ got = apigw.get_route(ApiId=api_id, RouteId=route["RouteId"])+ for answer in (route, got):+ assert answer["RouteResponseSelectionExpression"] == "$default"+ assert answer["ModelSelectionExpression"] == "$request.body.type"+ updated = apigw.update_route(ApiId=api_id, RouteId=route["RouteId"], RouteResponseSelectionExpression="")+ assert "RouteResponseSelectionExpression" not in updated++ logs = {"DestinationArn": "arn:aws:logs:us-east-1:000000000000:log-group:ws", "Format": "$context.requestId"}+ stage = apigw.create_stage(ApiId=api_id, StageName="prod", AccessLogSettings=logs)+ assert stage["AccessLogSettings"] == logs+ assert apigw.get_stage(ApiId=api_id, StageName="prod")["AccessLogSettings"] == logs+ changed = {**logs, "Format": "$context.requestId $context.status"}+ assert apigw.update_stage(ApiId=api_id, StageName="prod", AccessLogSettings=changed)["AccessLogSettings"] == changeddef test_ws_post_to_unknown_connection_returns_410(apigw, lam):