diff --git a/config/initializers/cors.rb b/config/initializers/cors.rb index 1ccfb542a..a1a329514 100644 --- a/config/initializers/cors.rb +++ b/config/initializers/cors.rb @@ -2,12 +2,12 @@ Rails.application.config.middleware.insert_before 0, Rack::Cors do # Allow the autocomplete API to be accessed from any GOV.UK domain, including non-production ones. - # This lets us use the API in local development "live" stacks as well as the GOV.UK Publishing - # Components guide. + # This allows autocomplete to be available on CSV previews, which are hosted on + # assets.publishing.service.gov.uk. This allows allows for local development usage. allow do - origins GovukContentSecurityPolicy::GOVUK_DOMAINS + origins %r{(www|dev|publishing\.service)\.gov\.uk\z} - resource "/api/autocomplete.json", + resource "/api/search/autocomplete*", headers: :any, methods: %i[get] end diff --git a/spec/requests/api/autocomplete_spec.rb b/spec/requests/api/autocomplete_spec.rb index ada6cd347..4ca10f49a 100644 --- a/spec/requests/api/autocomplete_spec.rb +++ b/spec/requests/api/autocomplete_spec.rb @@ -5,13 +5,14 @@ let(:suggestions) { %w[blue grey red] } let(:autocomplete_response) { instance_double(GdsApi::Response, to_hash: { suggestions: }) } + let(:params) { { q: "loving him was" } } before do allow(Services).to receive(:search_api_v2).and_return(search_api_v2) end it "returns suggestions from Search API v2" do - get "/api/search/autocomplete?q=loving+him+was" + get "/api/search/autocomplete", params: params expect(search_api_v2).to have_received(:autocomplete).with("loving him was") expect(response).to be_successful @@ -23,4 +24,31 @@ expect(response).to have_http_status(:bad_request) end + + describe "CORS headers" do + %w[https://www.gov.uk http://example.dev.gov.uk https://example.publishing.service.gov.uk].each do |allowed_host| + it "returns CORS headers for #{allowed_host}" do + get "/api/search/autocomplete", params:, headers: { Origin: allowed_host } + + expect(response.headers.to_h).to include({ + "access-control-allow-origin" => allowed_host, + "access-control-allow-methods" => "GET", + }) + end + end + + it "returns CORS headers when there is a format extension on the path" do + get "/api/search/autocomplete", params:, headers: { Origin: "https://www.gov.uk" } + + expect(response.headers) + .to include("access-control-allow-origin", "access-control-allow-methods") + end + + it "doesn't return CORS headers for an unsupported hosts" do + get "/api/search/autocomplete", params:, headers: { Origin: "https://www.gov.uk.non-govuk.com" } + + expect(response.headers) + .not_to include("access-control-allow-origin", "access-control-allow-methods") + end + end end