From d2193616fdcd4435312e432abd4e480f225dc6f2 Mon Sep 17 00:00:00 2001 From: Javier Julio Date: Fri, 16 Aug 2024 19:50:38 -0400 Subject: [PATCH] Any unmatched route render 404 file directly We've had some errors reported by Render since spammy requests coming in (e.g. POSTing to non-existent routes) so as a last resort in the routes file, any unmatched routes, just render the default 404 error page directly to avoid raising any errors. --- app/controllers/application_controller.rb | 5 +++++ config/routes.rb | 4 +++- test/system/active_admin/route_not_found_test.rb | 9 +++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 test/system/active_admin/route_not_found_test.rb diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 09705d12..e67b209f 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,2 +1,7 @@ class ApplicationController < ActionController::Base + protect_from_forgery with: :exception + + def route_not_found + render file: Rails.public_path.join("404.html"), status: :not_found, layout: false + end end diff --git a/config/routes.rb b/config/routes.rb index 9ef53082..4426abfb 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -4,7 +4,9 @@ # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. # Can be used by load balancers and uptime monitors to verify that the app is live. - get "up" => "rails/health#show", as: :rails_health_check + get "up", to: "rails/health#show", as: :rails_health_check root to: redirect("admin") + + match "*unmatched", to: "application#route_not_found", via: :all end diff --git a/test/system/active_admin/route_not_found_test.rb b/test/system/active_admin/route_not_found_test.rb new file mode 100644 index 00000000..c5daf18d --- /dev/null +++ b/test/system/active_admin/route_not_found_test.rb @@ -0,0 +1,9 @@ +require "application_system_test_case" + +class RouteNotFoundTest < ApplicationSystemTestCase + test "visiting non-existent route renders 404 page" do + visit "/does-not-exist" + + assert_text "The page you were looking for doesn't exist." + end +end