Skip to content

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

fix(apigateway): apply usage plan throttle limits and answer TooManyRequestsException (#1928)

iot-rocket402c988835a3
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 91894265..d59fff58 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -222,6 +222,7 @@ _GATEWAY_RESPONSE_ERROR_TYPES = {
"AUTHORIZER_FAILURE": "AuthorizerConfigurationException",
"AUTHORIZER_CONFIGURATION_ERROR": "AuthorizerConfigurationException",
"API_CONFIGURATION_ERROR": "InternalServerErrorException",
+ "THROTTLED": "TooManyRequestsException",
}
_GATEWAY_TEMPLATE_VARIABLE = re.compile(
@@ -2089,27 +2090,45 @@ def _method_throttle_settings(stage, resource_path, http_method):
return None
-def _check_throttle(stage, api_id, stage_name, resource_path, http_method):
- """Token bucket per method: rate refills, burst caps, 0/0 refuses all."""
- entry = _method_throttle_settings(stage, resource_path, http_method)
- if entry is None:
- return None
- rate = entry.get("throttlingRateLimit")
- burst = entry.get("throttlingBurstLimit")
+def _take_token(slot, limits):
+ """Token bucket per slot: rate refills, burst caps, 0/0 refuses all."""
+ rate = limits.get("rateLimit")
+ burst = limits.get("burstLimit")
if rate is None and burst is None:
- return None
- rate = float(rate if rate is not None else 0)
- burst = float(burst if burst is not None else 0)
+ return True
+ rate = float(rate or 0)
+ burst = float(burst or 0)
if rate <= 0 and burst <= 0:
- return _gw_error("THROTTLED", _GATEWAY_ERROR_MESSAGES["THROTTLED"])
- slot = (api_id, stage_name, resource_path, http_method)
+ return False
now = time.time()
tokens, last = _throttle_state.get(slot, (burst, now))
tokens = min(burst, tokens + (now - last) * rate)
if tokens < 1:
_throttle_state[slot] = (tokens, now)
- return _gw_error("THROTTLED", _GATEWAY_ERROR_MESSAGES["THROTTLED"])
+ return False
_throttle_state[slot] = (tokens - 1, now)
+ return True
+
+
+def _check_throttle(stage, api_id, stage_name, resource_path, http_method, key):
+ """Usage-plan limits for the caller's key, then the stage method limit."""
+ buckets = []
+ if key is not None:
+ for plan_id, plan, entry in _usage_plans_for_key(key["id"], api_id, stage_name):
+ buckets.append((("plan", plan_id, key["id"]), plan.get("throttle") or {}))
+ method_limits = (entry.get("throttle") or {}).get(f"{resource_path}/{http_method}")
+ if method_limits:
+ buckets.append((("plan", plan_id, key["id"], api_id, stage_name, resource_path,
+ http_method), method_limits))
+ entry = _method_throttle_settings(stage, resource_path, http_method)
+ if entry is not None:
+ buckets.append((("stage", api_id, stage_name, resource_path, http_method), {
+ "rateLimit": entry.get("throttlingRateLimit"),
+ "burstLimit": entry.get("throttlingBurstLimit"),
+ }))
+ for slot, limits in buckets:
+ if not _take_token(slot, limits):
+ return _gw_error("THROTTLED", _GATEWAY_ERROR_MESSAGES["THROTTLED"])
return None
@@ -2333,7 +2352,8 @@ async def _execute_in_scope(
if key_error is not None:
return key_error
throttle_error = _check_throttle(
- stage, api_id, stage_name, resource["path"], method)
+ stage, api_id, stage_name, resource["path"], method,
+ api_key or _resolve_api_key(_api_key_from_request(headers)))
if throttle_error is not None:
return throttle_error
quota_error = _check_quota(api_key, api_id, stage_name)
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index ea5035b2..0d5cde25 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -4951,7 +4951,7 @@ def test_apigwv1_usage_plan_quota_is_enforced_per_key(apigw_v1):
def test_apigwv1_method_and_stage_throttling_answer_429(apigw_v1):
- """A 0/0 limit refuses everything; a real limit does not."""
+ """A 0/0 limit refuses everything with TooManyRequestsException; a real limit does not."""
api_id, root = _gw_api(apigw_v1, f"gwthr-{_uuid_mod.uuid4().hex[:8]}")
try:
resource = apigw_v1.create_resource(restApiId=api_id, parentId=root,
@@ -4970,6 +4970,8 @@ def test_apigwv1_method_and_stage_throttling_answer_429(apigw_v1):
throttle("/~1thr/GET", 0, 0)
assert _stage_call(api_id, "/thr") == (429, '{"message":"Too Many Requests"}')
+ assert _gwresp_call(api_id, "thr", stage="p")[1].get(
+ "x-amzn-errortype") == "TooManyRequestsException"
throttle("/~1thr/GET", 100, 50)
assert _stage_call(api_id, "/thr") == (200, '{"ok":true}')
apigw_v1.update_stage(restApiId=api_id, stageName="p", patchOperations=[
@@ -4980,6 +4982,97 @@ def test_apigwv1_method_and_stage_throttling_answer_429(apigw_v1):
apigw_v1.delete_rest_api(restApiId=api_id)
+def _plan_key(apigw_v1, api_id, **plan_kwargs):
+ """The value of a new key in a new usage plan on stage p."""
+ key = apigw_v1.create_api_key(name=f"k-{_uuid_mod.uuid4().hex[:6]}", enabled=True)
+ stage = {"apiId": api_id, "stage": "p"}
+ if "method_throttle" in plan_kwargs:
+ stage["throttle"] = plan_kwargs.pop("method_throttle")
+ plan = apigw_v1.create_usage_plan(name=f"p-{_uuid_mod.uuid4().hex[:6]}",
+ apiStages=[stage], **plan_kwargs)["id"]
+ apigw_v1.create_usage_plan_key(usagePlanId=plan, keyId=key["id"], keyType="API_KEY")
+ return [("x-api-key", key["value"])]
+
+
+def test_apigwv1_usage_plan_throttle_answers_429(apigw_v1):
+ """The plan limit applies to every method the key calls, stage limits too."""
+ api_id, root = _gw_api(apigw_v1, f"gwplthr-{_uuid_mod.uuid4().hex[:8]}")
+ try:
+ for part, required in (("a", True), ("open", False)):
+ resource = apigw_v1.create_resource(restApiId=api_id, parentId=root,
+ pathPart=part)["id"]
+ _mock_method(apigw_v1, api_id, resource, "GET", apiKeyRequired=required)
+ apigw_v1.create_deployment(restApiId=api_id, stageName="p")
+ apigw_v1.update_stage(restApiId=api_id, stageName="p", patchOperations=[
+ {"op": "replace", "path": "/*/*/throttling/rateLimit", "value": "1000"},
+ {"op": "replace", "path": "/*/*/throttling/burstLimit", "value": "500"},
+ ])
+ closed = _plan_key(apigw_v1, api_id, throttle={"rateLimit": 0, "burstLimit": 0})
+ tiny = _plan_key(apigw_v1, api_id, throttle={"rateLimit": 0.01, "burstLimit": 1})
+ free = _plan_key(apigw_v1, api_id)
+ throttled = (429, '{"message":"Too Many Requests"}')
+
+ assert _stage_call(api_id, "/a", headers=closed) == throttled
+ assert _stage_call(api_id, "/open", headers=closed) == throttled
+ assert _stage_call(api_id, "/open") == (200, '{"ok":true}')
+ assert _stage_call(api_id, "/a", headers=free) == (200, '{"ok":true}')
+ assert _stage_call(api_id, "/a", headers=tiny) == (200, '{"ok":true}')
+ assert _stage_call(api_id, "/open", headers=tiny) == throttled
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_usage_plan_method_throttle_adds_to_the_plan_limit(apigw_v1):
+ """A per-method plan limit throttles that method and never lifts the plan limit."""
+ api_id, root = _gw_api(apigw_v1, f"gwplmthr-{_uuid_mod.uuid4().hex[:8]}")
+ try:
+ for part in ("a", "b"):
+ resource = apigw_v1.create_resource(restApiId=api_id, parentId=root,
+ pathPart=part)["id"]
+ _mock_method(apigw_v1, api_id, resource, "GET", apiKeyRequired=True)
+ apigw_v1.create_deployment(restApiId=api_id, stageName="p")
+ closed_a = _plan_key(apigw_v1, api_id,
+ throttle={"rateLimit": 1000, "burstLimit": 500},
+ method_throttle={"/a/GET": {"rateLimit": 0, "burstLimit": 0}})
+ open_a = _plan_key(apigw_v1, api_id,
+ throttle={"rateLimit": 0, "burstLimit": 0},
+ method_throttle={"/a/GET": {"rateLimit": 1000, "burstLimit": 500}})
+ throttled = (429, '{"message":"Too Many Requests"}')
+
+ assert _stage_call(api_id, "/a", headers=closed_a) == throttled
+ assert _stage_call(api_id, "/b", headers=closed_a) == (200, '{"ok":true}')
+ assert _stage_call(api_id, "/a", headers=open_a) == throttled
+ assert _stage_call(api_id, "/b", headers=open_a) == throttled
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_usage_plan_method_throttle_is_per_api_stage(apigw_v1):
+ """The same method on two API stages of one plan has two buckets."""
+ apis = [_gw_api(apigw_v1, f"gwplstg-{_uuid_mod.uuid4().hex[:8]}") for _ in range(2)]
+ try:
+ for api_id, root in apis:
+ resource = apigw_v1.create_resource(restApiId=api_id, parentId=root,
+ pathPart="a")["id"]
+ _mock_method(apigw_v1, api_id, resource, "GET", apiKeyRequired=True)
+ apigw_v1.create_deployment(restApiId=api_id, stageName="p")
+ key = apigw_v1.create_api_key(name=f"k-{_uuid_mod.uuid4().hex[:6]}", enabled=True)
+ limits = {"/a/GET": {"rateLimit": 0.01, "burstLimit": 1}}
+ plan = apigw_v1.create_usage_plan(
+ name=f"p-{_uuid_mod.uuid4().hex[:6]}",
+ apiStages=[{"apiId": api_id, "stage": "p", "throttle": limits} for api_id, _ in apis])["id"]
+ apigw_v1.create_usage_plan_key(usagePlanId=plan, keyId=key["id"], keyType="API_KEY")
+ headers = [("x-api-key", key["value"])]
+ first, second = (api_id for api_id, _ in apis)
+
+ assert _stage_call(first, "/a", headers=headers) == (200, '{"ok":true}')
+ assert _stage_call(second, "/a", headers=headers) == (200, '{"ok":true}')
+ assert _stage_call(first, "/a", headers=headers) == (429, '{"message":"Too Many Requests"}')
+ finally:
+ for api_id, _ in apis:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
def test_apigwv1_request_validator_checks_parameters_and_body(apigw_v1):
"""BAD_REQUEST_PARAMETERS and BAD_REQUEST_BODY."""
api_id, root = _gw_api(apigw_v1, f"gwval-{_uuid_mod.uuid4().hex[:8]}")