cyu / rack-cors

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

Upgrade to rails 7.1.1 #268

Open navidemad opened 11 months ago

navidemad commented 11 months ago

Summary

We attempted an upgrade from Rails 7.0.8 to 7.1.1 and encountered CORS issues that blocked our CloudFront CDN assets.

Description

On Rails 7.0.8, our CloudFront CDN assets functioned as expected. However, after upgrading to Rails 7.1.1, CORS issues started blocking our assets. Here is the error message from the console:

Access to script at 'https://foobar.cloudfront.net/assets/public-xxxxxx.js' 
from origin 'https://www.ourwebsite.com/' has been blocked by CORS policy: 
The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.

Troubleshooting Steps

We attempted the following steps to mitigate the issue, but they were unsuccessful:

Configurations

Gemfile.lock: Rails 7.0.8 Rails 7.1.1
rack (2.2.8) rack (3.0.8)
rack-cors (2.0.1) rack-cors (2.0.1)
     rack (>= 2.0.0)   rack (>= 2.0.0)
rack-protection (3.1.0) rack-protection (3.0.6)
     rack (~> 2.2, >= 2.2.4)      rack
rack_session_access (0.2.0) rack-session (2.0.0)
     builder (>= 2.0.0)      rack (>= 3.0.0)
     rack (>= 1.0.0) rackup (2.1.0)
     rack (>= 3)
     webrick (~> 1.8)

config/initializers/cors.rb:

Rails.configuration.middleware.insert_before 0, Rack::Cors do
  allow do
    origins "*"
    resource "/assets/*", headers: :any, methods: [:get]
  end
end

config/environments/production.rb:

Rails.application.configure do
  config.public_file_server.enabled = ENV["RAILS_SERVE_STATIC_FILES"].present?
  config.public_file_server.headers = {
    "Access-Control-Allow-Origin" => "*",
    "Cache-Control" => "public, s-maxage=31536000, maxage=31536000",
    "Expires" => 1.year.from_now.to_fs(:rfc822).to_s,
  }
  config.assume_ssl = true
  config.force_ssl = true
  config.ssl_options = { hsts: { subdomains: true, preload: true, expires: 1.year } }
end

Follow-Up Questions