From bef5eec7622ef15f5623a3b11e317473d76d2ec1 Mon Sep 17 00:00:00 2001 From: "David A. Wheeler" Date: Fri, 27 Dec 2024 12:39:13 -0500 Subject: [PATCH] Begin modifying code that removes trailing slashes Signed-off-by: David A. Wheeler --- app/controllers/projects_controller.rb | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 8f0dd2907..04a49a0ef 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -848,10 +848,28 @@ def url_anchor end # Clean up url; returns nil if given nil. + # In particular, remove trailing slashes def clean_url(url) - return url if url.nil? + return url if url.blank? + return url if url == '/' + return url if url.last != '/' + + # Remove trailing slashes. + # Attackers could make this version slow: url.gsub(%r{\/+\z}, '') + # Start from the last character and move backwards + i = url.length - 1 + + # Find the index of the last non-slash character + while i >= 0 && url[i] == '/' + i -= 1 + end - url.gsub(%r{\/+\z}, '') + # If the string was all slashes or empty, return a single slash + if i == -1 + return '/' + else + return url[0..i] + end end end # rubocop:enable Metrics/ClassLength