Skip to content

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

fix(apigateway): route on the resource+method pair, not the resource alone (#1423)

iot-rocket7057b2d4c078
diff --git a/README.md b/README.md
index 0d16cd8c..06321205 100644
--- a/README.md
+++ b/README.md
@@ -431,7 +431,7 @@ subnet = ec2.create_subnet(
| **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); `$default` stage served from the URL root (no stage segment in the path); per-API `corsConfiguration` applied to preflights + dispatched responses; request parameter mapping for HTTP_PROXY (`append/overwrite/remove` for headers/querystring plus `overwrite:path`) with context variables including `$context.authorizer.jwt.claims`; JWT data-plane authorization for HTTP routes (issuer/audience/time/scope checks) and claim propagation to integrations; 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, CreateDocumentationPart, GetDocumentationPart, GetDocumentationParts, UpdateDocumentationPart, DeleteDocumentationPart, 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), non-proxy Lambda (AWS — the handler's output is the response body, mapping templates not modeled), 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; TOKEN and REQUEST Lambda authorizers on the data plane, with the returned IAM policy evaluated against each request's own method ARN and `authorizerResultTtlInSeconds` caching the policy per stage and identity source; JSON Patch for all PATCH operations; state persistence; pin `id` 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, CreateDocumentationPart, GetDocumentationPart, GetDocumentationParts, UpdateDocumentationPart, DeleteDocumentationPart, 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), non-proxy Lambda (AWS — the handler's output is the response body, mapping templates not modeled), 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; routing is on the resource+method pair, so a request the matched resource does not serve falls through to a `{proxy+}` elsewhere in the tree (a methodless intermediate, a CORS-preflight-only node, or any undeclared verb), as it does on AWS; TOKEN and REQUEST Lambda authorizers on the data plane, with the returned IAM policy evaluated against each request's own method ARN and `authorizerResultTtlInSeconds` caching the policy per stage and identity source; 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, SetSubnets, SetIpAddressType, SetSecurityGroups, 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, GenerateMac, VerifyMac, GenerateDataKey, GenerateDataKeyWithoutPlaintext, GenerateDataKeyPair, GenerateDataKeyPairWithoutPlaintext, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, UpdateKeyDescription, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags | 32 actions; CMK specs: RSA (2048/3072/4096), ECC (SECG_P256K1, NIST P-256/384/521), Edwards25519 (`ECC_NIST_EDWARDS25519` — pure Ed25519 via `ED25519_SHA_512` with `MessageType=RAW`; `ED25519_PH_SHA_512` advertised in `SigningAlgorithms` but returns `UnsupportedOperationException` until Ed25519ph lands), HMAC (`HMAC_224`/`HMAC_256`/`HMAC_384`/`HMAC_512` with `KeyUsage=GENERATE_VERIFY_MAC`), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; real RFC 2104 HMAC via `GenerateMac`/`VerifyMac` (4096-byte message cap, `KMSInvalidMacException` on mismatch, `DryRun` supported); envelope encryption, incl. asymmetric data key pairs (`KeyPairSpec` adds RSA_3072); 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, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, **KeyValueStore (mgmt)**: CreateKeyValueStore, DescribeKeyValueStore, ListKeyValueStores, UpdateKeyValueStore, DeleteKeyValueStore, **Policies**: CreateCachePolicy, GetCachePolicy, GetCachePolicyConfig, UpdateCachePolicy, DeleteCachePolicy, ListDistributionsByCachePolicyId, CreateOriginRequestPolicy, GetOriginRequestPolicy, GetOriginRequestPolicyConfig, UpdateOriginRequestPolicy, DeleteOriginRequestPolicy, ListDistributionsByOriginRequestPolicyId, CreateResponseHeadersPolicy, GetResponseHeadersPolicy, GetResponseHeadersPolicyConfig, UpdateResponseHeadersPolicy, DeleteResponseHeadersPolicy, ListDistributionsByResponseHeadersPolicyId, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin config round-trip; cache / origin request / response headers policies round-trip their full config with `ETag` / `If-Match` optimistic concurrency; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; **CloudFront Functions** are API stubs (in-memory code + DEVELOPMENT/LIVE ETags for Terraform `aws_cloudfront_function`) with `KeyValueStoreAssociations` round-tripped — no `TestFunction`, no viewer-request JS execution at the edge; `UpdateFunction` clears the emulated LIVE stage until `PublishFunction` runs again |
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 85e8fb76..eef75f6f 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -617,6 +617,60 @@ def _match_recursive(resources, parent_id, segments, params):
return None, params
+def _match_greedy_fallback(api_id, segments, http_method):
+ """Fallback for a path-matched resource that does not serve this verb.
+
+ API Gateway resolves on the resource+method pair. A resource only keeps the
+ request when it declares the verb being asked for; otherwise the request
+ falls through to a greedy `{proxy+}` elsewhere in the tree. Measured on real
+ AWS, all three of these fall through: a node with no methods at all (`/jobs`,
+ existing only as the parent of `/jobs/{operation_type}`), a node carrying
+ only a CORS `OPTIONS` preflight, and a node declaring some other verb.
+
+ That includes the case where the sibling's declared method is guarded: an
+ open root `{proxy+} ANY` does serve `GET /admin` while `/admin POST` is
+ `AWS_IAM`-protected, because routing happens before authorization. It reads
+ like an auth bypass and it is worth knowing about, but it is what the
+ service does, so it is what this emulates.
+
+ Finds the most specific `{proxy+}` resource whose parent path is a prefix
+ of the request path AND that defines the method (or ANY) — which may be a
+ sibling of the methodless node, not only an ancestor. Literal prefix
+ segments must match exactly; `{param}` prefix segments capture. Returns
+ ``(resource, path_params)`` or ``(None, None)`` — callers keep their
+ existing rejection when nothing can serve the method.
+ """
+ resources = _resources.get(api_id, {})
+ best = None
+ for res in resources.values():
+ part = res.get("pathPart", "")
+ if not (part.startswith("{") and part.endswith("+}")):
+ continue
+ methods = res.get("resourceMethods") or {}
+ if http_method not in methods and "ANY" not in methods:
+ continue
+ prefix = [s for s in res.get("path", "").strip("/").split("/")[:-1] if s]
+ # {proxy+} must consume at least one segment.
+ if len(prefix) >= len(segments):
+ continue
+ params = {}
+ matched = True
+ for want, got in zip(prefix, segments):
+ if want.startswith("{") and want.endswith("}") and not want.endswith("+}"):
+ params[want[1:-1]] = got
+ elif want != got:
+ matched = False
+ break
+ if not matched:
+ continue
+ params[part[1:-2]] = "/".join(segments[len(prefix):])
+ if best is None or len(prefix) > best[0]:
+ best = (len(prefix), res, params)
+ if best is None:
+ return None, None
+ return best[1], best[2]
+
+
def _extract_lambda_ref_from_integration_uri(uri: str) -> str:
"""Pull the Lambda reference out of an integration URI.
@@ -1596,11 +1650,20 @@ async def _handle_execute_in_scope(
resource_methods = resource.get("resourceMethods", {})
method_obj = resource_methods.get(method) or resource_methods.get("ANY")
if not method_obj:
- # A matched resource with no method for this verb — including a
- # methodless intermediate node (e.g. `/jobs` created only as the parent
- # of `/jobs/{op}`) — is an "unsupported method" in API Gateway, which
- # answers 403 MISSING_AUTHENTICATION_TOKEN (not 405, and it does not
- # fall through to a {proxy+} sibling: the specific resource wins).
+ # The path matched a resource, but that resource does not serve this
+ # verb. API Gateway routes on the resource+method PAIR, so the request
+ # falls through to a `{proxy+}` elsewhere in the tree; only an exact
+ # match keeps the request on the specific resource. Measured against
+ # real AWS (see this commit's message): a node with no methods at all,
+ # a node carrying only an `OPTIONS` preflight, and a node declaring a
+ # different verb all fall through.
+ fb_resource, fb_params = _match_greedy_fallback(api_id, segments, method)
+ if fb_resource is not None:
+ resource, path_params = fb_resource, fb_params
+ resource_methods = resource.get("resourceMethods", {})
+ method_obj = resource_methods.get(method) or resource_methods.get("ANY")
+ if not method_obj:
+ # Nothing in the tree serves this verb for this path.
return _gw_error(403, "Missing Authentication Token")
integration = method_obj.get("methodIntegration")
diff --git a/tests/conftest.py b/tests/conftest.py
index 51fac482..edbf97ed 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -114,6 +114,11 @@ _SERIAL_TESTS = {
"tests/test_apigatewayv2.py::test_apigwv2_authorizer_simple_response_non_boolean_is_500",
"tests/test_apigatewayv2.py::test_apigwv2_authorizer_unparsable_ttl_falls_back_to_the_default",
"tests/test_apigatewayv2.py::test_apigwv2_authorizer_without_identity_source_does_not_cache",
+ # {proxy+} fallthrough tests: each request cold-starts a Lambda (the bypass
+ # test wires three), with the same cold-start-under-xdist flakiness as the
+ # apigw tests above.
+ "tests/test_apigatewayv1.py::test_apigwv1_methodless_resource_falls_through_to_proxy",
+ "tests/test_apigatewayv1.py::test_apigwv1_proxy_fallthrough_cannot_bypass_a_guarded_sibling",
# AppSync Lambda-resolver event-shape tests cold-start Lambdas under a 10s
# urlopen timeout (Test 6 spawns two functions). Same cold-start-under-xdist
# flakiness as the apigw Lambda tests above — run them in the serial phase.
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index 41bed876..02485a0b 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -3442,6 +3442,25 @@ def _auth_make_lambda(lam, label, code):
return fname
+# ---- Data plane: {proxy+} fallthrough from a methodless intermediate node ----
+
+
+def _proxy_fb_make_lambda(lam, label, code):
+ fname = f"v1-proxyfb-{label}-{_uuid_mod.uuid4().hex[:8]}"
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", code)
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler",
+ Timeout=30,
+ Code={"ZipFile": buf.getvalue()},
+ )
+ return fname
+
+
def _auth_drop_lambda(lam, fname):
try:
lam.delete_function(FunctionName=fname)
@@ -3463,6 +3482,13 @@ def _auth_lambda_uri(fname):
)
+def _proxy_fb_uri(fname):
+ return (
+ "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/"
+ f"arn:aws:lambda:us-east-1:000000000000:function:{fname}/invocations"
+ )
+
+
def _auth_token_authorizer_code(qname):
"""TOKEN authorizer: Allow for `allow*` tokens, Deny otherwise.
@@ -3503,6 +3529,19 @@ def _auth_http(url, method="GET", headers=None, timeout=30):
return resp.status, resp.read()
except _urlerr.HTTPError as e:
return e.code, e.read()
+def _proxy_fb_http(url, method="GET", headers=None, timeout=30):
+ """(status, body_bytes) without raising on 4xx/5xx."""
+ import urllib.error as _urlerr
+ import urllib.request as _urlreq
+
+ req = _urlreq.Request(url, method=method)
+ for k, v in (headers or {}).items():
+ req.add_header(k, v)
+ try:
+ resp = _urlreq.urlopen(req, timeout=timeout)
+ return resp.status, resp.read()
+ except _urlerr.HTTPError as e:
+ return e.code, e.read()
def _auth_root_id(apigw_v1, api_id):
@@ -3798,3 +3837,219 @@ def test_apigwv1_authorizer_cache_is_bounded():
finally:
cache.clear()
cache.update(saved)
+def _proxy_fb_wire(apigw_v1, api_id, resource_id, http_method, backend, **method_kwargs):
+ apigw_v1.put_method(
+ restApiId=api_id, resourceId=resource_id, httpMethod=http_method,
+ **method_kwargs,
+ )
+ apigw_v1.put_integration(
+ restApiId=api_id, resourceId=resource_id, httpMethod=http_method,
+ type="AWS_PROXY", integrationHttpMethod="POST", uri=_proxy_fb_uri(backend),
+ )
+
+
+def _proxy_fb_drop_lambda(lam, fname):
+ try:
+ lam.delete_function(FunctionName=fname)
+ except ClientError:
+ pass
+
+
+def _proxy_fb_drop_api(apigw_v1, api_id):
+ try:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ except ClientError:
+ pass
+
+
+def test_apigwv1_methodless_resource_falls_through_to_proxy(apigw_v1, lam):
+ """A path-matched resource that does not serve the requested verb falls
+ through to a `{proxy+}` elsewhere in the tree instead of failing the
+ request. That covers an implicit intermediate node like `/jobs`, which
+ exists only as the parent of `/jobs/{operation_type}`.
+
+ Measured against real API Gateway (eu-central-1, MOCK integrations): only an
+ exact resource+method match keeps a request on the specific resource."""
+ proxy_backend = _proxy_fb_make_lambda(
+ lam, "prx",
+ "def handler(event, context):\n"
+ " return {'statusCode': 200,\n"
+ " 'body': 'via-proxy:' + event['pathParameters']['proxy']}\n",
+ )
+ jobs_backend = _proxy_fb_make_lambda(
+ lam, "job",
+ "def handler(event, context):\n"
+ " return {'statusCode': 200,\n"
+ " 'body': 'job:' + event['pathParameters']['operation_type']}\n",
+ )
+ api_id = apigw_v1.create_rest_api(name=f"v1-proxyfb-{_uuid_mod.uuid4().hex[:6]}")["id"]
+ try:
+ root_id = next(
+ r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"]
+ if r["path"] == "/"
+ )
+ proxy_id = apigw_v1.create_resource(
+ restApiId=api_id, parentId=root_id, pathPart="{proxy+}"
+ )["id"]
+ _proxy_fb_wire(apigw_v1, api_id, proxy_id, "ANY", proxy_backend,
+ authorizationType="NONE")
+ jobs_id = apigw_v1.create_resource(
+ restApiId=api_id, parentId=root_id, pathPart="jobs"
+ )["id"]
+ op_id = apigw_v1.create_resource(
+ restApiId=api_id, parentId=jobs_id, pathPart="{operation_type}"
+ )["id"]
+ _proxy_fb_wire(apigw_v1, api_id, op_id, "GET", jobs_backend,
+ authorizationType="NONE")
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="test", deploymentId=dep_id)
+
+ base = f"http://localhost:{_EXECUTE_PORT}/_aws/execute-api/{api_id}/test"
+
+ # The specific resource still wins where it serves the verb.
+ assert _proxy_fb_http(f"{base}/jobs/reboot") == (200, b"job:reboot")
+
+ # /jobs itself declares no methods -> the sibling {proxy+} serves it.
+ assert _proxy_fb_http(f"{base}/jobs", method="POST") == (200, b"via-proxy:jobs")
+ assert _proxy_fb_http(f"{base}/jobs") == (200, b"via-proxy:jobs")
+
+ # /jobs/{operation_type} declares GET only, so POST does not match it
+ # either and lands on the proxy as well. Measured on real AWS: routing
+ # is on the resource+method pair, not on the resource alone.
+ assert _proxy_fb_http(f"{base}/jobs/reboot", method="POST") == (
+ 200, b"via-proxy:jobs/reboot")
+ finally:
+ _proxy_fb_drop_api(apigw_v1, api_id)
+ _proxy_fb_drop_lambda(lam, proxy_backend)
+ _proxy_fb_drop_lambda(lam, jobs_backend)
+
+
+def test_apigwv1_proxy_fallthrough_reaches_past_a_guarded_sibling(apigw_v1, lam):
+ """A guarded sibling method does not stop the fallthrough, because routing
+ happens before authorization: an open root `{proxy+} ANY` alongside a
+ protected `/admin POST` serves `GET /admin` from the unauthenticated proxy.
+
+ This reads like an auth bypass, so it was measured rather than assumed. On
+ real API Gateway (eu-central-1), with `/admin POST` at `AWS_IAM` and an open
+ `{proxy+} ANY`, an unsigned `GET /admin` answered 200 from the proxy. The
+ guarded verb itself stays guarded; it is the verbs the resource does not
+ declare that leave it. Protecting a path therefore means protecting every
+ method on it, or not putting an open `{proxy+}` above it."""
+ proxy_backend = _proxy_fb_make_lambda(
+ lam, "openprx",
+ "def handler(event, context):\n"
+ " return {'statusCode': 200,\n"
+ " 'body': 'via-proxy:' + event['pathParameters']['proxy']}\n",
+ )
+ admin_backend = _proxy_fb_make_lambda(
+ lam, "admin",
+ "def handler(event, context):\n"
+ " return {'statusCode': 200, 'body': 'admin-secret'}\n",
+ )
+ authz = _proxy_fb_make_lambda(
+ lam, "denyall",
+ "def handler(event, context):\n"
+ " return {'principalId': 'p',\n"
+ " 'policyDocument': {'Version': '2012-10-17', 'Statement': [\n"
+ " {'Action': 'execute-api:Invoke', 'Effect': 'Deny',\n"
+ " 'Resource': event['methodArn']}]}}\n",
+ )
+ api_id = apigw_v1.create_rest_api(name=f"v1-proxyfb-{_uuid_mod.uuid4().hex[:6]}")["id"]
+ try:
+ root_id = next(
+ r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"]
+ if r["path"] == "/"
+ )
+ proxy_id = apigw_v1.create_resource(
+ restApiId=api_id, parentId=root_id, pathPart="{proxy+}"
+ )["id"]
+ _proxy_fb_wire(apigw_v1, api_id, proxy_id, "ANY", proxy_backend,
+ authorizationType="NONE")
+ admin_id = apigw_v1.create_resource(
+ restApiId=api_id, parentId=root_id, pathPart="admin"
+ )["id"]
+ auth_id = apigw_v1.create_authorizer(
+ restApiId=api_id, name="denyall", type="TOKEN",
+ authorizerUri=_proxy_fb_uri(authz), authorizerResultTtlInSeconds=0,
+ )["id"]
+ _proxy_fb_wire(apigw_v1, api_id, admin_id, "POST", admin_backend,
+ authorizationType="CUSTOM", authorizerId=auth_id)
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="test", deploymentId=dep_id)
+
+ base = f"http://localhost:{_EXECUTE_PORT}/_aws/execute-api/{api_id}/test"
+
+ # The guarded verb is enforced by the authorizer.
+ status, body = _proxy_fb_http(f"{base}/admin", method="POST",
+ headers={"Authorization": "t"})
+ assert status == 403
+ assert b"admin-secret" not in body
+
+ # /admin declares POST only, so every other verb leaves the resource and
+ # lands on the open proxy — authorization on the sibling method does not
+ # hold the path. Verified against real AWS before pinning it here.
+ for verb in ("GET", "DELETE"):
+ assert _proxy_fb_http(f"{base}/admin", method=verb) == (
+ 200, b"via-proxy:admin"), f"{verb} /admin did not reach the proxy"
+
+ # The proxy still serves paths that are genuinely its own.
+ assert _proxy_fb_http(f"{base}/public/thing") == (200, b"via-proxy:public/thing")
+ finally:
+ _proxy_fb_drop_api(apigw_v1, api_id)
+ _proxy_fb_drop_lambda(lam, proxy_backend)
+ _proxy_fb_drop_lambda(lam, admin_backend)
+ _proxy_fb_drop_lambda(lam, authz)
+
+
+def test_apigwv1_cors_preflight_only_resource_falls_through(apigw_v1, lam):
+ """The shape real deployments actually have: an intermediate that carries a
+ CORS `OPTIONS` preflight and nothing else.
+
+ CDK and Serverless both add that preflight, so the intermediate is never
+ method-less in practice — it simply does not serve the verb being asked
+ for. Real AWS falls through here too (measured, eu-central-1), which is why
+ the fallthrough triggers on "does not serve this verb" rather than on "has
+ no methods": the narrower rule would miss every API we deploy."""
+ proxy_backend = _proxy_fb_make_lambda(
+ lam, "corsprx",
+ "def handler(event, context):\n"
+ " return {'statusCode': 200,\n"
+ " 'body': 'via-proxy:' + event['pathParameters']['proxy']}\n",
+ )
+ preflight_backend = _proxy_fb_make_lambda(
+ lam, "corspre",
+ "def handler(event, context):\n"
+ " return {'statusCode': 200, 'body': 'preflight'}\n",
+ )
+ api_id = apigw_v1.create_rest_api(name=f"v1-proxyfb-{_uuid_mod.uuid4().hex[:6]}")["id"]
+ try:
+ root_id = next(
+ r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"]
+ if r["path"] == "/"
+ )
+ proxy_id = apigw_v1.create_resource(
+ restApiId=api_id, parentId=root_id, pathPart="{proxy+}"
+ )["id"]
+ _proxy_fb_wire(apigw_v1, api_id, proxy_id, "ANY", proxy_backend,
+ authorizationType="NONE")
+ cors_id = apigw_v1.create_resource(
+ restApiId=api_id, parentId=root_id, pathPart="remote_connection"
+ )["id"]
+ _proxy_fb_wire(apigw_v1, api_id, cors_id, "OPTIONS", preflight_backend,
+ authorizationType="NONE")
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="test", deploymentId=dep_id)
+
+ base = f"http://localhost:{_EXECUTE_PORT}/_aws/execute-api/{api_id}/test"
+
+ # OPTIONS is declared, so it stays on the resource.
+ assert _proxy_fb_http(f"{base}/remote_connection", method="OPTIONS") == (
+ 200, b"preflight")
+
+ # GET is not, so it falls through to the sibling proxy.
+ assert _proxy_fb_http(f"{base}/remote_connection") == (
+ 200, b"via-proxy:remote_connection")
+ finally:
+ _proxy_fb_drop_api(apigw_v1, api_id)
+ _proxy_fb_drop_lambda(lam, proxy_backend)
+ _proxy_fb_drop_lambda(lam, preflight_backend)