Search code examples
ruby-on-railsjsonrackmiddlewareenv

How to intercept and rewrite damaged JSON calls with Middleware


I'm trying to find the best place to do this. My middleware looks like this :

class Fixer
  def initialize app
    @app = app
  end

  def call env
   if env["HTTP_ORIGIN"] == "https://where_i_expect_it_to_come_from.com/"
     env['rack.input'] = StringIO.new('{"yo":"momma"}') # <--  But this info is not actually written before the call is passed!
   end

   env['rack.input'].rewind
   status, headers, response = @app.call env
   return [status, headers, response]

  end
end

Rails.application.config.middleware.insert_before ActionDispatch::ParamsParser, Fixer

It seems that even when I rewrite the call here, the info is not actually rewritten properly. Any ideas how I can have my content written before its bubbled up?


Solution

  • i think this problem is the same as here: https://stackoverflow.com/questions/22712663/getting-a-routing-error-when-my-routes-are-clearly-marked and here I have a third party service that I believe is sending me malformed JSON

    from what i understand you want to fix some incoming request-data.

    as a simplified example:

    curl -X PUT -d "user[name]=something" http://localhost:3000/users/123
    

    i change something to phoet in the fixer

    class Fixer
      def initialize(app)
        @app = app
      end
    
      def call(env)
        env['rack.input'] = StringIO.new("user[name]=phoet")
        @app.call(env)
      end
    end
    

    and add it to application.rb

    config.middleware.insert_before "ActionDispatch::ParamsParser", "Fixer"
    

    when i request my app now, i see the logs

    [localhost] [fdff4eb0-8387-41] Started PUT "/users/123" for 127.0.0.1 at 2014-03-30 13:16:02 -0400
    [localhost] [fdff4eb0-8387-41] Processing by UsersController#update as */*
    [localhost] [fdff4eb0-8387-41]   Parameters: {"user"=>{"name"=>"phoet"}, "id"=>"123"}