1

I'd like to do something similar to what Google/Facebook do in this post: Why does Google prepend while(1); to their JSON responses?

Adding while(1); to the beginning of script and json posts, using Rack middleware in a rails app. This way we can go back to doing ajax GET requests (which may or may not have an authentity_token or or sensitive data embedded in the response).

We also have an API which needs to not use this, so I am thinking some url matching where the middleware does not kick in.

Can anyone point me in the right direction what this code might look like? Thanks!

Community
  • 1
  • 1
Brian Armstrong
  • 19,707
  • 17
  • 115
  • 144

1 Answers1

2

There's quite a lot of questions molded into one, I think.

The middleware itself would look something(haven't checked it, but it feels right) like this:

class AntiHijackingMiddleware
 def call(env)
    status, headers, body = @app.call(env) # save initial state

    if env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest" && headers['Content-type'].to_s.include?("application/json")
        body = "while(1);"+body
        headers['Content-Length'] = Rack::Utils.bytesize(body.to_s).to_s
    end

    [status, headers, body]
 end
end

You can add additional conditions on env["REQUEST_URI"] to do url matching.

Adding it to Rails' middleware stack is boilerplate.

Anton
  • 3,006
  • 3
  • 26
  • 37
  • Makes sense, thanks! This would prepend it. The client would have to strip it also right? I saw this this example also http://blag.7tonlnu.pl/blog/2012/09/27/json-hijacking-in-rails/ but it's not clear to me how jquery would strip the while(1) for any ajax request (in addition to json). But perhaps I'm missing something? Thanks again! – Brian Armstrong Jul 24 '13 at 19:09