将 POST 端点配置为仅响应 cron.yaml 请求



我有一个在 Elastic Beanstalk 上运行的 Django 应用程序,并希望每晚运行一个作业(搜索引擎的重新索引)。根据 AWS 文档,我可以使用 cron.yaml 在正确的时间自动向我的应用程序发出POST请求,并将我的应用程序配置为做出适当的响应。

如何确保我的应用仅响应自动生成的请求,而不响应对同一 URL 的随机请求?具体来说,我不希望恶意用户发布并导致应用程序执行操作。

您可以检查几件事以确保请求来自cron.yaml...

1)请求将来自localhost

2)User-Agent将包括aws-sqsd

3) 请求应仅由辅助角色实例处理。

我使用before_action过滤器在我的控制器中强制执行这些。代码如下所示:

##
# Protect against abuse - requests must have the correct "User-Agent" header,
# come from localhost, and will only be handled by worker instances.
before_action :correct_user_agent
before_action :correct_source
before_action :worker_instance
...controller code here...
private
##
# Confirms the correct User-Agent header was sent.
def correct_user_agent
  return if request.headers.env["HTTP_USER_AGENT"].include?("aws-sqsd")
  head(:forbidden)
end
##
# Confirms the request is coming from localhost.
def correct_source
  return if request.local? || Rails.env.development? || Rails.env.test?
  head(:forbidden)
end
##
# Don't allow requests to be processed in the production web environment, since
# it has a worker instance associated with it.
def worker_instance
  return unless Rails.env.production?
  head(:forbidden)
end

最新更新