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
feat(apigateway): route the data plane through registered custom domains (#1533)
iot-rocketcb933c8f304b
diff --git a/ministack/app.py b/ministack/app.pyindex d4cebe9e..fced9f34 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -984,9 +984,14 @@ async def _handle_pre_body_request(method: str, path: str, headers: dict, query_"""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). A Function URL owns its- # CORS config the same way. Skip the generic wildcard preflight in both cases.+ # CORS config the same way, as does a registered custom domain. Skip the generic+ # wildcard preflight in all three cases.host = headers.get("host", "")- owns_cors = _parse_execute_api_url(host, path) is not None or _parse_lambda_url(host, path) is not None+ owns_cors = (+ _parse_execute_api_url(host, path) is not None+ or _parse_lambda_url(host, path) is not None+ or _resolve_custom_domain_request(host, path) is not None+ )for response in (None if owns_cors else _handle_options_request(method, request_id),_handle_health_request(path, request_id),@@ -1391,11 +1396,43 @@ def _resolve_stage_and_path(api_id: str, tentative_stage: str, execute_path: strreturn tentative_stage, execute_path+def _resolve_custom_domain_request(host: str, path: str):+ """Resolve a request addressed by a registered API Gateway custom domain.++ Returns ``(api_id, stage, execute_path)`` or ``None``. Runs before any+ host-pattern service guessing, so a registered domain wins even when its+ name happens to contain a service token (a domain with ``iot.`` in it+ would otherwise land in the IoT service). Unregistered dotted hosts cost+ a linear scan over the registered domain names (a local stack holds a+ handful at most) and fall through unchanged."""+ hostname = host.split(":")[0].lower()+ if not hostname or "." not in hostname:+ # localhost / in-network single-label hosts can never be custom domains+ return None+ apigw_v1 = _get_module("apigateway_v1")+ return apigw_v1.resolve_base_path_mapping(hostname, 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)."""+ """Handle API Gateway execute-api data plane requests (Host-based,+ path-based, and registered custom domains)."""parsed = _parse_execute_api_url(host, path)+ stage_from_mapping = False+ if parsed is None:+ resolved = _resolve_custom_domain_request(host, path)+ if resolved is not None:+ api_id, mapped_stage, rest = resolved+ if mapped_stage:+ parsed = resolved+ stage_from_mapping = True+ else:+ # A stage-less mapping leaves the stage to the request path:+ # the first remaining segment is the tentative stage, exactly+ # like a plain execute-api URL.+ tentative, _, remainder = rest.lstrip("/").partition("/")+ parsed = (api_id, tentative, "/" + remainder if remainder else "/")if parsed is None:return Noneapi_id, tentative_stage, execute_path = parsed@@ -1413,7 +1450,11 @@ async def _handle_execute_api_request(return await _get_module("apigateway").handle_connections_api(method, api_id, tentative_stage, connection_id, body, headers)- stage, execute_path = _resolve_stage_and_path(api_id, tentative_stage, execute_path)+ if stage_from_mapping:+ # A base-path mapping names its stage; the whole remainder is API path.+ stage = tentative_stage+ else:+ stage, execute_path = _resolve_stage_and_path(api_id, tentative_stage, execute_path)apigw_v1 = _get_module("apigateway_v1")if apigw_v1.find_api_scope(api_id) is not None:return await apigw_v1.handle_execute(diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.pyindex 86f94d18..3dfe1a78 100644--- a/ministack/services/apigateway_v1.py+++ b/ministack/services/apigateway_v1.py@@ -79,9 +79,13 @@ Data plane:owning region by API id and run the invocation in that scope.Custom domains:- REGIONAL and EDGE records are both keyed per region in MiniStack. EDGE- global name uniqueness is not enforced because MiniStack does not route- data-plane requests by custom domain host today.+ REGIONAL and EDGE records are both keyed per region in MiniStack; EDGE+ global name uniqueness is not enforced. Data-plane requests addressed by a+ registered custom domain host ARE routed: app.py resolves the Host through+ resolve_base_path_mapping() before any host-pattern guessing runs (longest+ base path wins, "(none)" or an empty base path is the root mapping, a+ mapping's stage is authoritative when set, and a stage-less mapping takes+ the stage from the remaining request path)."""import base64@@ -873,6 +877,59 @@ def find_api_scope(api_id):return None+def find_domain_scope(domain_name):+ """Return (account_id, region, stored_name) owning a custom domain within+ the ambient account.++ Host headers are case-insensitive, so the comparison lowercases both+ sides; ``stored_name`` is the exact key the control plane stored, which+ the child-store lookup needs. A data-plane request addressed by a custom+ domain carries no signed scope, so like ``find_api_scope`` this resolves+ within the ambient account. EDGE global name uniqueness across accounts+ stays unenforced (see the module docstring) — the ambient default covers+ the single-account case a local stack actually runs."""+ account_id = get_account_id()+ wanted = domain_name.lower()+ for (stored_account, region, stored_domain), _rec in _domain_names.all_items():+ if stored_account == account_id and stored_domain.lower() == wanted:+ return stored_account, region, stored_domain+ return None+++def resolve_base_path_mapping(domain_name, path):+ """Resolve ``(api_id, stage, execute_path)`` through a registered custom+ domain's base-path mappings, or ``None``.++ The longest matching base path wins; the ``"(none)"`` sentinel (or an+ explicit empty base path) is the root mapping and matches everything.+ A mapping that names a stage is authoritative — the whole remainder+ belongs to the API. A stage-less mapping returns ``""`` as the stage and+ the caller derives the stage from the returned path instead."""+ scope = find_domain_scope(domain_name)+ if scope is None:+ return None+ account_id, region, stored_name = scope+ mappings = _base_path_mappings.get_scoped(account_id, region, stored_name, {})+ best = None+ for base_path, mapping in mappings.items():+ if not base_path or base_path == "(none)":+ candidate_len, rest = 0, path+ else:+ prefix = "/" + base_path+ if path == prefix:+ candidate_len, rest = len(base_path), "/"+ elif path.startswith(prefix + "/"):+ candidate_len, rest = len(base_path), path[len(prefix):]+ else:+ continue+ if best is None or candidate_len > best[0]:+ best = (candidate_len, mapping, rest)+ if best is None:+ return None+ _, mapping, rest = best+ return mapping["restApiId"], mapping["stage"], rest or "/"++def stages_for_api(api_id):"""Return stages for api_id after resolving the v1 data-plane owner scope."""scope = find_api_scope(api_id)diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.pyindex 02485a0b..6b34a624 100644--- a/tests/test_apigatewayv1.py+++ b/tests/test_apigatewayv1.py@@ -2369,6 +2369,131 @@ def test_apigwv1_base_path_mapping_crud(apigw_v1):apigw_v1.delete_rest_api(restApiId=api_id)apigw_v1.delete_domain_name(domainName="bpm.example.com")+++def _mock_api(apigw_v1, name, path_part, body_marker, stage):+ """A deployed v1 API whose GET /<path_part> answers a fixed MOCK body."""+ api_id = apigw_v1.create_rest_api(name=name)["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=path_part+ )["id"]+ apigw_v1.put_method(+ restApiId=api_id, resourceId=resource_id, httpMethod="GET", authorizationType="NONE"+ )+ apigw_v1.put_integration(+ restApiId=api_id, resourceId=resource_id, httpMethod="GET", type="MOCK",+ integrationHttpMethod="GET", uri="",+ requestTemplates={"application/json": '{"statusCode": 200}'},+ )+ apigw_v1.put_method_response(+ restApiId=api_id, resourceId=resource_id, httpMethod="GET", statusCode="200"+ )+ apigw_v1.put_integration_response(+ restApiId=api_id, resourceId=resource_id, httpMethod="GET", statusCode="200",+ selectionPattern="", responseTemplates={"application/json": body_marker},+ )+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]+ apigw_v1.create_stage(restApiId=api_id, stageName=stage, deploymentId=dep_id)+ return api_id+++def _request_via_host(host, path):+ import urllib.error as _urlerr+ import urllib.request as _urlreq++ url = f"http://localhost:{_EXECUTE_PORT}{path}"+ req = _urlreq.Request(url, method="GET")+ req.add_header("Host", host)+ try:+ resp = _urlreq.urlopen(req)+ return resp.status, resp.read()+ except _urlerr.HTTPError as e:+ return e.code, e.read()+++def test_apigwv1_custom_domain_routes_the_data_plane(apigw_v1):+ """A request addressed by a registered custom domain routes through its+ base-path mappings: longest base path wins, "(none)" is the root mapping,+ the mapping's stage is authoritative. The domain deliberately contains+ the substring `iot.` — a registered domain must win before any+ host-pattern service guessing (an unregistered host with that substring+ lands in the IoT service)."""+ domain = "svc.iot.example.com"+ feature_api = _mock_api(apigw_v1, "v1-cd-feature", "health", '{"api": "feature"}', "prod")+ root_api = _mock_api(apigw_v1, "v1-cd-root", "status", '{"api": "root"}', "live")++ apigw_v1.create_domain_name(domainName=domain)+ apigw_v1.create_base_path_mapping(+ domainName=domain, basePath="feature", restApiId=feature_api, stage="prod"+ )+ apigw_v1.create_base_path_mapping(+ domainName=domain, restApiId=root_api, stage="live"+ )++ # Longest-prefix: /feature/... strips the base path, stage from the mapping.+ status, body = _request_via_host(domain, "/feature/health")+ assert status == 200, body+ assert b'"feature"' in body+ # Everything else falls to the root "(none)" mapping, whole path forwarded.+ # (/health would be swallowed by the emulator's own health endpoint, which+ # answers before the data-plane chain — use a non-reserved path.)+ status, body = _request_via_host(domain, "/status")+ assert status == 200, body+ assert b'"root"' in body++ # An unregistered host keeps today's fallthrough behaviour.+ status, body = _request_via_host("unregistered.example.com", "/feature/health")+ assert status != 200++ apigw_v1.delete_base_path_mapping(domainName=domain, basePath="feature")+ apigw_v1.delete_base_path_mapping(domainName=domain, basePath="(none)")+ apigw_v1.delete_domain_name(domainName=domain)+ apigw_v1.delete_rest_api(restApiId=feature_api)+ apigw_v1.delete_rest_api(restApiId=root_api)+++def test_apigwv1_custom_domain_stage_less_mapping_takes_stage_from_path(apigw_v1):+ """A base-path mapping created without a stage takes the stage from the+ first path segment after the base path, like a plain execute-api URL.+ The domain is registered with mixed case but requested lowercase — the+ Host lookup must be case-insensitive."""+ domain = "StageLess.Example.Com"+ api_id = _mock_api(apigw_v1, "v1-cd-stageless", "ping", '{"api": "stageless"}', "dev")++ apigw_v1.create_domain_name(domainName=domain)+ apigw_v1.create_base_path_mapping(domainName=domain, basePath="svc", restApiId=api_id)++ status, body = _request_via_host("stageless.example.com", "/svc/dev/ping")+ assert status == 200, body+ assert b'"stageless"' in body++ apigw_v1.delete_base_path_mapping(domainName=domain, basePath="svc")+ apigw_v1.delete_domain_name(domainName=domain)+ apigw_v1.delete_rest_api(restApiId=api_id)+++def test_apigwv1_custom_domain_empty_base_path_is_root_mapping(apigw_v1):+ """An explicit basePath of "" behaves exactly like the "(none)" sentinel:+ it is the root mapping and the whole path is forwarded to the API."""+ domain = "emptybase.example.com"+ api_id = _mock_api(apigw_v1, "v1-cd-emptybase", "status", '{"api": "emptybase"}', "live")++ apigw_v1.create_domain_name(domainName=domain)+ apigw_v1.create_base_path_mapping(+ domainName=domain, basePath="", restApiId=api_id, stage="live"+ )++ status, body = _request_via_host(domain, "/status")+ assert status == 200, body+ assert b'"emptybase"' in body++ # DeleteDomainName drops the mapping store with it — the "" base path is+ # not addressable as a URI path parameter.+ apigw_v1.delete_domain_name(domainName=domain)+ apigw_v1.delete_rest_api(restApiId=api_id)++def test_apigwv1_execute_missing_stage_404(apigw_v1):"""execute-api returns 404 when stage does not exist."""import urllib.error as _urlerr