From 5deb3596d0671365e9135292ac2040c7ef2eb1ab Mon Sep 17 00:00:00 2001 From: Richard Lynch Date: Mon, 20 Jan 2025 13:58:01 +0000 Subject: [PATCH] Block all head requests Previously we were blocking some specific head requests however rollback is triggering on head requests from email clients. We want to just return a 400 rather than generate an error. --- app/controllers/application_controller.rb | 6 ++++- config/routes.rb | 6 ++--- spec/routes/routes_spec.rb | 28 +++++++++++++++-------- 3 files changed, 25 insertions(+), 15 deletions(-) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 26b5bf83e..ea7eb84ea 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -5,7 +5,11 @@ class ApplicationController < ActionController::Base protect_from_forgery except: :handle_unwanted_requests def handle_unwanted_requests - render file: Rails.root.join("public", "404.html"), status: :not_found, layout: false + if request.head? + head :bad_request + else + render file: Rails.root.join("public", "404.html"), status: :not_found, layout: false + end end private diff --git a/config/routes.rb b/config/routes.rb index 0c055bb82..66d7fc6d8 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -196,10 +196,8 @@ def matches?(request) req.path =~ %r{^/(wordpress|wp)}i } - # 404 - misc head requests - match "*path", to: "application#handle_unwanted_requests", via: :head, constraints: lambda { |req| - req.path =~ %r{^/(backup|bc|bk|home|main|new|old)}i - } + # 400 - any head requests + match "*path", to: "application#handle_unwanted_requests", via: :head # 404 - root requests options "/", to: "application#handle_unwanted_requests" diff --git a/spec/routes/routes_spec.rb b/spec/routes/routes_spec.rb index 29e88ab5f..6516c520d 100644 --- a/spec/routes/routes_spec.rb +++ b/spec/routes/routes_spec.rb @@ -99,17 +99,25 @@ end context "misc head requests" do - it "returns a 404" do - %w[ - backup - bc - bk - home - main - new - old + before { create(:journey_configuration, :additional_payments) } + + let(:some_app_url) do + Journeys::AdditionalPaymentsForTeaching::SlugSequence.start_page_url + end + + it "returns a 400" do + [ + "backup", + "bc", + "bk", + "home", + "main", + "new", + "old", + some_app_url ].each do |path| - expect(head: path).to route_to(controller: "application", action: "handle_unwanted_requests", path: path) + expected_path = path.remove(/\A\//) + expect(head: path).to route_to(controller: "application", action: "handle_unwanted_requests", path: expected_path) end end end