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(bugs):api, jwt, sdk (#1075)
Nahuel Nucera498c926c3b5b
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.pyindex c4179ee8..a45f01a0 100644--- a/ministack/services/apigateway.py+++ b/ministack/services/apigateway.py@@ -1943,6 +1943,14 @@ async def _invoke_ws_lambda(api_id: str, account_id: str, region: str, route: dielse:event["queryStringParameters"] = Noneevent["multiValueQueryStringParameters"] = None+ authorizer_claims = kwargs.get("authorizer_claims")+ if authorizer_claims is not None:+ request_context["authorizer"] = {+ "jwt": {+ "claims": authorizer_claims,+ "scopes": kwargs.get("authorizer_scopes") or [],+ }+ }runtime = func_config.get("Runtime", "")code_zip = func_data.get("code_zip")@@ -2043,10 +2051,31 @@ async def handle_websocket(scope, receive, send, api_id: str, path_override: str# $connect hookconnect_route = _match_ws_route(api_id, "$connect")if connect_route is not None:+ # JWT authorizer validation (mirrors the HTTP API path).+ auth_type = (connect_route.get("authorizationType") or "NONE").upper()+ ws_authorizer_claims = None+ ws_authorizer_scopes = []+ if auth_type == "JWT":+ authorizer_id = connect_route.get("authorizerId")+ authorizer = _authorizers.get(api_id, {}).get(authorizer_id) if authorizer_id else None+ if not authorizer:+ await send({"type": "websocket.close", "code": 1008})+ return+ claims, scopes, auth_error = await _validate_jwt_authorizer(+ connect_route, authorizer, headers, query_params or {},+ )+ if auth_error:+ await send({"type": "websocket.close", "code": 1008})+ return+ ws_authorizer_claims = claims or {}+ ws_authorizer_scopes = scopes or []+resp = await _invoke_ws_lambda(api_id, account_id, owner_region, connect_route, stage, connection_id,"CONNECT", new_uuid(), "", source_ip, headers,query_params=query_params,+ authorizer_claims=ws_authorizer_claims,+ authorizer_scopes=ws_authorizer_scopes,)status = int((resp or {}).get("statusCode", 200))if status < 200 or status >= 300:diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex a359f2fa..80d2bbc9 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -232,7 +232,11 @@ def _get_object_data(bucket_name: str, key: str, version_id: str | None = None)if version_id:for v in _object_versions.get((bucket_name, key), []):if v["version_id"] == version_id:- return v.get("data")+ data = v.get("data")+ if data is not None:+ return data+ obj = bucket["objects"].get(key)+ return _read_body(bucket_name, key, obj) if obj else Nonereturn Noneobj = bucket["objects"].get(key)if obj is None:@@ -2539,7 +2543,8 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict =if stored:resp_headers["x-amz-checksum-type"] = "FULL_OBJECT"resp_headers.update(_object_tagging_count_header(bucket_name, key, version_id))- return 200, resp_headers, v["data"]+ body = v["data"] if v["data"] is not None else _read_body(bucket_name, key, bucket["objects"].get(key, {}))+ return 200, resp_headers, bodyreturn _error("NoSuchVersion", "The specified version does not exist.", 404, f"/{bucket_name}/{key}")if key not in bucket["objects"]:@@ -4368,6 +4373,20 @@ def _load_persisted_bucket(account_id, bucket_name, bucket_path):}if meta.get("version_id"):bucket["objects"][key]["version_id"] = meta["version_id"]+ vkey = (bucket_name, key)+ scoped_vkey = (account_id, vkey)+ if scoped_vkey not in _object_versions._data:+ _object_versions._data[scoped_vkey] = []+ _object_versions._data[scoped_vkey].append({+ "version_id": meta["version_id"],+ "last_modified": meta.get("last_modified") or now_iso(),+ "etag": etag,+ "size": size,+ "is_latest": True,+ "data": None,+ "storage_class": meta.get("storage_class", "STANDARD"),+ "checksums": meta.get("checksums", {}),+ })_load_persisted_data()diff --git a/ministack/services/sqs.py b/ministack/services/sqs.pyindex f72c7a8e..0497dd6a 100644--- a/ministack/services/sqs.py+++ b/ministack/services/sqs.py@@ -1294,10 +1294,11 @@ def _xml_resp(status: int, root: str, inner: str) -> tuple:def _xml_err_resp(code: str, msg: str, status: int = 400) -> tuple:sender_type = "Sender" if status < 500 else "Receiver"+ legacy = _QUERY_COMPAT_CODES.get(code, code)body = (f'<?xml version="1.0" encoding="UTF-8"?>'f'<ErrorResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/">'- f'<Error><Type>{sender_type}</Type><Code>{_esc(code)}</Code><Message>{_esc(msg)}</Message></Error>'+ f'<Error><Type>{sender_type}</Type><Code>{_esc(legacy)}</Code><Message>{_esc(msg)}</Message></Error>'f'<RequestId>{new_uuid()}</RequestId>'f'</ErrorResponse>').encode("utf-8")diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.pyindex 94ea86a5..7482d49b 100644--- a/tests/test_apigatewayv2.py+++ b/tests/test_apigatewayv2.py@@ -2368,6 +2368,54 @@ def test_apigwv2_path_based_websocket(apigw, lam):ws.close()+def test_ws_connect_jwt_authorizer_rejects_missing_token(apigw, lam, cognito_idp):+ """$connect with a JWT authorizer rejects connections that lack a valid token (#1074)."""+ from ministack.services import cognito as _cognito++ pool_id = cognito_idp.create_user_pool(PoolName=f"ws-jwt-{_uuid_mod.uuid4().hex[:8]}")["UserPool"]["Id"]+ issuer = f"https://cognito-idp.us-east-1.amazonaws.com/{pool_id}"+ api = apigw.create_api(Name=f"ws-jwt-deny-{_uuid_mod.uuid4().hex[:8]}", ProtocolType="WEBSOCKET")+ api_id = api["ApiId"]++ fn_name = f"ws-jwt-con-{_uuid_mod.uuid4().hex[:6]}"+ arn = _make_fn(lam, fn_name, _ECHO_CODE)+ integ = apigw.create_integration(+ ApiId=api_id, IntegrationType="AWS_PROXY",+ IntegrationUri=arn, IntegrationMethod="POST",+ )+ auth_id = apigw.create_authorizer(+ ApiId=api_id, AuthorizerType="JWT", Name="ws-jwt",+ IdentitySource=["$request.querystring.token"],+ JwtConfiguration={"Audience": ["ws-client"], "Issuer": issuer},+ )["AuthorizerId"]+ apigw.create_route(+ ApiId=api_id, RouteKey="$connect",+ Target=f"integrations/{integ['IntegrationId']}",+ AuthorizationType="JWT", AuthorizerId=auth_id,+ )+ apigw.create_route(+ ApiId=api_id, RouteKey="$default",+ Target=f"integrations/{integ['IntegrationId']}",+ )+ apigw.create_stage(ApiId=api_id, StageName="prod")++ # Without a token → connection must be rejected (close code 1008).+ with pytest.raises(Exception):+ _WSClient("localhost", _EXECUTE_PORT, "/prod",+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"})++ # With a valid token → connection must be accepted.+ now = int(time.time())+ token = _make_signed_token({+ "sub": "ws-user", "iss": issuer, "aud": "ws-client",+ "iat": now, "nbf": now - 1, "exp": now + 3600,+ })+ ws = _WSClient("localhost", _EXECUTE_PORT, f"/prod?token={token}",+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"})+ ws.close()+ cognito_idp.delete_user_pool(UserPoolId=pool_id)++def test_apigwv1_path_based_restapi_legacy_user_request(apigw_v1, lam):"""REST API v1 reachable via /restapis/{apiId}/{stage}/_user_request_/{path} (LocalStack legacy)."""import urllib.requestdiff --git a/tests/test_s3.py b/tests/test_s3.pyindex b8fe20f4..48dfcf40 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -2399,6 +2399,53 @@ def test_s3_version_id_persisted_to_disk(tmp_path, monkeypatch):s3mod._buckets._data.pop(("000000000000", "ver-bucket"), None)+def test_s3_version_id_get_object_after_restore(tmp_path, monkeypatch):+ """GetObject(VersionId=...) must work after _load_persisted_bucket restores+ from disk. The version index (_object_versions) must be rebuilt so lookups+ by VersionId succeed (#1065)."""+ from ministack.services import s3 as s3mod+ monkeypatch.setattr(s3mod, "DATA_DIR", str(tmp_path))+ monkeypatch.setattr(s3mod, "S3_PERSIST", True)+ monkeypatch.setattr(s3mod, "get_account_id", lambda: "000000000000")++ version_id = "test-version-1065"+ obj = {+ "body": b"version-data",+ "content_type": "application/octet-stream",+ "content_encoding": None,+ "etag": '"abc"',+ "last_modified": s3mod.now_iso(),+ "size": 12,+ "metadata": {},+ "preserved_headers": {},+ "storage_class": "STANDARD",+ "version_id": version_id,+ }+ s3mod._persist_object("ver-get-bucket", "k", obj)++ # Clear in-memory state to simulate restart+ s3mod._buckets._data.pop(("000000000000", "ver-get-bucket"), None)+ s3mod._object_versions._data.pop(("000000000000", ("ver-get-bucket", "k")), None)++ try:+ s3mod._load_persisted_bucket(+ "000000000000", "ver-get-bucket",+ os.path.join(str(tmp_path), "000000000000", "ver-get-bucket"))++ # Verify _object_versions was rebuilt+ versions = s3mod._object_versions._data.get(("000000000000", ("ver-get-bucket", "k")), [])+ assert len(versions) == 1+ assert versions[0]["version_id"] == version_id+ assert versions[0]["data"] is None # body stays on disk++ # Verify GetObject by VersionId returns the body from disk+ data = s3mod._get_object_data("ver-get-bucket", "k", version_id=version_id)+ assert data == b"version-data"+ finally:+ s3mod._buckets._data.pop(("000000000000", "ver-get-bucket"), None)+ s3mod._object_versions._data.pop(("000000000000", ("ver-get-bucket", "k")), None)++def test_s3_put_object_sidecar_carries_version_id(tmp_path, monkeypatch):"""PutObject on a versioned bucket must persist AFTER version_id assignment,so the on-disk .meta.json carries the id returned in x-amz-version-id (#1058)."""diff --git a/tests/test_sqs.py b/tests/test_sqs.pyindex 652dad73..35fad882 100644--- a/tests/test_sqs.py+++ b/tests/test_sqs.py@@ -1292,6 +1292,29 @@ def test_sqs_send_message_allows_valid_chars(sqs):assert "MessageId" in resp, f"send failed for {repr(body)}"+def test_sqs_xml_query_error_code_uses_legacy_namespace():+ """XML Query API error responses must use legacy namespaced codes+ (e.g. AWS.SimpleQueueService.NonExistentQueue) not the short JSON codes+ (e.g. QueueDoesNotExist). .NET SDK and other XML-protocol callers match+ on the namespaced string (#1066)."""+ import urllib.error+ import urllib.request+ import xml.etree.ElementTree as ET++ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ try:+ urllib.request.urlopen(f"{endpoint}/?Action=GetQueueUrl&QueueName=nonexistent-xml-test-queue")+ raise AssertionError("expected HTTP error")+ except urllib.error.HTTPError as e:+ body = e.read()+ root = ET.fromstring(body)+ ns = {"ns": "http://queue.amazonaws.com/doc/2012-11-05/"}+ code = root.find(".//ns:Code", ns).text+ assert code == "AWS.SimpleQueueService.NonExistentQueue", (+ f"XML error code must be legacy namespaced, got '{code}'"+ )++def test_sqs_invalid_chars_regex_matches_xml10_complement():"""The forbidden-char regex must be the exact complement of AWS SQS's allowedset (#x9 | #xA | #xD | #x20-#xD7FF | #xE000-#xFFFD | #x10000-#x10FFFF), which