A platform for community discussion. Free, open, simple.
FIX: Avoid `?tl=<default>` duplicates of plain crawler URLs (#45146)
Arpit Jalan9e0f60a92931
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rbindex edf4bc1f45a..a6504c9cee0 100644--- a/app/controllers/application_controller.rb+++ b/app/controllers/application_controller.rb@@ -84,6 +84,16 @@ class ApplicationController < ActionController::Baseendhelper_method :use_crawler_layout?+ # Kept in the env so that Middleware::CrawlerHooks rewrites links to match the page's tags.+ def plain_url_serves_default_locale?+ key = ContentLocalization::PLAIN_URL_SERVES_DEFAULT_LOCALE_ENV+ return request.env[key] if request.env.key?(key)++ request.env[key] = current_user.nil? &&+ ContentLocalization.plain_url_serves_default_locale?(request)+ end+ helper_method :plain_url_serves_default_locale?+def include_splash_screen?!Rails.env.test?enddiff --git a/app/views/common/_hreflang_tags.html.erb b/app/views/common/_hreflang_tags.html.erbindex 828a0fa9b2a..220b5572b61 100644--- a/app/views/common/_hreflang_tags.html.erb+++ b/app/views/common/_hreflang_tags.html.erb@@ -1,9 +1,12 @@<% if ContentLocalization.crawler_locale_param_enabled? %><% locales = SiteSetting.content_localization_supported_locales&.split('|') || [] %><% if locales.any? %>+ <% plain_url = plain_url_serves_default_locale? %>+ <% locales = SiteSetting.content_localization_locales if plain_url %><link rel="alternate" href="<%= canonical_url_for_locale(nil) %>" hreflang="x-default" /><% locales.each do |locale| %>- <link rel="alternate" href="<%= canonical_url_for_locale(locale) %>" hreflang="<%= locale.tr('_', '-') %>" />+ <% href_locale = locale unless plain_url && locale == SiteSetting.default_locale %>+ <link rel="alternate" href="<%= canonical_url_for_locale(href_locale) %>" hreflang="<%= locale.tr('_', '-') %>" /><% end %><% end %><% end %>diff --git a/lib/canonical_url.rb b/lib/canonical_url.rbindex 7ef8e7a123e..9f103d8d39b 100644--- a/lib/canonical_url.rb+++ b/lib/canonical_url.rb@@ -39,6 +39,7 @@ module CanonicalURLlocale = params[Discourse::LOCALE_PARAM]return url if locale.blank?+ return url if locale == SiteSetting.default_locale && plain_url_serves_default_locale?supported = SiteSetting.content_localization_supported_locales.to_s.split("|")return url if supported.exclude?(locale)diff --git a/lib/content_localization.rb b/lib/content_localization.rbindex f4c175c4cf4..f9f01976975 100644--- a/lib/content_localization.rb+++ b/lib/content_localization.rb@@ -128,6 +128,19 @@ class ContentLocalizationSiteSetting.set_locale_from_paramend+ PLAIN_URL_SERVES_DEFAULT_LOCALE_ENV = "discourse.plain_url_serves_default_locale"++ # Whether an anonymous client gets the default locale at the plain URL, so that URL can stand in+ # for the default locale's locale param URL. A locale cookie written from the locale param can+ # change what the plain URL serves between requests, so it is never guaranteed then.+ # @param request [Rack::Request]+ # @return [Boolean]+ def self.plain_url_serves_default_locale?(request)+ return false if SiteSetting.set_locale_from_cookie++ Discourse.anonymous_locale(request, include_param: false) == SiteSetting.default_locale+ end+# These are the same conditions the header renders the switcher on. Keeping the two set-equal# means a locale cookie is only ever honoured while there is UI to change it back.# @return [Boolean]diff --git a/lib/discourse.rb b/lib/discourse.rbindex 7a9c22e9bea..624cec271c9 100644--- a/lib/discourse.rb+++ b/lib/discourse.rb@@ -1379,8 +1379,8 @@ module DiscourseTheme.expire_site_cache!end- def self.anonymous_locale(request)- locale = request.params[LOCALE_PARAM] if SiteSetting.set_locale_from_param+ def self.anonymous_locale(request, include_param: true)+ locale = request.params[LOCALE_PARAM] if include_param && SiteSetting.set_locale_from_paramlocale ||= locale_from_cookie(request)locale ||=request.env["HTTP_ACCEPT_LANGUAGE"] if SiteSetting.set_locale_from_accept_language_headerdiff --git a/lib/middleware/anonymous_cache.rb b/lib/middleware/anonymous_cache.rbindex db028bc3a31..577e5b1eb60 100644--- a/lib/middleware/anonymous_cache.rb+++ b/lib/middleware/anonymous_cache.rb@@ -120,11 +120,16 @@ module Middleware# rubocop:enable Lint/BooleanSymboldef key_locale- if locale = Discourse.anonymous_locale(@request)- locale- else- "" # No need to key, it is the same for all anon users+ locale = Discourse.anonymous_locale(@request).to_s++ # Crawler pages at a locale param URL also depend on the locale the plain URL serves.+ # A blank param still skips the other locale sources, so check for the key.+ if ContentLocalization.crawler_locale_param_enabled? &&+ @request.params.key?(Discourse::LOCALE_PARAM)+ locale += "|#{Discourse.anonymous_locale(@request, include_param: false)}"end++ localeend# rubocop:disable Lint/BooleanSymboldiff --git a/lib/middleware/crawler_hooks.rb b/lib/middleware/crawler_hooks.rbindex 986f16a57f3..f9088eeb3dc 100644--- a/lib/middleware/crawler_hooks.rb+++ b/lib/middleware/crawler_hooks.rb@@ -26,8 +26,12 @@ module Middlewaredef transform_response(request:, response:)locale = request.params[Discourse::LOCALE_PARAM]+ # Set by the controller when the page's tags use the plain URL for the default locale.+ plain_url =+ locale == SiteSetting.default_locale &&+ request.env[ContentLocalization::PLAIN_URL_SERVES_DEFAULT_LOCALE_ENV]- if ContentLocalization.crawler_locale_param_enabled? && locale.present?+ if ContentLocalization.crawler_locale_param_enabled? && locale.present? && !plain_urlhtml_fragment = Nokogiri::HTML5.parse(response.body)html_fragmentdiff --git a/spec/lib/discourse_spec.rb b/spec/lib/discourse_spec.rbindex e1b6d737c89..571c2156baf 100644--- a/spec/lib/discourse_spec.rb+++ b/spec/lib/discourse_spec.rb@@ -831,9 +831,12 @@ RSpec.describe Discourse doenddescribe ".anonymous_locale" do- def locale_for(cookie: nil, path: "/")- env = cookie ? { "HTTP_COOKIE" => "locale=#{cookie}" } : {}- Discourse.anonymous_locale(ActionDispatch::Request.new(Rack::MockRequest.env_for(path, env)))+ def locale_for(cookie: nil, path: "/", env: {}, include_param: true)+ env = env.merge("HTTP_COOKIE" => "locale=#{cookie}") if cookie+ Discourse.anonymous_locale(+ ActionDispatch::Request.new(Rack::MockRequest.env_for(path, env)),+ include_param:,+ )endbefore do@@ -899,5 +902,28 @@ RSpec.describe Discourse doexpect(locale_for(cookie: "es", path: "/?tl=fr")).to eq("fr")endend++ context "without the locale param" do+ before do+ SiteSetting.set_locale_from_param = true+ SiteSetting.set_locale_from_cookie = true+ SiteSetting.set_locale_from_accept_language_header = true+ end++ it "resolves the locale the plain URL would serve" do+ expect(locale_for(cookie: "es", path: "/?tl=fr", include_param: false)).to eq("es")+ expect(+ locale_for(+ path: "/?tl=fr",+ env: {+ "HTTP_ACCEPT_LANGUAGE" => "ja",+ },+ include_param: false,+ ),+ ).to eq("ja")+ expect(locale_for(path: "/?tl=fr", include_param: false)).to eq("en")+ expect(locale_for(cookie: "es", path: "/?tl=fr")).to eq("fr")+ end+ endendenddiff --git a/spec/lib/middleware/anonymous_cache_spec.rb b/spec/lib/middleware/anonymous_cache_spec.rbindex c51c39f84d0..4e0fafdc160 100644--- a/spec/lib/middleware/anonymous_cache_spec.rb+++ b/spec/lib/middleware/anonymous_cache_spec.rb@@ -144,6 +144,40 @@ RSpec.describe Middleware::AnonymousCache doexpect(new_helper(env).cache_key).to include("l=#{Discourse.anonymous_locale(request)}")end++ it "keys locale param URLs on the locale the plain URL serves when crawler URLs are localized" do+ SiteSetting.allow_user_locale = true+ SiteSetting.set_locale_from_param = true+ SiteSetting.set_locale_from_accept_language_header = true+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "ja"+ path = "http://test.com/path?#{Discourse::LOCALE_PARAM}=en"++ key_for = ->(opts = {}) { new_helper(path:, **opts).cache_key }++ expect(key_for.call).to eq(key_for.call("HTTP_ACCEPT_LANGUAGE" => "ja"))++ SiteSetting.content_localization_crawler_param = true++ expect(key_for.call).not_to eq(key_for.call("HTTP_ACCEPT_LANGUAGE" => "ja"))+ expect(key_for.call).to eq(key_for.call("HTTP_ACCEPT_LANGUAGE" => "en"))+ expect(new_helper.cache_key).to eq(new_helper("HTTP_ACCEPT_LANGUAGE" => "en").cache_key)+ end++ it "keys blank locale param URLs on the locale the plain URL serves when crawler URLs are localized" do+ SiteSetting.allow_user_locale = true+ SiteSetting.set_locale_from_param = true+ SiteSetting.set_locale_from_accept_language_header = true+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_crawler_param = true+ SiteSetting.content_localization_supported_locales = "ja"+ path = "http://test.com/path?#{Discourse::LOCALE_PARAM}="++ key_for = ->(opts = {}) { new_helper(path:, **opts).cache_key }++ expect(key_for.call).not_to eq(key_for.call("HTTP_ACCEPT_LANGUAGE" => "ja"))+ expect(key_for.call).to eq(key_for.call("HTTP_ACCEPT_LANGUAGE" => "en"))+ endendit "handles old browsers" dodiff --git a/spec/lib/middleware/crawler_hooks_spec.rb b/spec/lib/middleware/crawler_hooks_spec.rbindex 009bfab9ee6..1c6c0fe0afa 100644--- a/spec/lib/middleware/crawler_hooks_spec.rb+++ b/spec/lib/middleware/crawler_hooks_spec.rb@@ -315,6 +315,48 @@ describe Middleware::CrawlerHooks doexpect(Nokogiri::HTML5.parse(transformed_response.first).css("a").size).to eq(2)end+ context "when the locale parameter is the default locale" do+ def call_with_default_locale(env_overrides = {})+ middleware.call(+ env(+ :path => "https://discourse.site/page",+ :params => {+ Discourse::LOCALE_PARAM => SiteSetting.default_locale,+ },+ "HTTP_USER_AGENT" => crawler_user_agent,+ "X-Discourse-Crawler-View" => true,+ **env_overrides,+ ),+ )+ end++ before do+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_crawler_param = true+ end++ it "does not append it to links when the plain URL serves the default locale" do+ status, _headers, response =+ call_with_default_locale(ContentLocalization::PLAIN_URL_SERVES_DEFAULT_LOCALE_ENV => true)++ expect(status).to eq(200)+ expect(response).to eq(html_response)+ end++ it "appends it to links when the plain URL may serve another locale" do+ _status, _headers, response =+ call_with_default_locale(+ ContentLocalization::PLAIN_URL_SERVES_DEFAULT_LOCALE_ENV => false,+ )++ expect(response.first).to include(%(href="/test?#{Discourse::LOCALE_PARAM}=en"))++ _status, _headers, response = call_with_default_locale++ expect(response.first).to include(%(href="/test?#{Discourse::LOCALE_PARAM}=en"))+ end+ end+it "does not modify links in HTML responses when locale parameter is not present" doSiteSetting.content_localization_enabled = trueSiteSetting.content_localization_crawler_param = truediff --git a/spec/requests/about_controller_spec.rb b/spec/requests/about_controller_spec.rbindex b17b525bbf3..0a543bbbcc6 100644--- a/spec/requests/about_controller_spec.rb+++ b/spec/requests/about_controller_spec.rb@@ -71,6 +71,32 @@ RSpec.describe AboutController doexpect(response.parsed_body.dig("about", "description")).to eq("日本語の説明")end+ it "localizes JSON responses from Accept-Language for clients classified as crawlers" do+ SiteSetting.allow_user_locale = true+ SiteSetting.set_locale_from_accept_language_header = true+ SiteSetting.content_localization_crawler_param = true+ SiteSetting.content_localization_supported_locales = "ja"++ get "/about.json",+ headers: {+ "HTTP_USER_AGENT" => "curl/8.0",+ "HTTP_ACCEPT_LANGUAGE" => "ja",+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body.dig("about", "title")).to eq("日本語タイトル")++ get "/about",+ headers: {+ "HTTP_USER_AGENT" => "curl/8.0",+ "HTTP_ACCEPT" => "application/json, text/html;q=0.5",+ "HTTP_ACCEPT_LANGUAGE" => "ja",+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body.dig("about", "title")).to eq("日本語タイトル")+ end+it "falls back to default values when a localized value is blank" doSiteSettingLocalization.find_by!(setting_name: "title", locale: "ja").update_column(:value,diff --git a/spec/requests/crawler_hreflang_spec.rb b/spec/requests/crawler_hreflang_spec.rbindex bb3017ce393..df76e6a0d9c 100644--- a/spec/requests/crawler_hreflang_spec.rb+++ b/spec/requests/crawler_hreflang_spec.rb@@ -27,6 +27,143 @@ describe "Crawler hreflang tags" doexpect(response.body).to include("?#{Discourse::LOCALE_PARAM}=ja")end+ it "points the default locale's hreflang to the plain URL" do+ get "/t/#{post.topic.slug}/#{post.topic.id}",+ headers: {+ "User-Agent" => "Googlebot/2.1 (+http://www.google.com/bot.html)",+ }++ expect(response.body).to include(+ %(<link rel="alternate" href="#{post.topic.url}" hreflang="en" />),+ )+ expect(response.body).not_to include("?#{Discourse::LOCALE_PARAM}=en")+ end++ it "includes the default locale's hreflang when the default locale isn't a supported locale" do+ SiteSetting.content_localization_supported_locales = "ja|es"++ get "/t/#{post.topic.slug}/#{post.topic.id}",+ headers: {+ "User-Agent" => "Googlebot/2.1 (+http://www.google.com/bot.html)",+ }++ expect(response.body).to include(+ %(<link rel="alternate" href="#{post.topic.url}" hreflang="en" />),+ )+ end++ it "canonicalizes topic and list pages to the plain URL when ?tl= is the default locale" do+ get "/t/#{post.topic.slug}/#{post.topic.id}?#{Discourse::LOCALE_PARAM}=en",+ headers: {+ "User-Agent" => "Googlebot/2.1 (+http://www.google.com/bot.html)",+ }++ expect(response.body).to match(+ %r{<link rel="canonical" href="#{Regexp.escape(post.topic.url)}"\s*/?>},+ )++ get "/latest?#{Discourse::LOCALE_PARAM}=en",+ headers: {+ "User-Agent" => "Googlebot/2.1 (+http://www.google.com/bot.html)",+ }++ expect(response.body).to match(+ %r{<link rel="canonical" href="#{Regexp.escape(Discourse.base_url)}/latest"\s*/?>},+ )+ end++ context "when the plain URL may not serve the default locale" do+ let(:topic_path) { "/t/#{post.topic.slug}/#{post.topic.id}" }++ def expect_default_locale_param_urls+ expect(response.body).to include(+ %(<link rel="alternate" href="#{post.topic.url}?#{Discourse::LOCALE_PARAM}=en" hreflang="en" />),+ )+ expect(response.body).not_to include(+ %(<link rel="alternate" href="#{post.topic.url}" hreflang="en" />),+ )++ get "#{topic_path}?#{Discourse::LOCALE_PARAM}=en", headers: request_headers++ expect(response.body).to include(+ %(<link rel="canonical" href="#{post.topic.url}?#{Discourse::LOCALE_PARAM}=en">),+ )+ end++ context "with a crawler whose Accept-Language picks another locale" do+ let(:request_headers) do+ {+ "User-Agent" => "Googlebot/2.1 (+http://www.google.com/bot.html)",+ "Accept-Language" => "ja",+ }+ end++ before { SiteSetting.set_locale_from_accept_language_header = true }++ it "keeps the default locale's locale param URL" do+ get topic_path, headers: request_headers++ expect(response.body).to include('<html lang="ja"')+ expect_default_locale_param_urls+ end+ end++ context "with a crawler whose language switcher cookie picks another locale" do+ let(:request_headers) do+ {+ "User-Agent" => "Googlebot/2.1 (+http://www.google.com/bot.html)",+ "Cookie" => "locale=ja",+ }+ end++ before { SiteSetting.content_localization_language_switcher = "all" }++ it "keeps the default locale's locale param URL" do+ get topic_path, headers: request_headers++ expect(response.body).to include('<html lang="ja"')+ expect_default_locale_param_urls+ end+ end++ context "when set_locale_from_cookie is enabled" do+ let(:request_headers) do+ { "User-Agent" => "Googlebot/2.1 (+http://www.google.com/bot.html)" }+ end++ before { SiteSetting.set_locale_from_cookie = true }++ it "keeps the default locale's locale param URL" do+ get topic_path, headers: request_headers++ expect_default_locale_param_urls+ end++ it "doesn't add the default locale when it isn't a supported locale" do+ SiteSetting.content_localization_supported_locales = "ja|es"++ get topic_path, headers: request_headers++ expect(response.body).to include('hreflang="ja"')+ expect(response.body).not_to include('hreflang="en"')+ end+ end++ context "with a signed-in user" do+ let(:request_headers) do+ { "User-Agent" => "Googlebot/2.1 (+http://www.google.com/bot.html)" }+ end++ before { sign_in(user) }++ it "keeps the default locale's locale param URL" do+ get topic_path, headers: request_headers++ expect_default_locale_param_urls+ end+ end+ end+it "uses hyphens instead of underscores in hreflang attribute for region-qualified locales" doSiteSetting.content_localization_supported_locales = "en|pt_BR|zh_CN"@@ -167,12 +304,26 @@ describe "Crawler hreflang tags" doexpect(hreflang_links).to contain_exactly(["x-default", "#{topic_url}?page=2"],- ["en", "#{topic_url}?page=2&#{Discourse::LOCALE_PARAM}=en"],+ ["en", "#{topic_url}?page=2"],["ja", "#{topic_url}?page=2&#{Discourse::LOCALE_PARAM}=ja"],["es", "#{topic_url}?page=2&#{Discourse::LOCALE_PARAM}=es"],)end+ it "keeps the page in the default locale's locale param URL when the plain URL may not serve the default locale" do+ SiteSetting.set_locale_from_cookie = true++ get "#{topic_url}?page=2",+ headers: {+ "User-Agent" => "Googlebot/2.1 (+http://www.google.com/bot.html)",+ }++ expect(hreflang_links).to include(+ ["x-default", "#{topic_url}?page=2"],+ ["en", "#{topic_url}?page=2&#{Discourse::LOCALE_PARAM}=en"],+ )+ end+it "points the alternates of a reply link to the page that holds the reply" doget "#{topic_url}/#{replies.last.post_number}",headers: {diff --git a/spec/requests/list_controller_spec.rb b/spec/requests/list_controller_spec.rbindex cf3f4b22134..4d6a9599f4c 100644--- a/spec/requests/list_controller_spec.rb+++ b/spec/requests/list_controller_spec.rb@@ -931,6 +931,25 @@ RSpec.describe ListController doexpect(response.headers["X-Robots-Tag"]).to eq("noindex")end+ it "localizes latest RSS from Accept-Language for clients classified as crawlers" do+ SiteSetting.allow_user_locale = true+ SiteSetting.set_locale_from_param = true+ SiteSetting.set_locale_from_accept_language_header = true+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_crawler_param = true+ SiteSetting.content_localization_supported_locales = "ja"++ get "/latest.rss",+ headers: {+ "HTTP_USER_AGENT" => "curl/8.0",+ "HTTP_ACCEPT" => "*/*",+ "HTTP_ACCEPT_LANGUAGE" => "ja",+ }++ title = Nokogiri.XML(response.body).at_xpath("/rss/channel/title").text+ expect(title).to eq("#{SiteSetting.title} - #{I18n.t("rss_description.latest", locale: :ja)}")+ end+it "does not allow a topic author to forge RSS items" doattacker = Fabricate(:user, refresh_auto_groups: true)forged_title = "Forged RSS item"diff --git a/spec/requests/posts_controller_spec.rb b/spec/requests/posts_controller_spec.rbindex 416e07c0378..458379a7c03 100644--- a/spec/requests/posts_controller_spec.rb+++ b/spec/requests/posts_controller_spec.rb@@ -124,6 +124,27 @@ RSpec.describe PostsController doexpect(parsed["cooked"]).to eq(new_post.cooked)end+ it "localizes posts from Accept-Language for clients classified as crawlers" do+ SiteSetting.allow_user_locale = true+ SiteSetting.set_locale_from_param = true+ SiteSetting.set_locale_from_accept_language_header = true+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_crawler_param = true+ SiteSetting.content_localization_supported_locales = "ja"+ localized_post = Fabricate(:post, raw: "Original post body", locale: "en")+ Fabricate(:post_localization, post: localized_post, locale: "ja", cooked: "<p>翻訳された本文</p>")++ get "/posts/#{localized_post.id}",+ headers: {+ "HTTP_USER_AGENT" => "curl/8.0",+ "HTTP_ACCEPT" => "*/*",+ "HTTP_ACCEPT_LANGUAGE" => "ja",+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body["cooked"]).to eq("<p>翻訳された本文</p>")+ end+context "with version parameter" dolet(:post_with_revisions) { Fabricate(:post, user: user, version: 2) }let(:post_revision) { Fabricate(:post_revision, post: post_with_revisions) }diff --git a/spec/requests/site_controller_spec.rb b/spec/requests/site_controller_spec.rbindex 184074981de..e392441c5fe 100644--- a/spec/requests/site_controller_spec.rb+++ b/spec/requests/site_controller_spec.rb@@ -76,6 +76,26 @@ RSpec.describe SiteController do[public_category_tag.name, public_category_tag.description],)end++ it "localizes extensionless requests from clients classified as crawlers" do+ SiteSetting.allow_user_locale = true+ SiteSetting.set_locale_from_param = true+ SiteSetting.set_locale_from_accept_language_header = true+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_crawler_param = true+ SiteSetting.content_localization_supported_locales = "ja"++ get "/site",+ headers: {+ "HTTP_USER_AGENT" => "curl/8.0",+ "HTTP_ACCEPT" => "*/*",+ "HTTP_ACCEPT_LANGUAGE" => "ja",+ }++ spam = response.parsed_body["post_action_types"].find { |type| type["name_key"] == "spam" }+ expect(spam["name"]).to eq(I18n.t("post_action_types.spam.title", locale: :ja))+ expect(spam["name"]).not_to eq(I18n.t("post_action_types.spam.title", locale: :en))+ endenddescribe "#basic_info" do