cyu / rack-cors

Rack Middleware for handling Cross-Origin Resource Sharing (CORS), which makes cross-origin AJAX possible.
MIT License
3.26k stars 263 forks source link

Rack cors not blocking requests with no origin header set #226

Closed bubbaspaarx closed 2 years ago

bubbaspaarx commented 3 years ago

Not sure this is a specific rack/cors gem problem or a configuration problem but we stumbled across a chrome bug that would allow a particular service to send a request without an origin header. This wouldn't be an issue normally but we noticed that our backend rails api was still allowing requests through that didn't have an origin header set.

If we made a request that did have an origin but not one of our allowed origins, it would rightfully be blocked.

Rails.application.config.middleware.insert_before(0, Rack::Cors) do
  allow do
    origins ENV['ALLOWED_REQUEST_ORIGINS'].split(',').map { |origin| origin.strip }

    resource '*', headers: :any, methods: %i[get post put patch delete options head], credentials: true
  end
end

Not sure if there's further configuration needed to prevent requests that are missing the origin header altogether

cyu commented 2 years ago

@bubbaspaarx This is currently the expected behavior with GET requests – the only time Rack::Cors actually return without allowing the app to respond is for Pre-flight OPTION requests. If you make a GET request with an invalid Origin value, it'll actually still allow that request the propagate up to the Rails stack.

If you think about it, blocking request without Origin would probably be disastrous, since a lot of API calls don't always provide that value.

bubbaspaarx commented 2 years ago

Fair. That's a good point. It turned out to be a reported Chrome bug that allowed requests to be made from the browser where an origin header should have been set but wasn't