1

从 rack-attack 6.3.1 升级到 6.5.0 时,请求对象无法获取任何自定义方法

当我运行 request.comment 时,它会引发以下错误

#Hash:0x00007fd2b4f41530 的未定义方法“注释”

根据文档,我将方法从 throttled_callback 更新为 throttled_response

Rack::Attack.throttled_response = lambda do |request|
  details = {restriction: {name: 'asdas', comment: request.comment}}

  
  if Feature.enabled?(:some_feature)
    restrict_user(request.token, details) if request.update_password?
  end
end


I have added a lot of method but now after upgradating unable to access any of the method inside the throttled_callback

class Rack::Attack
  class Request < ::Rack::Request
    ##
    ## Helper Functions
    ##
    # Get the real IP Address of the user/client
    attr_accessor :comment

    def remote_ip
      @remote_ip ||= get_header('HTTP_X_FORWARDED_FOR').try(:to_s)
    end

    def body_params
      unless @body_params 
        @body_params = JSON.parse(body.read)
        body.rewind
      end
      @body_params
    end

    def username
      (body_params["username"]).to_s.downcase
    end

    def login?
      self.path == '/user_sign_in'
    end
end

throttle("ip:user-key-min", limit: 10, period: 1.minute) do |req|
  if req.login?
    req.comment = "some comment"
    req.remote_ip
  end
end

当我在throttled_response 内时。因此,升级到最新版本的 rack-attack 后,请求对象无法访问Request < ::Rack::Request类中的注释或任何方法。在 request 对象的 6.3.1 版本中,我能够从throttled_callback 内的类 Request < ::Rack::Request访问该方法

request.methods
[ :comment, :username, , :comment=, :body_params, :remote_ip, :login?]
4

1 回答 1

-1

的实现与throttled_response的实现不完全相同throttled_callback。请求对象是可访问的,throttled_callback因此您可以访问所有方法,但throttled_response传递 env 对象。

请参阅此处的throttled_response实施

Rack::Attack.throttled_response = lambda do |env|
  # NB: you have access to the name and other data about the matched throttle
  #  env['rack.attack.matched'],
  #  env['rack.attack.match_type'],
  #  env['rack.attack.match_data'],
  #  env['rack.attack.match_discriminator']

  # Using 503 because it may make attacker think that they have successfully
  # DOSed the site. Rack::Attack returns 429 for throttling by default
  [ 503, {}, ["Server Error\n"]]
end
于 2021-09-26T12:47:28.493 回答