Skip to content

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

release 1.3.6 (#408)

Nahuel Nucera7c7b1a42070d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 611f4f1e..2fd77cda 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,22 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.3.6] — 2026-04-20
+
+### Added
+- **API Gateway path-based data plane** — REST + HTTP + WebSocket APIs are now reachable without `*.execute-api.localhost` Host overrides: `http(s)://localhost:4566/_aws/execute-api/{apiId}/{stage}/{path}` (v1 + v2 HTTP + v2 WS) and the LocalStack-legacy `http://localhost:4566/restapis/{apiId}/{stage}/_user_request_/{path}` (v1). Unblocks macOS browsers (no `*.localhost` DNS resolution) and strict HTTP clients with no Host override.
+- **Custom/predictable API Gateway IDs** — `aws_apigatewayv2_api` and `aws_apigateway_rest_api` honour an `ms-custom-id` tag on `CreateApi` / `CreateRestApi` and pin the generated `apiId` / REST API id to the tag value. Duplicates in the same account return `ConflictException` (409). The LocalStack `ls-custom-id` tag is intentionally rejected with a clear `BadRequestException` (400) pointing callers at the ministack-native key. Reported by @whittin3. Fixes #400
+- **Cognito `AWS::Cognito::UserPoolClient` CFN `GenerateSecret`** — CloudFormation-provisioned user pool clients now generate a client secret when `GenerateSecret: true`, matching the native Cognito API path. Contributed by @mgius-ae (#403)
+
+### Fixed
+- **API Gateway v2 HTTP API — `$default` stage treated first path segment as stage name** — an API configured with the `$default` stage returned `404 "Stage 'X' not found"` for any request because the dispatcher always stripped a stage prefix from the URL. Stage resolution now checks the API's configured stages: strip the first segment only if it matches a real stage, otherwise route to `$default` with the full path (matching AWS). Same fix applies to the WebSocket scope handler. Reported by @whittin3. Fixes #404
+- **API Gateway v2 HTTP API — `corsConfiguration` ignored** — every OPTIONS preflight returned a hard-coded wildcard `Access-Control-Allow-Origin: *`, breaking browsers using `credentials: "include"`, and non-OPTIONS responses had the wildcard spliced in over whatever the Lambda set. API Gateway now serves preflights from the per-API `corsConfiguration` (403 if origin isn't in `allowOrigins`, `Access-Control-Allow-Credentials: true` only when configured and paired with a concrete origin), and dispatched responses carry per-config CORS headers instead of the wildcard. Reported by @whittin3. Fixes #406
+- **Lambda alias qualifier parsed as function name** — integrations (v1 REST, v2 HTTP, v2 WebSocket) and event source mappings wired to a qualified ARN (`arn:...:function:<name>:<alias>`) invoked a function whose name was the qualifier (`live`) and returned `502 "Lambda function 'live' not found"`. All three dispatchers now use `_resolve_name_and_qualifier` + `_get_func_record_for_qualifier` to resolve aliases to their target version before invocation; worker pool keyed by `name:qualifier` so aliased vs unqualified calls don't share process state. ESM pollers (SQS, Kinesis, DDB Streams) store the qualifier on the mapping and use it on every batch. Reported by @whittin3. Fixes #407
+- **API Gateway v1 error responses used `type` instead of `__type`** — boto3 fell back to the numeric HTTP status as the error code (`ClientError.response["Error"]["Code"] == "409"` instead of `"ConflictException"`). Every JSON-protocol AWS service uses `__type`; v1 now matches.
+- **SQS singular `DeleteMessage` / `ChangeMessageVisibility` silently succeeded on invalid ReceiptHandle** — real AWS returns `ReceiptHandleIsInvalid` (400); batch variants already did. Singular operations now raise the same error. Contributed by @nigel-campbell (#405)
+
+---
+
## [1.3.5] — 2026-04-20
### Added
diff --git a/README.md b/README.md
index b91c89bf..cf58cb43 100644
--- a/README.md
+++ b/README.md
@@ -356,8 +356,8 @@ subnet = ec2.create_subnet(
| **ACM** | RequestCertificate, DescribeCertificate, ListCertificates, DeleteCertificate, GetCertificate, ImportCertificate, AddTagsToCertificate, RemoveTagsFromCertificate, ListTagsForCertificate, UpdateCertificateOptions, RenewCertificate, ResendValidationEmail | Certificates auto-issued; DNS validation records generated; supports SANs |
| **WAF v2** | CreateWebACL, GetWebACL, UpdateWebACL, DeleteWebACL, ListWebACLs, AssociateWebACL, DisassociateWebACL, GetWebACLForResource, ListResourcesForWebACL, CreateIPSet, GetIPSet, UpdateIPSet, DeleteIPSet, ListIPSets, CreateRuleGroup, GetRuleGroup, UpdateRuleGroup, DeleteRuleGroup, ListRuleGroups, TagResource, UntagResource, ListTagsForResource, CheckCapacity, DescribeManagedRuleGroup | LockToken enforced on Update/Delete; resource associations tracked |
| **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StartSyncExecution, StopExecution, DescribeExecution, DescribeStateMachineForExecution, ListExecutions, GetExecutionHistory, SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat, CreateActivity, DeleteActivity, DescribeActivity, ListActivities, GetActivityTask, TestState, TagResource, UntagResource, ListTagsForResource | Full ASL interpreter; Retry/Catch; waitForTaskToken; Activities (worker pattern); Pass/Task/Choice/Wait/Succeed/Fail/Map/Parallel; TestState API with mock and inspectionLevel support; SFN_MOCK_CONFIG for AWS SFN Local compatible mock testing; intrinsic functions (States.StringToJson, States.JsonToString, States.JsonMerge, States.Format); nested startExecution.sync |
-| **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateRouteResponse, GetRouteResponse, GetRouteResponses, UpdateRouteResponse, DeleteRouteResponse, CreateIntegrationResponse, GetIntegrationResponse, GetIntegrationResponses, UpdateIntegrationResponse, DeleteIntegrationResponse, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags, PostToConnection, GetConnection, DeleteConnection | **HTTP API** and **WebSocket API** (`protocolType=WEBSOCKET`); Lambda proxy (`AWS_PROXY`), HTTP proxy (`HTTP_PROXY`), and MOCK integrations; HTTP data plane via `{apiId}.execute-api.localhost` Host header or path-based `/_aws/execute-api/{apiId}/{stage}/{path}` (no DNS/Host override needed — works from browsers on macOS and strict clients); WebSocket data plane on the same two URL forms, with `$connect` / `$disconnect` / `$default` / custom-action routing, `$request.body.*` RouteSelectionExpression, `@connections` management API (PostToConnection / GetConnection / DeleteConnection), per-connection outbox for server-side push; `{param}` / `{proxy+}` matching; JWT/Lambda authorizer CRUD |
-| **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost` Host header, path-based `/_aws/execute-api/{apiId}/{stage}/{path}`, or legacy `/restapis/{apiId}/{stage}/_user_request_/{path}`; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence |
+| **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateRouteResponse, GetRouteResponse, GetRouteResponses, UpdateRouteResponse, DeleteRouteResponse, CreateIntegrationResponse, GetIntegrationResponse, GetIntegrationResponses, UpdateIntegrationResponse, DeleteIntegrationResponse, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags, PostToConnection, GetConnection, DeleteConnection | **HTTP API** and **WebSocket API** (`protocolType=WEBSOCKET`); Lambda proxy (`AWS_PROXY`), HTTP proxy (`HTTP_PROXY`), and MOCK integrations; HTTP data plane via `{apiId}.execute-api.localhost` Host header or path-based `/_aws/execute-api/{apiId}/{stage}/{path}` (no DNS/Host override needed — works from browsers on macOS and strict clients); `$default` stage served from the URL root (no stage segment in the path); per-API `corsConfiguration` applied to preflights + dispatched responses; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; WebSocket data plane on the same two URL forms, with `$connect` / `$disconnect` / `$default` / custom-action routing, `$request.body.*` RouteSelectionExpression, `@connections` management API (PostToConnection / GetConnection / DeleteConnection), per-connection outbox for server-side push; `{param}` / `{proxy+}` matching; JWT/Lambda authorizer CRUD; pin `apiId` across runs with the `ms-custom-id` tag |
+| **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost` Host header, path-based `/_aws/execute-api/{apiId}/{stage}/{path}`, or legacy `/restapis/{apiId}/{stage}/_user_request_/{path}`; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence; pin `id` across runs with the `ms-custom-id` tag |
| **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, RegisterTargets, DeregisterTargets, DescribeTargetHealth, AddTags, RemoveTags, DescribeTags | Control plane + data plane; ALB→Lambda live traffic routing; `path-pattern`, `host-header`, `http-method`, `query-string`, `http-header` rule conditions; `forward`, `redirect`, `fixed-response` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix |
| **KMS** | CreateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateDataKey, GenerateDataKeyWithoutPlaintext, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags | 27 actions; RSA (2048/4096), ECC (SECG_P256K1, NIST P-256/384/521), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; envelope encryption; alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; full Terraform `aws_kms_key` compatible; `cryptography` package included in Docker image |
| **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; field validation and name uniqueness enforcement |
@@ -997,6 +997,23 @@ module "vpc" {
Creates VPC with per-VPC default network ACL, security group, and main route table. All 23 resources (subnets, IGW, NAT, route tables, associations, routes, default resources) supported.
+#### Predictable API Gateway IDs (`ms-custom-id`)
+
+Pin the generated `apiId` / REST API id to a caller-supplied value so URLs stay stable across `terraform apply` runs. Works on `aws_apigatewayv2_api` (HTTP + WebSocket) and `aws_apigateway_rest_api`.
+
+```hcl
+resource "aws_apigatewayv2_api" "example" {
+ name = "example"
+ protocol_type = "HTTP"
+ tags = {
+ ms-custom-id = "example"
+ }
+}
+# → invoke URL stays "example.execute-api.localhost:4566" every apply
+```
+
+Duplicates in the same account fail with `ConflictException`. The LocalStack `ls-custom-id` tag is not recognised — use `ms-custom-id` only (callers hitting the old name get a clear `BadRequestException`).
+
### AWS CDK
Set `AWS_ENDPOINT_URL` to route all CDK requests to MiniStack:
diff --git a/ministack/app.py b/ministack/app.py
index 965fde46..0e3172e3 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -433,8 +433,13 @@ async def _handle_admin_reset(path: str, method: str, query_params: dict):
async def _handle_pre_body_request(method: str, path: str, headers: dict, query_params: dict, request_id: str):
"""Handle fast-path routes that do not require request body parsing."""
+ # OPTIONS on an execute-api host / path MUST flow through apigateway.handle_execute
+ # so the API's own corsConfiguration is applied (#406). Skip the generic wildcard
+ # preflight in that case.
+ host = headers.get("host", "")
+ is_execute_api = _parse_execute_api_url(host, path) is not None
for response in (
- _handle_options_request(method, request_id),
+ None if is_execute_api else _handle_options_request(method, request_id),
_handle_health_request(path, request_id),
_handle_ready_request(path, request_id),
_handle_lambda_download_request(path, method),
@@ -634,20 +639,54 @@ def _parse_execute_api_url(host: str, path: str) -> tuple[str, str, str] | None:
return None
+def _resolve_stage_and_path(api_id: str, tentative_stage: str, execute_path: str) -> tuple[str, str]:
+ """Pick (stage, execute_path) based on the API's configured stages.
+
+ AWS v2 HTTP / WebSocket APIs configured with the ``$default`` stage serve
+ from the root of the execute-api URL — no stage segment in the path. v1
+ REST APIs always carry the stage as the first path segment. We can't tell
+ from the URL alone which pattern applies, so we check the API's configured
+ stages and route accordingly (issue #404).
+
+ Rules:
+ - If the tentative first segment IS a configured stage name, strip it.
+ - Else if the API has a ``$default`` stage, use that and treat the
+ whole original path (including ``tentative_stage``) as ``execute_path``.
+ - Else fall through (``handle_execute`` will return "Stage not found").
+ """
+ apigw_v1 = _get_module("apigateway_v1")
+ if api_id in apigw_v1._rest_apis:
+ stages_map = apigw_v1._stages_v1.get(api_id, {})
+ else:
+ stages_map = _get_module("apigateway")._stages.get(api_id, {})
+
+ if tentative_stage in stages_map:
+ return tentative_stage, execute_path
+ if "$default" in stages_map:
+ if execute_path == "/":
+ resolved_path = "/" + tentative_stage if tentative_stage else "/"
+ else:
+ resolved_path = "/" + tentative_stage + execute_path
+ return "$default", resolved_path
+ # No match — let handle_execute report the stage miss verbatim.
+ return tentative_stage, execute_path
+
+
async def _handle_execute_api_request(host: str, path: str, method: str, headers: dict, body: bytes, query_params: dict):
"""Handle API Gateway execute-api data plane requests (Host-based + path-based)."""
parsed = _parse_execute_api_url(host, path)
if parsed is None:
return None
- api_id, stage, execute_path = parsed
+ api_id, tentative_stage, execute_path = parsed
try:
- # WebSocket @connections management API — /{stage}/@connections/{id} in
- # the Host-based form resolves to execute_path == "/@connections/{id}".
+ # WebSocket @connections management API — /{stage}/@connections/{id}.
+ # The @connections prefix is authoritative; skip $default resolution.
if execute_path.startswith("/@connections/"):
connection_id = execute_path[len("/@connections/"):].split("/", 1)[0]
return await _get_module("apigateway").handle_connections_api(
- method, api_id, stage, connection_id, body, headers
+ method, api_id, tentative_stage, connection_id, body, headers
)
+ stage, execute_path = _resolve_stage_and_path(api_id, tentative_stage, execute_path)
if api_id in _get_module("apigateway_v1")._rest_apis:
return await _get_module("apigateway_v1").handle_execute(
api_id, stage, method, execute_path, headers, body, query_params
@@ -722,16 +761,21 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: d
)
-def _with_data_plane_headers(response, request_id: str, include_s3_id: bool = False):
- """Attach common data-plane CORS and request ID headers to a response tuple."""
+def _with_data_plane_headers(response, request_id: str, include_s3_id: bool = False, wildcard_cors: bool = True):
+ """Attach common data-plane request-id headers to a response tuple.
+
+ ``wildcard_cors`` controls whether a wildcard ``Access-Control-Allow-Origin: *``
+ is added. API Gateway owns its own CORS (per-API ``corsConfiguration``,
+ issue #406) so the caller passes ``wildcard_cors=False`` there to avoid
+ clobbering the per-config value. Respects any ``Access-Control-Allow-Origin``
+ already set by the upstream handler."""
if response is None:
return None
status, headers, body = response
- headers.update({
- "Access-Control-Allow-Origin": "*",
- "x-amzn-requestid": request_id,
- "x-amz-request-id": request_id,
- })
+ if wildcard_cors and "Access-Control-Allow-Origin" not in headers:
+ headers["Access-Control-Allow-Origin"] = "*"
+ headers["x-amzn-requestid"] = request_id
+ headers["x-amz-request-id"] = request_id
if include_s3_id:
headers["x-amz-id-2"] = base64.b64encode(os.urandom(48)).decode()
return status, headers, body
@@ -755,7 +799,7 @@ async def _handle_special_data_plane_request(
host = headers.get("host", "")
if response := await _handle_execute_api_request(host, path, method, headers, body, query_params):
- return _with_data_plane_headers(response, request_id)
+ return _with_data_plane_headers(response, request_id, wildcard_cors=False)
if response := await _handle_s3_vhost_request(host, path, method, headers, body, query_params):
return _with_data_plane_headers(response, request_id, include_s3_id=True)
if response := await _handle_alb_request(host, path, method, headers, body, query_params):
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index 25557b07..9c1f6020 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -287,12 +287,75 @@ async def handle_request(method, path, headers, body, query_params):
# ---- Data plane ----
+def _cors_response_headers(cors_cfg: dict, origin: str) -> dict:
+ """Build CORS response headers for a non-OPTIONS dispatched response.
+
+ Per AWS (https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-cors.html):
+ - If Origin matches allow_origins (or allow_origins contains "*"), echo
+ the caller's Origin back (or "*"); else omit CORS headers entirely.
+ - allow_credentials is only emitted when true, and requires a concrete
+ origin — never paired with "*".
+ - expose_headers / max_age / etc. are attached if configured.
+ """
+ if not cors_cfg:
+ return {}
+ allowed_origins = [o.lower() for o in cors_cfg.get("allowOrigins", [])]
+ origin_lc = (origin or "").lower()
+ if allowed_origins == ["*"]:
+ allow_origin_value = "*"
+ elif origin_lc and origin_lc in allowed_origins:
+ allow_origin_value = origin # echo exact caller-supplied casing
+ else:
+ return {}
+
+ out: dict = {"Access-Control-Allow-Origin": allow_origin_value}
+ if cors_cfg.get("allowCredentials") and allow_origin_value != "*":
+ out["Access-Control-Allow-Credentials"] = "true"
+ if cors_cfg.get("exposeHeaders"):
+ out["Access-Control-Expose-Headers"] = ",".join(cors_cfg["exposeHeaders"])
+ if "Origin" not in out.get("Vary", ""):
+ out["Vary"] = "Origin"
+ return out
+
+
+def _cors_preflight_response(cors_cfg: dict, origin: str) -> tuple:
+ """Build the full OPTIONS preflight response from corsConfiguration."""
+ if not cors_cfg:
+ # AWS behaviour: API without CORS configured returns 403 on preflight.
+ return 403, {"Content-Type": "application/json"}, json.dumps(
+ {"message": "CORS not configured"}
+ ).encode()
+
+ base = _cors_response_headers(cors_cfg, origin)
+ if not base:
+ # Origin not in allow_origins — 403, no CORS headers echoed back.
+ return 403, {"Content-Type": "application/json"}, json.dumps(
+ {"message": "CORS origin denied"}
+ ).encode()
+
+ if cors_cfg.get("allowMethods"):
+ base["Access-Control-Allow-Methods"] = ",".join(cors_cfg["allowMethods"])
+ if cors_cfg.get("allowHeaders"):
+ base["Access-Control-Allow-Headers"] = ",".join(cors_cfg["allowHeaders"])
+ if cors_cfg.get("maxAge") is not None:
+ base["Access-Control-Max-Age"] = str(cors_cfg["maxAge"])
+ base["Content-Length"] = "0"
+ return 204, base, b""
+
+
async def handle_execute(api_id, stage, path, method, headers, body, query_params):
"""Execute an API request through a deployed API (data plane)."""
api = _apis.get(api_id)
if not api:
return 404, {"Content-Type": "application/json"}, json.dumps({"message": "Not Found"}).encode()
+ # CORS preflight: served from the API's corsConfiguration before any route
+ # matching, because AWS responds to OPTIONS itself without invoking the
+ # integration. (#406)
+ cors_cfg = api.get("corsConfiguration") or {}
+ if method == "OPTIONS":
+ return _cors_preflight_response(cors_cfg, headers.get("origin") or headers.get("Origin", ""))
+
api_stages = _stages.get(api_id, {})
if stage not in api_stages and stage != "$default":
return 404, {"Content-Type": "application/json"}, json.dumps({"message": f"Stage '{stage}' not found"}).encode()
@@ -314,12 +377,20 @@ async def handle_execute(api_id, stage, path, method, headers, body, query_param
rk_parts = route_key.split(" ", 1)
if len(rk_parts) == 2:
path_params = _extract_path_params(rk_parts[1], path) or None
- return await _invoke_lambda_proxy(integration, api_id, stage, path, method, headers, body, query_params, route_key, path_params)
+ response = await _invoke_lambda_proxy(integration, api_id, stage, path, method, headers, body, query_params, route_key, path_params)
elif integration_type == "HTTP_PROXY":
- return await _invoke_http_proxy(integration, path, method, headers, body, query_params)
+ response = await _invoke_http_proxy(integration, path, method, headers, body, query_params)
else:
return 500, {"Content-Type": "application/json"}, json.dumps({"message": f"Unsupported integration type: {integration_type}"}).encode()
+ # Decorate dispatched response with per-API CORS headers (#406) — AWS adds
+ # these in front of the integration response for non-OPTIONS requests.
+ if cors_cfg:
+ status, resp_headers, resp_body = response
+ resp_headers.update(_cors_response_headers(cors_cfg, headers.get("origin") or headers.get("Origin", "")))
+ response = status, resp_headers, resp_body
+ return response
+
def _match_route(api_id, method, path):
"""Find the best matching route for method+path. $default route is the fallback."""
@@ -380,14 +451,19 @@ async def _invoke_lambda_proxy(integration, api_id, stage, path, method, headers
from ministack.core.lambda_runtime import get_or_create_worker
from ministack.services import lambda_svc
- uri = integration.get("integrationUri", "")
- # integrationUri is a Lambda ARN; the function name is the last segment
- func_name = uri.split(":")[-1] if ":" in uri else uri
- # Strip /invocations suffix emitted by some SDKs
- func_name = func_name.replace("/invocations", "")
-
- if func_name not in lambda_svc._functions:
- return 502, {"Content-Type": "application/json"}, json.dumps({"message": f"Lambda function '{func_name}' not found"}).encode()
+ # integrationUri is typically a Lambda ARN; strip the trailing /invocations
+ # that the apigateway:lambda:path form appends, then parse name + qualifier.
+ # Qualified aliases (arn:...:function:<name>:<alias>) must resolve to the
+ # alias's target version, not be treated as the function name itself (#407).
+ uri = integration.get("integrationUri", "").replace("/invocations", "")
+ func_name, qualifier = lambda_svc._resolve_name_and_qualifier(uri)
+ func_data, func_config = lambda_svc._get_func_record_for_qualifier(func_name, qualifier)
+ if func_data is None:
+ return 502, {"Content-Type": "application/json"}, json.dumps({
+ "message": f"Lambda function '{func_name}'" +
+ (f" (qualifier '{qualifier}')" if qualifier else "") +
+ " not found"
+ }).encode()
# Build API Gateway v2 proxy event (payload format 2.0)
# AWS API Gateway v2 joins multi-value query params with commas
@@ -422,12 +498,13 @@ async def _invoke_lambda_proxy(integration, api_id, stage, path, method, headers
"isBase64Encoded": False,
}
- func_data = lambda_svc._functions[func_name]
code_zip = func_data.get("code_zip")
-
- runtime = func_data["config"].get("Runtime", "")
+ runtime = func_config.get("Runtime", "")
if code_zip and runtime.startswith(("python", "nodejs")):
- worker = get_or_create_worker(func_name, func_data["config"], code_zip)
+ # Key the worker by name+qualifier so versioned / aliased invocations
+ # use their own cached process, matching Lambda.Invoke semantics.
+ worker_key = f"{func_name}:{qualifier}" if qualifier else func_name
+ worker = get_or_create_worker(worker_key, func_config, code_zip)
result = await asyncio.to_thread(worker.invoke, event, new_uuid())
if result.get("status") == "error":
return 502, {"Content-Type": "application/json"}, json.dumps({"message": result.get("error")}).encode()
@@ -469,8 +546,42 @@ async def _invoke_http_proxy(integration, path, method, headers, body, query_par
# ---- Control plane: APIs ----
+def _resolve_custom_api_id(tags: dict, existing: "AccountScopedDict") -> str | None:
+ """Return a caller-pinned API id from the ``ms-custom-id`` tag, or None
+ if no tag is set (issue #400).
+
+ Raises ``ValueError`` if the requested id is already in use in the caller's
+ account, so misconfigs surface immediately instead of silently falling back
+ to a random id.
+
+ ``ls-custom-id`` (LocalStack's tag) is intentionally NOT supported — callers
+ hitting it get a clear ``BadRequestException`` pointing them at
+ ``ms-custom-id`` so the ministack-native key is the only contract."""
+ if not isinstance(tags, dict):
+ return None
+ if "ls-custom-id" in tags and "ms-custom-id" not in tags:
+ raise ValueError(
+ "ls-custom-id tag is not supported; use 'ms-custom-id' instead"
+ )
+ custom = tags.get("ms-custom-id")
+ if not custom:
+ return None
+ if custom in existing:
+ raise ValueError(
+ f"API id '{custom}' (from ms-custom-id tag) is already in use"
+ )
+ return str(custom)
+
+
def _create_api(data):
- api_id = new_uuid()[:8]
+ tags = data.get("tags", {})
+ try:
+ api_id = _resolve_custom_api_id(tags, _apis) or new_uuid()[:8]
+ except ValueError as exc:
+ msg = str(exc)
+ if "already in use" in msg:
+ return _apigw_error("ConflictException", msg, 409)
+ return _apigw_error("BadRequestException", msg, 400)
protocol = data.get("protocolType", "HTTP")
# AWS defaults: HTTP → "$request.method $request.path"; WEBSOCKET → "$request.body.action".
default_rse = "$request.body.action" if protocol == "WEBSOCKET" else "$request.method $request.path"
@@ -1012,10 +1123,11 @@ async def _invoke_ws_lambda(api_id: str, account_id: str, route: dict, stage: st
)
return None
- uri = integration.get("integrationUri", "")
- func_name = uri.split(":")[-1] if ":" in uri else uri
- func_name = func_name.replace("/invocations", "")
- if func_name not in lambda_svc._functions:
+ # Parse name + qualifier so alias ARNs resolve to their target version (#407).
+ uri = integration.get("integrationUri", "").replace("/invocations", "")
+ func_name, qualifier = lambda_svc._resolve_name_and_qualifier(uri)
+ func_data, func_config = lambda_svc._get_func_record_for_qualifier(func_name, qualifier)
+ if func_data is None:
return None
request_context = {
@@ -1061,11 +1173,11 @@ async def _invoke_ws_lambda(api_id: str, account_id: str, route: dict, stage: st
event["queryStringParameters"] = None
event["multiValueQueryStringParameters"] = None
- func_data = lambda_svc._functions[func_name]
- runtime = func_data["config"].get("Runtime", "")
+ runtime = func_config.get("Runtime", "")
code_zip = func_data.get("code_zip")
if code_zip and runtime.startswith(("python", "nodejs")):
- worker = get_or_create_worker(func_name, func_data["config"], code_zip)
+ worker_key = f"{func_name}:{qualifier}" if qualifier else func_name
+ worker = get_or_create_worker(worker_key, func_config, code_zip)
result = await asyncio.to_thread(worker.invoke, event, message_id)
if result.get("status") == "error":
return {"statusCode": 500, "body": result.get("error", "")}
@@ -1102,9 +1214,18 @@ async def handle_websocket(scope, receive, send, api_id: str, path_override: str
# Stage parsing: Host-based URLs look like wss://{apiId}.execute-api.../stage;
# path-based compat URLs (#401) use path_override with the rewritten path.
+ # If the first segment isn't a configured stage name but the API has a
+ # ``$default`` stage, route to it (issue #404).
path = path_override if path_override is not None else scope.get("path", "")
path_parts = path.lstrip("/").split("/", 1)
- stage = path_parts[0] if path_parts and path_parts[0] else "$default"
+ tentative = path_parts[0] if path_parts and path_parts[0] else "$default"
+ configured_stages = _stages.get(api_id, {})
+ if tentative in configured_stages:
+ stage = tentative
+ elif "$default" in configured_stages:
+ stage = "$default"
+ else:
+ stage = tentative # pass through; downstream will handle unknown-stage
headers = {}
for name, value in scope.get("headers", []):
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 20246641..7220a595 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -120,7 +120,11 @@ def _v1_response(data, status=200):
def _v1_error(code, message, status):
- return status, {"Content-Type": "application/json"}, json.dumps({"message": message, "type": code}, ensure_ascii=False).encode("utf-8")
+ # AWS API Gateway errors use __type (double underscore), matching every
+ # other JSON-protocol AWS service. boto3 reads this to populate
+ # ``ClientError.response["Error"]["Code"]``; with plain "type" it falls
+ # back to the numeric HTTP status as the code.
+ return status, {"Content-Type": "application/json"}, json.dumps({"message": message, "__type": code}, ensure_ascii=False).encode("utf-8")
def _rest_api_arn(api_id):
@@ -226,20 +230,25 @@ def _match_recursive(resources, parent_id, segments, params):
return None, params
-async def _call_lambda(func_name, event):
- """Invoke a Lambda function and return the parsed response dict."""
+async def _call_lambda(func_name, event, qualifier=None):
+ """Invoke a Lambda function and return the parsed response dict.
+
+ ``qualifier`` may be a version number or alias name; aliases resolve to
+ their target version via ``_get_func_record_for_qualifier`` so aliased
+ integration URIs (arn:...:function:<name>:<alias>) invoke correctly (#407)."""
from ministack.core.lambda_runtime import get_or_create_worker
from ministack.services import lambda_svc
- if func_name not in lambda_svc._functions:
- return None, f"Lambda function '{func_name}' not found"
+ func_data, func_config = lambda_svc._get_func_record_for_qualifier(func_name, qualifier)
+ if func_data is None:
+ label = f"{func_name}:{qualifier}" if qualifier else func_name
+ return None, f"Lambda function '{label}' not found"
- func_data = lambda_svc._functions[func_name]
code_zip = func_data.get("code_zip")
-
- runtime = func_data["config"].get("Runtime", "")
+ runtime = func_config.get("Runtime", "")
if code_zip and runtime.startswith(("python", "nodejs")):
- worker = get_or_create_worker(func_name, func_data["config"], code_zip)
+ worker_key = f"{func_name}:{qualifier}" if qualifier else func_name
+ worker = get_or_create_worker(worker_key, func_config, code_zip)
result = await asyncio.to_thread(worker.invoke, event, new_uuid())
if result.get("status") == "error":
return None, result.get("error", "Lambda invocation error")
@@ -608,13 +617,17 @@ async def _invoke_lambda_proxy_v1(integration, api_id, stage_name, stage, resour
"""Invoke Lambda with API Gateway v1 payload format 1.0."""
uri = integration.get("uri", "")
# Supported URI formats:
- # 1. arn:aws:apigateway:{region}:lambda:path/2015-03-31/functions/arn:aws:lambda:{region}:{acct}:function:{name}/invocations
- # 2. arn:aws:lambda:{region}:{acct}:function:{name}
- # 3. plain function name: MyFunction
+ # 1. arn:aws:apigateway:{region}:lambda:path/2015-03-31/functions/arn:aws:lambda:{region}:{acct}:function:{name}[:{qualifier}]/invocations
+ # 2. arn:aws:lambda:{region}:{acct}:function:{name}[:{qualifier}]
+ # 3. plain function name: MyFunction[:{qualifier}]
+ from ministack.services import lambda_svc as _lambda_svc
if "function:" in uri:
- func_name = uri.split("function:")[-1].split("/")[0].split(":")[0]
+ # Strip wrapper up through 'function:' and any trailing /invocations.
+ tail = uri.split("function:")[-1].split("/")[0]
+ # tail is now "<name>" or "<name>:<qualifier>".
+ func_name, qualifier = _lambda_svc._resolve_name_and_qualifier(tail)
else:
- func_name = uri
+ func_name, qualifier = _lambda_svc._resolve_name_and_qualifier(uri)
qs_params = {k: v[0] for k, v in query_params.items()} if query_params else None
mv_qs_params = {k: list(v) for k, v in query_params.items()} if query_params else None
@@ -662,7 +675,7 @@ async def _invoke_lambda_proxy_v1(integration, api_id, stage_name, stage, resour
"isBase64Encoded": False,
}
- lambda_response, err = await _call_lambda(func_name, event)
+ lambda_response, err = await _call_lambda(func_name, event, qualifier=qualifier)
if err:
return 502, {"Content-Type": "application/json"}, json.dumps({"message": err}).encode()
@@ -746,8 +759,39 @@ def _invoke_mock_v1(integration):
# ---- Control plane: REST APIs ----
+def _resolve_custom_rest_api_id(tags: dict) -> tuple[str | None, tuple | None]:
+ """Return (api_id_or_None, error_response_or_None).
+
+ Reads the ministack-native ``ms-custom-id`` tag (issue #400). If the
+ LocalStack ``ls-custom-id`` tag is set (and ``ms-custom-id`` is not), the
+ caller gets a clear ``BadRequestException`` so the ministack-native key is
+ the only supported contract."""
+ if not isinstance(tags, dict):
+ return None, None
+ if "ls-custom-id" in tags and "ms-custom-id" not in tags:
+ return None, _v1_error(
+ "BadRequestException",
+ "ls-custom-id tag is not supported; use 'ms-custom-id' instead",
+ 400,
+ )
+ custom = tags.get("ms-custom-id")
+ if not custom:
+ return None, None
+ if custom in _rest_apis:
+ return None, _v1_error(
+ "ConflictException",
+ f"REST API id '{custom}' (from ms-custom-id tag) is already in use",
+ 409,
+ )
+ return str(custom), None
+
+
def _create_rest_api(data):
- api_id = _new_id()[:8]
+ tags = data.get("tags", {})
+ custom_id, err = _resolve_custom_rest_api_id(tags)
+ if err is not None:
+ return err
+ api_id = custom_id or _new_id()[:8]
api = {
"id": api_id,
"name": data.get("name", "unnamed"),
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index df267b8f..57313178 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -3581,7 +3581,9 @@ def _esm_response(esm: dict) -> dict:
def _create_esm(data: dict):
esm_id = new_uuid()
- func_name = _resolve_name(data.get("FunctionName", ""))
+ # Preserve the alias/version qualifier if the caller supplied one so
+ # poller invocations route to the correct target (#407).
+ func_name, qualifier = _resolve_name_and_qualifier(data.get("FunctionName", ""))
event_source_arn = data.get("EventSourceArn", "")
enabled = data.get("Enabled", True)
@@ -3590,8 +3592,9 @@ def _create_esm(data: dict):
esm = {
"UUID": esm_id,
"EventSourceArn": event_source_arn,
- "FunctionArn": _func_arn(func_name),
+ "FunctionArn": _func_arn(func_name) + (f":{qualifier}" if qualifier else ""),
"FunctionName": func_name,
+ "Qualifier": qualifier,
"State": "Enabled" if enabled else "Disabled",
"StateTransitionReason": "USER_INITIATED",
"BatchSize": data.get("BatchSize", 10),
@@ -3739,7 +3742,9 @@ def _poll_sqs():
continue
func_name = esm["FunctionName"]
- if func_name not in _functions:
+ qualifier = esm.get("Qualifier")
+ func_rec, _cfg = _get_func_record_for_qualifier(func_name, qualifier)
+ if func_rec is None:
continue
queue_name = source_arn.split(":")[-1]
@@ -3786,7 +3791,7 @@ def _poll_sqs():
continue
event = {"Records": records}
- result = _execute_function(_functions[func_name], event)
+ result = _execute_function(func_rec, event)
if result.get("error"):
err_body = result.get("body") or {}
@@ -3848,7 +3853,9 @@ def _poll_kinesis():
continue
func_name = esm["FunctionName"]
- if func_name not in _functions:
+ qualifier = esm.get("Qualifier")
+ func_rec, _cfg = _get_func_record_for_qualifier(func_name, qualifier)
+ if func_rec is None:
continue
stream_name = source_arn.split("/")[-1]
@@ -3920,7 +3927,7 @@ def _poll_kinesis():
continue
event = {"Records": records}
- result = _execute_function(_functions[func_name], event)
+ result = _execute_function(func_rec, event)
if result.get("error"):
err_body = result.get("body") or {}
@@ -3959,7 +3966,9 @@ def _poll_dynamodb_streams():
continue
func_name = esm["FunctionName"]
- if func_name not in _functions:
+ qualifier = esm.get("Qualifier")
+ func_rec, _cfg = _get_func_record_for_qualifier(func_name, qualifier)
+ if func_rec is None:
continue
table_arn = source_arn.split("/stream/")[0]
@@ -3991,7 +4000,7 @@ def _poll_dynamodb_streams():
continue
event = {"Records": batch}
- result = _execute_function(_functions[func_name], event)
+ result = _execute_function(func_rec, event)
if result.get("error"):
err_body = result.get("body") or {}
diff --git a/pyproject.toml b/pyproject.toml
index c517720f..1f7f085e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.3.5"
+version = "1.3.6"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index 3703a6d5..8634b6f0 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -1025,3 +1025,39 @@ def test_apigwv1_created_date_is_unix_timestamp(apigw_v1):
f"createdDate should be datetime (parsed from Unix int), got {type(created)}"
)
apigw_v1.delete_rest_api(restApiId=resp["id"])
+
+
+# ========== Custom/predictable REST API IDs via tags (issue #400) ==========
+
+def test_apigwv1_custom_id_via_ms_custom_id_tag(apigw_v1):
+ resp = apigw_v1.create_rest_api(
+ name="ms-custom-v1", tags={"ms-custom-id": "v1pinned"},
+ )
+ assert resp["id"] == "v1pinned"
+
+
+def test_apigwv1_custom_id_rejects_ls_custom_id(apigw_v1):
+ """ls-custom-id is not supported; caller must use ms-custom-id."""
+ with pytest.raises(ClientError) as exc_info:
+ apigw_v1.create_rest_api(
+ name="ls-reject-v1", tags={"ls-custom-id": "should-fail"},
+ )
+ assert exc_info.value.response["Error"]["Code"] == "BadRequestException"
+ assert "ms-custom-id" in exc_info.value.response["Error"]["Message"]
+
+
+def test_apigwv1_custom_id_duplicate_rejected(apigw_v1):
+ apigw_v1.create_rest_api(
+ name="v1-dup-1", tags={"ms-custom-id": "v1dup"},
+ )
+ with pytest.raises(ClientError) as exc_info:
+ apigw_v1.create_rest_api(
+ name="v1-dup-2", tags={"ms-custom-id": "v1dup"},
+ )
+ assert exc_info.value.response["Error"]["Code"] == "ConflictException"
+
+
+def test_apigwv1_custom_id_absent_uses_random(apigw_v1):
+ resp = apigw_v1.create_rest_api(name="v1-random")
+ # _new_id() returns up to 10 hex chars; trimmed to [:8] in _create_rest_api.
+ assert 8 <= len(resp["id"]) <= 10
diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.py
index beb8333c..b4391eb0 100644
--- a/tests/test_apigatewayv2.py
+++ b/tests/test_apigatewayv2.py
@@ -1442,3 +1442,220 @@ def test_apigwv1_path_based_restapi_legacy_user_request(apigw_v1, lam):
url = f"http://localhost:{_EXECUTE_PORT}/restapis/{api_id}/prod/_user_request_/hello"
r = urllib.request.urlopen(url, timeout=5)
assert r.status == 200
+
+
+# ========== Custom/predictable API IDs via tags (issue #400) ==========
+
+def test_apigwv2_custom_id_via_ms_custom_id_tag(apigw):
+ """ms-custom-id tag pins the apiId to the caller-supplied value."""
+ resp = apigw.create_api(
+ Name="ms-custom-id-test", ProtocolType="HTTP",
+ Tags={"ms-custom-id": "mypinnedid"},
+ )
+ assert resp["ApiId"] == "mypinnedid"
+ assert "mypinnedid.execute-api" in resp["ApiEndpoint"]
+
+
+def test_apigwv2_custom_id_rejects_ls_custom_id(apigw):
+ """ls-custom-id (LocalStack's tag) is not supported. Callers get a clear
+ BadRequestException pointing them at the ministack-native 'ms-custom-id'."""
+ with pytest.raises(ClientError) as exc_info:
+ apigw.create_api(
+ Name="ls-reject-test", ProtocolType="HTTP",
+ Tags={"ls-custom-id": "should-fail"},
+ )
+ assert exc_info.value.response["Error"]["Code"] == "BadRequestException"
+ assert "ms-custom-id" in exc_info.value.response["Error"]["Message"]
+
+
+def test_apigwv2_custom_id_duplicate_rejected(apigw):
+ """Second CreateApi with the same ms-custom-id in the same account is rejected."""
+ apigw.create_api(
+ Name="dup-1", ProtocolType="HTTP",
+ Tags={"ms-custom-id": "duplicated"},
+ )
+ with pytest.raises(ClientError) as exc_info:
+ apigw.create_api(
+ Name="dup-2", ProtocolType="HTTP",
+ Tags={"ms-custom-id": "duplicated"},
+ )
+ assert exc_info.value.response["Error"]["Code"] == "ConflictException"
+ assert exc_info.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409
+
+
+def test_apigwv2_custom_id_absent_uses_random(apigw):
+ """CreateApi without the tag continues to produce a random apiId."""
+ resp = apigw.create_api(Name="random-id", ProtocolType="HTTP")
+ assert len(resp["ApiId"]) == 8
+
+
+# ========== Lambda alias qualifier in integrationUri (issue #407) ==========
+
+def test_apigwv2_integration_uri_with_alias_qualifier_resolves_to_alias_target(apigw, lam):
+ """HTTP integration pointing at arn:...:function:<name>:<alias> must resolve
+ the alias to its target version, not try to invoke a function literally
+ named after the alias (#407)."""
+ import urllib.request
+
+ # 1) Publish a Lambda that returns a distinctive string.
+ code = """
+def handler(event, context):
+ return {'statusCode': 200, 'body': 'hello-from-alias'}
+"""
+ fn_name = f"alias-target-fn-{uuid.uuid4().hex[:6]}"
+ try:
+ lam.delete_function(FunctionName=fn_name)
+ except Exception:
+ pass
+ lam.create_function(
+ FunctionName=fn_name, Runtime="python3.12", Role=_LAMBDA_ROLE,
+ Handler="index.handler", Code={"ZipFile": _make_zip(code)}, Publish=True,
+ )
+ # Publishing on create yields version 1; create an alias pointing at it.
+ lam.create_alias(FunctionName=fn_name, Name="live", FunctionVersion="1")
+
+ # 2) Wire an HTTP API integration URI to the qualified ARN.
+ api_id = apigw.create_api(Name="alias-integ", ProtocolType="HTTP")["ApiId"]
+ qualified_arn = f"arn:aws:lambda:us-east-1:000000000000:function:{fn_name}:live"
+ integ = apigw.create_integration(
+ ApiId=api_id, IntegrationType="AWS_PROXY",
+ IntegrationUri=qualified_arn, IntegrationMethod="POST",
+ )
+ apigw.create_route(
+ ApiId=api_id, RouteKey="GET /hello",
+ Target=f"integrations/{integ['IntegrationId']}",
+ )
+ apigw.create_stage(ApiId=api_id, StageName="live")
+
+ # 3) Hit the route — before the fix this returned 502 "'live' not found".
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/live/hello"
+ req = urllib.request.Request(url)
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ r = urllib.request.urlopen(req, timeout=5)
+ assert r.status == 200
+ assert r.read() == b"hello-from-alias"
+
+
+# ========== CORS configuration respected (issue #406) ==========
+
+def _create_cors_api(apigw, *, name: str, cors: dict | None):
+ kwargs = {"Name": name, "ProtocolType": "HTTP"}
+ if cors is not None:
+ kwargs["CorsConfiguration"] = cors
+ api_id = apigw.create_api(**kwargs)["ApiId"]
+ # Default stage so execute_path parsing works at the root.
+ apigw.create_stage(ApiId=api_id, StageName="$default", AutoDeploy=True)
+ return api_id
+
+
+def test_apigwv2_cors_preflight_echoes_configured_origin(apigw):
+ """OPTIONS preflight returns allow_origin from cors_configuration, not wildcard (#406)."""
+ import urllib.request
+ api_id = _create_cors_api(apigw, name="cors-origin", cors={
+ "AllowOrigins": ["http://localhost:3000"],
+ "AllowMethods": ["GET", "POST", "OPTIONS"],
+ "AllowHeaders": ["content-type", "cookie"],
+ "AllowCredentials": True,
+ "MaxAge": 600,
+ })
+ req = urllib.request.Request(
+ f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/",
+ method="OPTIONS",
+ )
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ req.add_header("Origin", "http://localhost:3000")
+ req.add_header("Access-Control-Request-Method", "GET")
+ r = urllib.request.urlopen(req, timeout=5)
+ assert r.status == 204
+ assert r.headers["Access-Control-Allow-Origin"] == "http://localhost:3000"
+ assert r.headers["Access-Control-Allow-Credentials"] == "true"
+ assert r.headers["Access-Control-Max-Age"] == "600"
+ # methods/headers should reflect config
+ assert "GET" in r.headers["Access-Control-Allow-Methods"]
+ assert "cookie" in r.headers["Access-Control-Allow-Headers"].lower()
+
+
+def test_apigwv2_cors_preflight_denies_non_allowlisted_origin(apigw):
+ """OPTIONS from an origin not in allow_origins returns 403 with no CORS headers."""
+ import urllib.request, urllib.error
+ api_id = _create_cors_api(apigw, name="cors-deny", cors={
+ "AllowOrigins": ["http://localhost:3000"],
+ "AllowMethods": ["GET"],
+ })
+ req = urllib.request.Request(
+ f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/",
+ method="OPTIONS",
+ )
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ req.add_header("Origin", "http://evil.example.com")
+ with pytest.raises(urllib.error.HTTPError) as exc_info:
+ urllib.request.urlopen(req, timeout=5)
+ assert exc_info.value.code == 403
+
+
+def test_apigwv2_cors_preflight_403_when_no_configuration(apigw):
+ """API without CorsConfiguration returns 403 on OPTIONS (AWS default)."""
+ import urllib.request, urllib.error
+ api_id = _create_cors_api(apigw, name="no-cors", cors=None)
+ req = urllib.request.Request(
+ f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/",
+ method="OPTIONS",
+ )
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ req.add_header("Origin", "http://localhost:3000")
+ with pytest.raises(urllib.error.HTTPError) as exc_info:
+ urllib.request.urlopen(req, timeout=5)
+ assert exc_info.value.code == 403
+
+
+# ========== $default stage routing (issue #404) ==========
+
+def test_apigwv2_default_stage_serves_from_root(apigw, lam):
+ """v2 HTTP API with $default stage must route /api/hello to GET /api/hello —
+ the first segment is NOT the stage name (#404)."""
+ import urllib.request
+
+ fn_name = f"default-stage-fn-{uuid.uuid4().hex[:6]}"
+ arn = _make_fn(lam, fn_name, _ECHO_CODE)
+
+ api_id = apigw.create_api(Name="default-stage-test", ProtocolType="HTTP")["ApiId"]
+ integ = apigw.create_integration(
+ ApiId=api_id, IntegrationType="AWS_PROXY",
+ IntegrationUri=arn, IntegrationMethod="POST",
+ )
+ apigw.create_route(
+ ApiId=api_id, RouteKey="GET /api/hello",
+ Target=f"integrations/{integ['IntegrationId']}",
+ )
+ apigw.create_stage(ApiId=api_id, StageName="$default", AutoDeploy=True)
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/api/hello"
+ req = urllib.request.Request(url)
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ r = urllib.request.urlopen(req, timeout=5)
+ assert r.status == 200
+
+
+def test_apigwv2_named_stage_still_requires_prefix(apigw, lam):
+ """APIs with a named stage (not $default) still require the stage in the path."""
+ import urllib.request
+
+ fn_name = f"named-stage-fn-{uuid.uuid4().hex[:6]}"
+ arn = _make_fn(lam, fn_name, _ECHO_CODE)
+
+ api_id = apigw.create_api(Name="named-stage-test", ProtocolType="HTTP")["ApiId"]
+ integ = apigw.create_integration(
+ ApiId=api_id, IntegrationType="AWS_PROXY",
+ IntegrationUri=arn, IntegrationMethod="POST",
+ )
+ apigw.create_route(
+ ApiId=api_id, RouteKey="GET /api/hello",
+ Target=f"integrations/{integ['IntegrationId']}",
+ )
+ apigw.create_stage(ApiId=api_id, StageName="live", AutoDeploy=True)
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/live/api/hello"
+ req = urllib.request.Request(url)
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ r = urllib.request.urlopen(req, timeout=5)
+ assert r.status == 200
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 112839a1..f4f30f92 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -2106,3 +2106,55 @@ Outputs:
# And the bucket was actually created with that name.
buckets = [b["Name"] for b in s3_us2.list_buckets()["Buckets"]]
assert "rgn-test-us-east-2" in buckets
+
+
+def test_cfn_cognito_user_pool_client_generate_secret(cfn, cognito_idp):
+ """CFN AWS::Cognito::UserPoolClient with GenerateSecret=true creates a
+ ClientSecret; GenerateSecret=false/absent leaves it None (#403)."""
+ template = """
+AWSTemplateFormatVersion: '2010-09-09'
+Resources:
+ Pool:
+ Type: AWS::Cognito::UserPool
+ Properties:
+ UserPoolName: cfn-upc-secret-pool
+ ClientWithSecret:
+ Type: AWS::Cognito::UserPoolClient
+ Properties:
+ UserPoolId: !Ref Pool
+ ClientName: with-secret
+ GenerateSecret: true
+ ClientWithoutSecret:
+ Type: AWS::Cognito::UserPoolClient
+ Properties:
+ UserPoolId: !Ref Pool
+ ClientName: no-secret
+ GenerateSecret: false
+Outputs:
+ PoolId:
+ Value: !Ref Pool
+ ClientWithSecretId:
+ Value: !Ref ClientWithSecret
+ ClientWithoutSecretId:
+ Value: !Ref ClientWithoutSecret
+"""
+ stack_name = "cfn-upc-secret"
+ try:
+ cfn.delete_stack(StackName=stack_name)
+ except Exception:
+ pass
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ _wait_stack(cfn, stack_name)
+
+ stack = cfn.describe_stacks(StackName=stack_name)["Stacks"][0]
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}
+ pool_id = outputs["PoolId"]
+
+ with_resp = cognito_idp.describe_user_pool_client(
+ UserPoolId=pool_id, ClientId=outputs["ClientWithSecretId"],
+ )
+ without_resp = cognito_idp.describe_user_pool_client(
+ UserPoolId=pool_id, ClientId=outputs["ClientWithoutSecretId"],
+ )
+ assert with_resp["UserPoolClient"].get("ClientSecret"), "GenerateSecret=true should produce a non-empty ClientSecret"
+ assert not without_resp["UserPoolClient"].get("ClientSecret"), "GenerateSecret=false should leave ClientSecret empty"