Rails ArgumentError: invalid %-encoding

前端 未结 2 506
一个人的身影
一个人的身影 2021-02-01 01:58

For the last month, we\'ve had a bot scraping our site regularly, leading to a bunch of ArgumentError: invalid %-encoding errors because the URLs are malformed. I\'

2条回答
  •  难免孤独
    2021-02-01 02:39

    You could inject a middleware designed to detect these and fail gracefully. The basic idea is to just try to parse the query string, and if it fails, bail out with a HTTP 400. Otherwise, just allow the request through.

    class RefuseInvalidRequest
      def initialize(app)
        @app = app
      end
    
      def call(env)
        query = Rack::Utils.parse_nested_query(env['QUERY_STRING'].to_s) rescue :bad_query
        if query == :bad_query
          [400, {'Content-Type' => 'text/plain'}, "Bad Request"]
        else
          @app.call(env)
        end
      end
    end
    

    I haven't tested this, but the concept should work.

提交回复
热议问题