如何通过 IP 限制 AWS Lambda 或 API 网关?

How to throttle AWS Lambda or API Gateway by IP?

我目前正在尝试使用 S3 静态网站、API 网关和 AWS Lambda 设计无服务器应用程序。我想让这个网站 public,所以每个用户没有 API 密钥。

我想防止将这些端点滥用到非常低的水平,例如给定 public IP 每 5 秒 1 个请求。

是否可以使用 AWS Shield 或在任何这些服务中?

来自AWS Announces Rate-Based Rules for AWS WAF

AWS today announced Rate-based Rules for AWS WAF. This new rule type protects customer websites and APIs from threats such as web-layer DDoS attacks, brute force login attempts and bad bots. Rate Based Rules are automatically triggered when web requests from a client exceed a certain configurable threshold.

With Rated-based Rules customers can also block future requests from a client trying to send large volume of requests to certain parts of their website like the login page. Customer can also integrate this new rule with CloudWatch Alarms and AWS Lambda to take custom action on clients making unusually high calls against their API endpoints. Customers can also use Rate-Based Rules to mitigate unwanted bots by combining the Rate-based rule with a condition to identify specific malicious user agents’ associated with bad bots.

2021 年 3 月 23 日更新:

您现在可以限制低至每 5 分钟 100 个请求!


旧答案:

不幸的是,如果您有 的要求,我想防止将这些端点滥用到非常低的水平,例如给定 public IP 每 5 秒 1 个请求。 那么AWS WAF就不合适了

您可以为基于 WAF 速率的规则设置的最小阈值是 5 分钟内 2000 个请求。

如果您想基于 IP 实施激进的基于速率的规则,您将需要编写自己的解决方案:

  • 检查 CloudFront 访问日志并追溯禁止不良 IP
  • 使用 Lambda@Edge 实时评估请求 + 相应地禁止

可能更适合您的用例的是在 API 阶段使用节流,而不是基于 IP。您可以做的是平均每秒设置最大请求数,并在超过该数字时让 API return 429,请求太多。您可以对此非常激进,或者使用十进制值更放松: