PUT/POST request throttle Rack attack redirect not working

1.1k Views Asked by At

So I have a form that makes XHR to external api on to get token and then submit to url which calls our db at "/update" on our backend. We are trying to limit number of requests a person can make using the form by using a rack attack throttle. So that when a limit is reached for example after two attempts the third should give a 429 error and then redirect to our page /429. I have this so far:

throttle '/update', {
    limit: 2,
    period: 60
  } do |req|
    next nil unless req.path == '/update' && req.put?

    req.ip
  end

Then for our throttle response we are doing:

Rack::Attack.throttled_response = lambda do |env|
headers = {
        'Location' => '/429'
      }
      [302, headers]
  end

The code does work and returns a 429 but the redirect doesn't happen even though we have Location in the headers. Also we have an endpoint where we do a GET and the same response redirects the user to /429 successfully.

So how to redirect the user when making a put or post request with Rack Attack ruby on rails library? Is there another way to redirect the user? Any help would be appreciated.

1

There are 1 best solutions below

2
On

The problem is with the HTTP response status code. If you want the browser to redirect you need to use one of the 3XX status.

# frozen_string_literal: true

module Rack
  class Attack
    throttle('test', limit: 1, period: 60.seconds) do |req|
      true
    end
  end

  # response
  Rack::Attack.throttled_response = lambda do |env|
    headers = {
        'Location' => '/test_redirect'
    }
    [301, headers, []]
  end
end