A platform for community discussion. Free, open, simple.
FEATURE: Admins can disallow anons from using /search (#43281)
Natalie Tayae6fe4943487
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rbindex 6fc5c31f7f4..7e65f7dee92 100644--- a/app/controllers/application_controller.rb+++ b/app/controllers/application_controller.rb@@ -948,7 +948,7 @@ class ApplicationController < ActionController::Baseend@subtitle = opts[:subtitle] || I18n.t("page_not_found.subtitle")@group = opts[:group]- @hide_search = true if SiteSetting.login_required+ @hide_search = true if SiteSetting.login_required || !guardian.can_search?params[:slug] = params[:slug].first if params[:slug].kind_of?(Array)params[:id] = params[:id].first if params[:id].kind_of?(Array)diff --git a/app/controllers/search_controller.rb b/app/controllers/search_controller.rbindex b399e4b68ee..567a1919477 100644--- a/app/controllers/search_controller.rb+++ b/app/controllers/search_controller.rb@@ -1,6 +1,7 @@# frozen_string_literal: trueclass SearchController < ApplicationController+ before_action :ensure_can_search, only: %i[show query]before_action :block_crawler, only: :showbefore_action :cancel_overloaded_search, only: [:query]skip_before_action :check_xhr, only: :show@@ -166,6 +167,16 @@ class SearchController < ApplicationControllerprotected+ def ensure_can_search+ return if guardian.can_search?++ if request.format.html?+ redirect_to_login+ else+ ensure_logged_in+ end+ end+def pageview_session_idrequest.headers["HTTP_DISCOURSE_PAGEVIEW_SESSION_ID"]enddiff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rbindex 07ba068b7d5..fec405e2350 100644--- a/app/helpers/application_helper.rb+++ b/app/helpers/application_helper.rb@@ -408,6 +408,8 @@ module ApplicationHelperenddef render_sitelinks_search_tag+ return if !guardian.can_search?+if current_page?("/") || current_page?(Discourse.base_path)json = {"@context" => "http://schema.org",diff --git a/app/serializers/site_serializer.rb b/app/serializers/site_serializer.rbindex 4ccfde4c2d7..4af784d9eef 100644--- a/app/serializers/site_serializer.rb+++ b/app/serializers/site_serializer.rb@@ -22,6 +22,7 @@ class SiteSerializer < ApplicationSerializer:post_action_types,:topic_flag_types,:can_create_tag,+ :can_search,:can_tag_topics,:can_tag_pms,:tags_filter_regexp,@@ -262,6 +263,10 @@ class SiteSerializer < ApplicationSerializerscope.can_create_tag?end+ def can_search+ scope.can_search?+ end+def can_tag_topicsscope.can_tag_topics?enddiff --git a/app/views/layouts/_head.html.erb b/app/views/layouts/_head.html.erbindex 14e070e2c31..5995b84ad6c 100644--- a/app/views/layouts/_head.html.erb+++ b/app/views/layouts/_head.html.erb@@ -19,4 +19,6 @@<% if SiteSetting.google_site_verification_token.present? %><meta name="google-site-verification" content="<%= SiteSetting.google_site_verification_token %>"><% end %>-<link rel="search" type="application/opensearchdescription+xml" href="<%= Discourse.base_url %>/opensearch.xml" title="<%= SiteSetting.title %> Search">+<% if guardian.can_search? %>+ <link rel="search" type="application/opensearchdescription+xml" href="<%= Discourse.base_url %>/opensearch.xml" title="<%= SiteSetting.title %> Search">+<% end %>diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex b333a525b40..6d8a13e4b82 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -1988,6 +1988,7 @@ en:min_personal_message_title_length: "Minimum allowed title length for a message in characters"max_emojis_in_title: "Maximum allowed emojis in topic title. If the set value is zero, it prevents the use of any emojis in topic titles."min_search_term_length: "Minimum valid search term length in characters"+ allow_anonymous_search: "Allow anonymous visitors to use /search. When disabled, anonymous visitors cannot access /search and interface controls that use /search are hidden."search_tokenize_chinese: "Force search to tokenize Chinese even on non Chinese sites"search_tokenize_japanese: "Force search to tokenize Japanese even on non Japanese sites"search_prefer_recent_posts: "If searching your large forum is slow, this option tries an index of more recent posts first"diff --git a/config/site_settings.yml b/config/site_settings.ymlindex 32f5af68192..49f296f489f 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -3806,6 +3806,9 @@ search:zh_TW: 1ko: 1ja: 1+ allow_anonymous_search:+ default: true+ refresh: truesearch_tokenize_chinese:default: falsevalidator: "SearchTokenizeChineseValidator"diff --git a/frontend/discourse/app/components/header.gjs b/frontend/discourse/app/components/header.gjsindex eb2534354e9..1fd7d46116f 100644--- a/frontend/discourse/app/components/header.gjs+++ b/frontend/discourse/app/components/header.gjs@@ -145,7 +145,7 @@ export default class GlimmerHeader extends Component {@actiontoggleSearchMenu(_, value) {- if (this.isDestroying || this.isDestroyed) {+ if (!this.site.can_search || this.isDestroying || this.isDestroyed) {return;}diff --git a/frontend/discourse/app/components/header/contents.gjs b/frontend/discourse/app/components/header/contents.gjsindex 624a2ef3818..e21abc3f2ca 100644--- a/frontend/discourse/app/components/header/contents.gjs+++ b/frontend/discourse/app/components/header/contents.gjs@@ -40,6 +40,7 @@ export default class Contents extends Component {get showHeaderSearch() {if (+ !this.site.can_search ||this.site.mobileView ||this.args.narrowDesktop ||ALL_PAGES_EXCLUDED_ROUTES.some(diff --git a/frontend/discourse/app/components/header/header-search.gjs b/frontend/discourse/app/components/header/header-search.gjsindex c81bf710272..45ca45eb09b 100644--- a/frontend/discourse/app/components/header/header-search.gjs+++ b/frontend/discourse/app/components/header/header-search.gjs@@ -8,6 +8,7 @@ import DButton from "discourse/ui-kit/d-button";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";export default class HeaderSearch extends Component {+ @service site;@service siteSettings;@service currentUser;@service appEvents;@@ -36,8 +37,9 @@ export default class HeaderSearch extends Component {get shouldDisplay() {return (- (this.siteSettings.login_required && this.currentUser) ||- !this.siteSettings.login_required+ this.site.can_search &&+ ((this.siteSettings.login_required && this.currentUser) ||+ !this.siteSettings.login_required));}diff --git a/frontend/discourse/app/components/header/icons.gjs b/frontend/discourse/app/components/header/icons.gjsindex 2ebe4630077..23526f1cb64 100644--- a/frontend/discourse/app/components/header/icons.gjs+++ b/frontend/discourse/app/components/header/icons.gjs@@ -62,6 +62,7 @@ export default class Icons extends Component {get showSearchButton() {if (+ !this.site.can_search ||this.header.headerButtonsHidden.includes("search") ||ALL_PAGES_EXCLUDED_ROUTES.some((name) => name === this.router.currentRouteNamediff --git a/frontend/discourse/app/components/topic-map/topic-map-summary.gjs b/frontend/discourse/app/components/topic-map/topic-map-summary.gjsindex f0c46b6ea40..d97ec99bff8 100644--- a/frontend/discourse/app/components/topic-map/topic-map-summary.gjs+++ b/frontend/discourse/app/components/topic-map/topic-map-summary.gjs@@ -292,60 +292,69 @@ export default class TopicMapSummary extends Component {{{/if}}{{#if this.hasLikes}}- <DMenu- @arrow={{true}}- @identifier="topic-map__likes"- @interactive={{true}}- @modalForMobile={{true}}- @placement="right"- @groupIdentifier="topic-map"- @inline={{true}}- @autofocus={{true}}- >- <:trigger>+ {{#if this.site.can_search}}+ <DMenu+ @arrow={{true}}+ @autofocus={{true}}+ @groupIdentifier="topic-map"+ @identifier="topic-map__likes"+ @inline={{true}}+ @interactive={{true}}+ @modalForMobile={{true}}+ @placement="right"+ >+ <:trigger>+ {{dNumber @topic.like_count noTitle="true"}}+ <span class="topic-map__stat-label">+ {{i18n "likes_lowercase" [email protected]_count}}+ </span>+ </:trigger>+ <:content>+ <h3 {{didInsert this.fetchMostLiked}}>{{i18n+ "topic_map.menu_titles.replies"+ }}</h3>+ <DConditionalLoadingSpinner @condition={{this.loading}}>+ <PluginOutlet+ @name="most-liked-replies"+ @outletArgs={{lazyHash+ posts=this.top3LikedPosts+ postUrl=this.postUrl+ }}+ >+ <ul>+ {{#each this.top3LikedPosts as |post|}}+ <li>+ <a href={{this.postUrl post}}>+ <span class="like-section__user">+ {{dBoundAvatarTemplate+ post.avatar_template+ "tiny"+ (hash title=post.username)+ }}+ {{post.username}}+ </span>+ <span class="like-section__likes">+ {{post.like_count}}+ {{dIcon "heart"}}</span>+ <p>+ {{trustHTML (emojiUnescape post.blurb)}}+ </p>+ </a>+ </li>+ {{/each}}+ </ul>+ </PluginOutlet>+ </DConditionalLoadingSpinner>+ </:content>+ </DMenu>+ {{else}}+ <div class="topic-map__stat topic-map__likes">{{dNumber @topic.like_count noTitle="true"}}<span class="topic-map__stat-label">{{i18n "likes_lowercase" [email protected]_count}}</span>- </:trigger>- <:content>- <h3 {{didInsert this.fetchMostLiked}}>{{i18n- "topic_map.menu_titles.replies"- }}</h3>- <DConditionalLoadingSpinner @condition={{this.loading}}>- <PluginOutlet- @name="most-liked-replies"- @outletArgs={{lazyHash- posts=this.top3LikedPosts- postUrl=this.postUrl- }}- >- <ul>- {{#each this.top3LikedPosts as |post|}}- <li>- <a href={{this.postUrl post}}>- <span class="like-section__user">- {{dBoundAvatarTemplate- post.avatar_template- "tiny"- (hash title=post.username)- }}- {{post.username}}- </span>- <span class="like-section__likes">- {{post.like_count}}- {{dIcon "heart"}}</span>- <p>- {{trustHTML (emojiUnescape post.blurb)}}- </p>- </a>- </li>- {{/each}}- </ul>- </PluginOutlet>- </DConditionalLoadingSpinner>- </:content>- </DMenu>+ </div>+ {{/if}}{{/if}}{{#if this.linksCount}}diff --git a/frontend/discourse/app/components/user-summary-category-search.gjs b/frontend/discourse/app/components/user-summary-category-search.gjsindex a3c169ad21b..000151310b4 100644--- a/frontend/discourse/app/components/user-summary-category-search.gjs+++ b/frontend/discourse/app/components/user-summary-category-search.gjs@@ -3,10 +3,13 @@ import Component from "@ember/component";import { hash } from "@ember/helper";import { computed } from "@ember/object";import { LinkTo } from "@ember/routing";+import { service } from "@ember/service";import { tagName } from "@ember-decorators/component";@tagName("")export default class UserSummaryCategorySearch extends Component {+ @service site;+@computed("user", "category")get searchParams() {let query = `@${this.get("user.username")} #${this.get("category.slug")}`;@@ -18,9 +21,13 @@ export default class UserSummaryCategorySearch extends Component {<template>{{#if @count}}- <LinkTo @route="full-page-search" @query={{hash q=this.searchParams}}>+ {{#if this.site.can_search}}+ <LinkTo @route="full-page-search" @query={{hash q=this.searchParams}}>+ {{@count}}+ </LinkTo>+ {{else}}{{@count}}- </LinkTo>+ {{/if}}{{else}}–{{/if}}diff --git a/frontend/discourse/app/components/welcome-banner.gjs b/frontend/discourse/app/components/welcome-banner.gjsindex 9fca83a7e5e..0c1c74867d0 100644--- a/frontend/discourse/app/components/welcome-banner.gjs+++ b/frontend/discourse/app/components/welcome-banner.gjs@@ -32,12 +32,18 @@ export const ALL_PAGES_EXCLUDED_ROUTES = [export default class WelcomeBanner extends Component {@service router;+ @service site;@service siteSettings;@service currentUser;@service appEvents;@service search;checkViewport = modifier((element) => {+ if (!this.site.can_search) {+ this.search.welcomeBannerSearchInViewport = false;+ return;+ }+const searchMenu =element.querySelector(".welcome-banner__search-menu") ?? element;@@ -107,6 +113,10 @@ export default class WelcomeBanner extends Component {});handleKeyboardShortcut = modifier(() => {+ if (!this.site.can_search) {+ return;+ }+const cb = (appEvent) => {if (appEvent.type === "search" &&@@ -281,22 +291,24 @@ export default class WelcomeBanner extends Component {{{/if}}</div><PluginOutlet @name="welcome-banner-below-headline" />- <div class="search-menu welcome-banner__search-menu">- {{#if this.showAdvancedSearchIcon}}- <DButton- @icon="magnifying-glass"- @title="search.open_advanced"- @href={{getURL "/search?expanded=true"}}- class="search-icon"+ {{#if this.site.can_search}}+ <div class="search-menu welcome-banner__search-menu">+ {{#if this.showAdvancedSearchIcon}}+ <DButton+ class="search-icon"+ @href={{getURL "/search?expanded=true"}}+ @icon="magnifying-glass"+ @title="search.open_advanced"+ />+ {{/if}}+ <SearchMenu+ @hideResults={{not this.search.welcomeBannerSearchInViewport}}+ @location="welcome-banner"+ @searchInputId="welcome-banner-search-input"+ @searchInputPlaceholder="welcome_banner.search_placeholder"/>- {{/if}}- <SearchMenu- @location="welcome-banner"- @searchInputId="welcome-banner-search-input"- @searchInputPlaceholder="welcome_banner.search_placeholder"- @hideResults={{not this.search.welcomeBannerSearchInViewport}}- />- </div>+ </div>+ {{/if}}<PluginOutlet @name="welcome-banner-below-input" /></div></div>diff --git a/frontend/discourse/app/routes/full-page-search.js b/frontend/discourse/app/routes/full-page-search.jsindex 780e6dde090..b1d4fef3319 100644--- a/frontend/discourse/app/routes/full-page-search.js+++ b/frontend/discourse/app/routes/full-page-search.js@@ -22,6 +22,14 @@ export default class FullPageSearch extends DiscourseRoute {category = null;+ beforeModel(transition) {+ if (this.site.can_search) {+ return;+ }++ transition.send("showLogin");+ }+titleToken() {return i18n("search.results_page", {term: escapeExpression(diff --git a/frontend/discourse/tests/acceptance/search-test.js b/frontend/discourse/tests/acceptance/search-test.jsindex c594896bf41..b759dbb4b61 100644--- a/frontend/discourse/tests/acceptance/search-test.js+++ b/frontend/discourse/tests/acceptance/search-test.js@@ -426,6 +426,31 @@ acceptance("Search - Anonymous", function (needs) {});});+acceptance("Search - Anonymous search disabled", function (needs) {+ needs.site({ can_search: false });+ needs.settings({ enable_welcome_banner: true });++ test("removes global search and sends anonymous users to login", async function (assert) {+ await visit("/");++ assert.dom(".welcome-banner").exists("keeps the welcome banner");+ assert+ .dom(".welcome-banner__search-menu")+ .doesNotExist("hides welcome banner search");+ assert.dom("#search-button").doesNotExist("hides header search");++ await triggerKeyEvent(document, "keypress", "/".charCodeAt(0));++ assert+ .dom(".search-menu-panel")+ .doesNotExist("does not open search from the keyboard shortcut");++ await visit("/search");++ assert.strictEqual(currentURL(), "/login", "opens the login page");+ });+});+acceptance("Search - Authenticated", function (needs) {needs.user();needs.settings({diff --git a/frontend/discourse/tests/acceptance/topic-test.js b/frontend/discourse/tests/acceptance/topic-test.jsindex 0fa92dae76b..dd426b0d0da 100644--- a/frontend/discourse/tests/acceptance/topic-test.js+++ b/frontend/discourse/tests/acceptance/topic-test.js@@ -827,3 +827,14 @@ acceptance(`Topic stats update automatically`, function () {);});});++acceptance(`Topic - Anonymous search disabled`, function (needs) {+ needs.site({ can_search: false });++ test("shows the likes count without opening search-backed details", async function (assert) {+ await visit("/t/internationalization-localization/280");++ assert.dom("#post_1 .topic-map .topic-map__likes").exists();+ assert.dom("#post_1 .topic-map .topic-map__likes-trigger").doesNotExist();+ });+});diff --git a/frontend/discourse/tests/acceptance/user-profile-summary-test.js b/frontend/discourse/tests/acceptance/user-profile-summary-test.jsindex 5b1d75c7568..f5f9fb97c50 100644--- a/frontend/discourse/tests/acceptance/user-profile-summary-test.js+++ b/frontend/discourse/tests/acceptance/user-profile-summary-test.js@@ -58,6 +58,30 @@ acceptance("User Profile - Summary", function (needs) {});});+acceptance(+ "User Profile - Summary - Anonymous search disabled",+ function (needs) {+ needs.site({ can_search: false });++ test("shows category counts without search links", async function (assert) {+ await visit("/u/eviltrout/summary");++ assert+ .dom(".top-categories-section tbody .reply-count a")+ .doesNotExist("does not link reply counts to search");+ assert+ .dom(".top-categories-section tbody .topic-count a")+ .doesNotExist("does not link topic counts to search");+ assert+ .dom(".top-categories-section tbody .reply-count")+ .hasText("1", "keeps the reply count visible");+ assert+ .dom(".top-categories-section tbody .topic-count")+ .hasText("1", "keeps the topic count visible");+ });+ }+);+acceptance("User Profile - Summary - User Status", function (needs) {needs.user();needs.pretender((server, helper) => {diff --git a/frontend/discourse/tests/fixtures/site-fixtures.js b/frontend/discourse/tests/fixtures/site-fixtures.jsindex 6c330ce8a49..fc6294623f7 100644--- a/frontend/discourse/tests/fixtures/site-fixtures.js+++ b/frontend/discourse/tests/fixtures/site-fixtures.js@@ -3,6 +3,7 @@ import { NOTIFICATION_TYPES } from "./concerns/notification-types";const siteFixtures = {"site.json": {site: {+ can_search: true,default_archetype: "regular",shared_drafts_category_id: 24,notification_types: NOTIFICATION_TYPES,diff --git a/lib/guardian.rb b/lib/guardian.rbindex 1fef68f6828..89c70b88c11 100644--- a/lib/guardian.rb+++ b/lib/guardian.rb@@ -204,6 +204,10 @@ class Guardian@user.in_any_groups?(group_ids)end+ def can_search?+ authenticated? || SiteSetting.allow_anonymous_search+ end+# Can the user see the object?def can_see?(obj)if objdiff --git a/lib/llms_txt.rb b/lib/llms_txt.rbindex a2a77f8ca8e..b7e48d71238 100644--- a/lib/llms_txt.rb+++ b/lib/llms_txt.rb@@ -23,11 +23,11 @@ module LlmsTxtif !SiteSetting.login_requiredpublic_links = [- translated_local_link(:search, "/search"),translated_local_link(:filter, "/filter"),translated_local_link(:latest, "/latest"),translated_local_link(:categories, "/categories"),]+ public_links.unshift(translated_local_link(:search, "/search")) if Guardian.new.can_search?if SiteSetting.enable_sitemappublic_links << translated_local_link(:sitemap, "/sitemap.xml")enddiff --git a/spec/helpers/application_helper_spec.rb b/spec/helpers/application_helper_spec.rbindex 7bed094ac3e..5117c63f5cc 100644--- a/spec/helpers/application_helper_spec.rb+++ b/spec/helpers/application_helper_spec.rb@@ -278,6 +278,14 @@ RSpec.describe ApplicationHelper doexpect(sitelinks_search_tag["name"]).to eq(SiteSetting.title)expect(sitelinks_search_tag["url"]).to eq(Discourse.base_url)end++ it "omits the sitelinks search tag when anonymous users cannot search" do+ SiteSetting.allow_anonymous_search = false+ helper.stubs(:current_page?).returns(false)+ helper.stubs(:current_page?).with("/").returns(true)++ expect(helper.render_sitelinks_search_tag).to be_nil+ endendcontext "when not on homepage" doit "will not return sitelinks search tag" dodiff --git a/spec/lib/guardian_spec.rb b/spec/lib/guardian_spec.rbindex 9e673146d87..4b755c7c878 100644--- a/spec/lib/guardian_spec.rb+++ b/spec/lib/guardian_spec.rb@@ -55,6 +55,24 @@ RSpec.describe Guardian doendend+ describe "#can_search?" do+ it "allows anonymous and logged-in users by default" do+ expect(Guardian.new.can_search?).to eq(true)+ expect(Guardian.new(user).can_search?).to eq(true)+ end++ it "only blocks anonymous users when anonymous search is disabled" do+ SiteSetting.allow_anonymous_search = false++ [false, true].each do |granular_permissions|+ SiteSetting.granular_anonymous_and_logged_in_groups_permissions = granular_permissions++ expect(Guardian.new.can_search?).to eq(false)+ expect(Guardian.new(user).can_search?).to eq(true)+ end+ end+ end+describe "acl permissions" dofab!(:acl_user) { Fabricate(:user, refresh_auto_groups: true) }fab!(:acl_group) { Fabricate(:group).tap { |group| group.add(acl_user) } }diff --git a/spec/requests/api/schemas/json/site_response.json b/spec/requests/api/schemas/json/site_response.jsonindex 2e24483641a..01eb9595d83 100644--- a/spec/requests/api/schemas/json/site_response.json+++ b/spec/requests/api/schemas/json/site_response.json@@ -517,6 +517,9 @@"can_create_tag": {"type": "boolean"},+ "can_search": {+ "type": "boolean"+ },"can_tag_topics": {"type": "boolean"},@@ -1069,6 +1072,7 @@"post_action_types","topic_flag_types","can_create_tag",+ "can_search","can_tag_topics","can_tag_pms","tags_filter_regexp",diff --git a/spec/requests/application_controller_spec.rb b/spec/requests/application_controller_spec.rbindex b18469f89e7..54cef1e2b2b 100644--- a/spec/requests/application_controller_spec.rb+++ b/spec/requests/application_controller_spec.rb@@ -42,6 +42,19 @@ RSpec.describe ApplicationController doendend+ describe "search metadata" do+ it "only advertises OpenSearch to users who can search" do+ SiteSetting.allow_anonymous_search = false++ get "/latest"+ expect(response.body).not_to have_tag("link[rel='search']")++ sign_in(user)+ get "/latest"+ expect(response.body).to have_tag("link[rel='search']")+ end+ end+context "for cache control headers" doit "sets the `no-cache, no-store` cache control response header when no error is raised" doget "/latest"@@ -538,6 +551,15 @@ RSpec.describe ApplicationController doexpect(response.body).to_not include("google.com/search")end+ it "does not include search when anonymous search is disabled" do+ SiteSetting.allow_anonymous_search = false++ get "/t/nope-nope/99999999"++ expect(response).to have_http_status(:not_found)+ expect(response.body).not_to include(I18n.t("page_not_found.search_title"))+ end+it "should allow anchor tags in title" doTranslationOverride.upsert!(I18n.locale,diff --git a/spec/requests/search_controller_spec.rb b/spec/requests/search_controller_spec.rbindex 2a51527944b..04ec01f4fbf 100644--- a/spec/requests/search_controller_spec.rb+++ b/spec/requests/search_controller_spec.rb@@ -259,6 +259,25 @@ RSpec.describe SearchController doenddescribe "#query" do+ context "when anonymous search is disabled" do+ before { SiteSetting.allow_anonymous_search = false }++ it "requires an anonymous user to log in" do+ get "/search/query.json", params: { term: "wookie" }++ expect(response).to have_http_status(:forbidden)+ expect(response.parsed_body["error_type"]).to eq("not_logged_in")+ end++ it "allows a logged-in user" do+ sign_in(user)++ get "/search/query.json", params: { term: "wookie" }++ expect(response).to have_http_status(:ok)+ end+ end+it "logs the search term" doSiteSetting.log_search_queries = trueget "/search/query.json", params: { term: "wookie" }@@ -403,6 +422,26 @@ RSpec.describe SearchController doenddescribe "#show" do+ context "when an anonymous user cannot search" do+ before { SiteSetting.allow_anonymous_search = false }++ it "redirects an HTML request to login and preserves the destination" do+ get "/search", params: { q: "猫" }++ expect(response).to redirect_to("/login")+ expect(URI.parse(response.cookies["destination_url"]).request_uri).to eq(+ "/search?q=%E7%8C%AB",+ )+ end++ it "rejects a JSON request" do+ get "/search.json", params: { q: "wookie" }++ expect(response).to have_http_status(:forbidden)+ expect(response.parsed_body["error_type"]).to eq("not_logged_in")+ end+ end+it "doesn't raise an error when search term not specified" doget "/search"expect(response.status).to eq(200)diff --git a/spec/requests/static_controller_spec.rb b/spec/requests/static_controller_spec.rbindex 7ccd4eac8ad..31a75696807 100644--- a/spec/requests/static_controller_spec.rb+++ b/spec/requests/static_controller_spec.rb@@ -665,6 +665,16 @@ RSpec.describe StaticController doexpect(response.body).to eq(anonymous_body)end+ it "omits the public search link when anonymous users cannot search" do+ SiteSetting.allow_anonymous_search = false++ get "/llms.txt"++ expect(response.status).to eq(200)+ expect(response.body).not_to include("#{Discourse.base_path}/search")+ expect(response.body).to include("#{Discourse.base_path}/latest")+ end+context "with local store" dobefore { SiteSetting.authorized_extensions = "txt" }diff --git a/spec/serializers/site_serializer_spec.rb b/spec/serializers/site_serializer_spec.rbindex 3c8008b9a94..9dda140a87f 100644--- a/spec/serializers/site_serializer_spec.rb+++ b/spec/serializers/site_serializer_spec.rb@@ -60,6 +60,21 @@ RSpec.describe SiteSerializer doendend+ describe "#can_search" do+ it "exposes whether the current user can search" do+ SiteSetting.allow_anonymous_search = false++ anonymous_payload =+ described_class.new(Site.new(guardian), scope: guardian, root: false).as_json+ user_guardian = Guardian.new(Fabricate(:user))+ user_payload =+ described_class.new(Site.new(user_guardian), scope: user_guardian, root: false).as_json++ expect(anonymous_payload[:can_search]).to eq(false)+ expect(user_payload[:can_search]).to eq(true)+ end+ end+describe "#user_tips" doit "is included if enable_user_tips" doSiteSetting.enable_user_tips = true