A platform for community discussion. Free, open, simple.
FIX: Make composer mention reachability checks case-insensitive (#39482)
Régis Hanol9a4cca2962a3
diff --git a/app/controllers/composer_controller.rb b/app/controllers/composer_controller.rbindex 17ded67c584..0b433032ebe 100644--- a/app/controllers/composer_controller.rb+++ b/app/controllers/composer_controller.rb@@ -4,8 +4,9 @@ class ComposerController < ApplicationControllerrequires_logindef mentions- @names = params.require(:names)- raise Discourse::InvalidParameters.new(:names) if [email protected]_of?(Array) || @names.size > 20+ names = params.require(:names)+ raise Discourse::InvalidParameters.new(:names) if !names.kind_of?(Array) || names.size > 20+ @names = names.map { |n| n.to_s.downcase }if params[:topic_id].present?@topic = Topic.find_by(id: params[:topic_id])@@ -18,7 +19,7 @@ class ComposerController < ApplicationControllerif !params[:allowed_names].is_a?(Array)raise Discourse::InvalidParameters.new(:allowed_names)end- params[:allowed_names] << current_user.username+ (params[:allowed_names] + [current_user.username]).map(&:downcase)else[]end@@ -35,7 +36,7 @@ class ComposerController < ApplicationControllerendend- if @topic && @names.include?(SiteSetting.here_mention) && guardian.can_mention_here?+ if @topic && @names.include?(SiteSetting.here_mention.downcase) && guardian.can_mention_here?here_count =PostAlerter.new.expand_here_mention(@topic.first_post, exclude_ids: [current_user.id]).sizeend@@ -43,41 +44,25 @@ class ComposerController < ApplicationControllerserialized_groups =groups.values- .reduce({}) do |hash, group|+ .each_with_object({}) do |group, hash|+ name = group.name.downcaseserialized_group = { user_count: group.user_count }- if group_reasons[group.name] == :not_allowed &&- members_visible_group_ids.include?(group.id) &&+ if group_reasons[name] == :not_allowed && members_visible_group_ids.include?(group.id) &&(@topic&.private_message? || @allowed_names.present?)- # Find users that are notified already because they have been invited- # directly or via a group- notified_count =- GroupUser- # invited directly- .where(user_id: topic_allowed_user_ids)- .or(- # invited via a group- GroupUser.where(- user_id: GroupUser.where(group_id: topic_allowed_group_ids).select(:user_id),- ),- )- .where(group_id: group.id)- .select(:user_id)- .distinct- .count+ notified_count = already_notified_member_count(group)if notified_count > 0if notified_count == group.user_count- group_reasons.delete(group.name)+ group_reasons.delete(name)else- group_reasons[group.name] = :some_not_allowed+ group_reasons[name] = :some_not_allowedserialized_group[:notified_count] = notified_countendendend- hash[group.name] = serialized_group- hash+ hash[name] = serialized_groupendrender json: {@@ -123,6 +108,20 @@ class ComposerController < ApplicationControllerendend+ def already_notified_member_count(group)+ GroupUser+ .where(user_id: topic_allowed_user_ids)+ .or(+ GroupUser.where(+ user_id: GroupUser.where(group_id: topic_allowed_group_ids).select(:user_id),+ ),+ )+ .where(group:)+ .select(:user_id)+ .distinct+ .count+ end+def is_user_allowed?(user, user_ids, group_ids)user_ids.include?(user.id) ||user.group_ids.any? do |group_id|@@ -133,33 +132,44 @@ class ComposerController < ApplicationControllerdef visible_group_ids_for_allowed_check@visible_group_ids_for_allowed_check ||=if @allowed_names.present?- Group.members_visible_groups(current_user).where(name: @allowed_names).pluck(:id).to_set+ Group+ .members_visible_groups(current_user)+ .where("LOWER(name) IN (?)", @allowed_names)+ .pluck(:id)+ .to_setelsetopic_allowed_group_ids || Set.newendenddef users- @users ||=- User.not_staged.where(username_lower: @names.map(&:downcase)).index_by(&:username_lower)+ @users ||= User.not_staged.where(username_lower: @names).index_by(&:username_lower)enddef groups@groups ||=Group.visible_groups(current_user)- .where("lower(name) IN (?)", @names.map(&:downcase))- .index_by(&:name)+ .where("LOWER(name) IN (?)", @names)+ .index_by { |g| g.name.downcase }enddef mentionable_group_ids@mentionable_group_ids ||=- Group.mentionable(current_user, include_public: false).where(name: @names).pluck(:id).to_set+ Group+ .mentionable(current_user, include_public: false)+ .where("LOWER(name) IN (?)", @names)+ .pluck(:id)+ .to_setenddef members_visible_group_ids@members_visible_group_ids ||=- Group.members_visible_groups(current_user).where(name: @names).pluck(:id).to_set+ Group+ .members_visible_groups(current_user)+ .where("LOWER(name) IN (?)", @names)+ .pluck(:id)+ .to_setenddef topic_muted_by@@ -179,7 +189,7 @@ class ComposerController < ApplicationControllerdef topic_allowed_user_ids@topic_allowed_user_ids ||=if @allowed_names.present?- User.where(username_lower: @allowed_names.map(&:downcase)).pluck(:id).to_set+ User.where(username_lower: @allowed_names).pluck(:id).to_setelsif @topic&.private_message?TopicAllowedUser.where(topic: @topic).pluck(:user_id).to_setend@@ -188,7 +198,11 @@ class ComposerController < ApplicationControllerdef topic_allowed_group_ids@topic_allowed_group_ids ||=if @allowed_names.present?- Group.messageable(current_user).where(name: @allowed_names).pluck(:id).to_set+ Group+ .messageable(current_user)+ .where("LOWER(name) IN (?)", @allowed_names)+ .pluck(:id)+ .to_setelsif @topic&.private_message?TopicAllowedGroup.where(topic: @topic).pluck(:group_id).to_setenddiff --git a/frontend/discourse/app/lib/link-mentions.js b/frontend/discourse/app/lib/link-mentions.jsindex 15dde0f0116..c8145d1637d 100644--- a/frontend/discourse/app/lib/link-mentions.js+++ b/frontend/discourse/app/lib/link-mentions.js@@ -53,17 +53,18 @@ function replaceSpan(element, name, opts) {function updateFound(mentions, names) {mentions.forEach((mention, index) => {const name = names[index];- if (foundUsers[name.toLowerCase()]) {+ const lower = name.toLowerCase();+ if (foundUsers[lower]) {replaceSpan(mention, name, {- reason: userReasons[name],+ reason: userReasons[lower],});- } else if (foundGroups[name]) {+ } else if (foundGroups[lower]) {replaceSpan(mention, name, {group: true,- details: foundGroups[name],- reason: groupReasons[name],+ details: foundGroups[lower],+ reason: groupReasons[lower],});- } else if (checked[name]) {+ } else if (checked[lower]) {mention.classList.add("mention-tested");}});@@ -82,7 +83,9 @@ export function linkSeenMentions(element, siteSettings) {updateFound(mentions, names);return uniqueItemsFromArray(names).filter(- (name) => !checked[name] && name.length >= siteSettings.min_username_length+ (name) =>+ !checked[name.toLowerCase()] &&+ name.length >= siteSettings.min_username_length);}@@ -91,16 +94,18 @@ export async function fetchUnseenMentions({ names, topicId, allowedNames }) {data: { names, topic_id: topicId, allowed_names: allowedNames },});- names.forEach((name) => (checked[name] = true));- response.users.forEach((username) => (foundUsers[username] = true));+ names.forEach((name) => (checked[name.toLowerCase()] = true));+ response.users.forEach(+ (username) => (foundUsers[username.toLowerCase()] = true)+ );Object.entries(response.user_reasons).forEach(- ([username, reason]) => (userReasons[username] = reason)+ ([username, reason]) => (userReasons[username.toLowerCase()] = reason));Object.entries(response.groups).forEach(- ([name, details]) => (foundGroups[name] = details)+ ([name, details]) => (foundGroups[name.toLowerCase()] = details));Object.entries(response.group_reasons).forEach(- ([name, reason]) => (groupReasons[name] = reason)+ ([name, reason]) => (groupReasons[name.toLowerCase()] = reason));maxGroupMention = response.max_users_notified_per_group_mention;diff --git a/frontend/discourse/app/static/prosemirror/extensions/mention.js b/frontend/discourse/app/static/prosemirror/extensions/mention.jsindex 9ce040b2f60..d5d300283c5 100644--- a/frontend/discourse/app/static/prosemirror/extensions/mention.js+++ b/frontend/discourse/app/static/prosemirror/extensions/mention.js@@ -109,7 +109,8 @@ const extension = {processMentionNodes(view) {const mentionNames = [];const mentionNodes = [];- const hereMention = getContext().siteSettings.here_mention;+ const hereMention =+ getContext().siteSettings.here_mention.toLowerCase();if (this._processingMentionNodes) {return;@@ -136,7 +137,11 @@ const extension = {for (const mentionNode of mentionNodes) {const { name, node, pos } = mentionNode;- if (VALID_MENTIONS.has(name) || hereMention === name) {+ const lowerName = name.toLowerCase();+ if (+ VALID_MENTIONS.has(lowerName) ||+ hereMention === lowerName+ ) {continue;}@@ -161,7 +166,8 @@ const extension = {async function fetchMentions(names, context) {// only fetch new mentions that are not already validatednames = uniqueItemsFromArray(names).filter((name) => {- return !VALID_MENTIONS.has(name) && !INVALID_MENTIONS.has(name);+ const lower = name.toLowerCase();+ return !VALID_MENTIONS.has(lower) && !INVALID_MENTIONS.has(lower);});if (!names.length) {@@ -172,20 +178,13 @@ async function fetchMentions(names, context) {data: { names, topic_id: context.topicId },});- const lowerGroupNames = Object.keys(response.groups).map((groupName) =>- groupName.toLowerCase()- );-names.forEach((name) => {const lowerName = name.toLowerCase();- if (- response.users.includes(lowerName) ||- lowerGroupNames.includes(lowerName)- ) {- VALID_MENTIONS.add(name);+ if (response.users.includes(lowerName) || response.groups[lowerName]) {+ VALID_MENTIONS.add(lowerName);} else {- INVALID_MENTIONS.add(name);+ INVALID_MENTIONS.add(lowerName);}checkMentionWarning(name, response, context);@@ -198,6 +197,8 @@ function checkMentionWarning(name, response, context) {response?.max_users_notified_per_group_mention,10);+ const lowerName = name.toLowerCase();+ const group = response.groups[lowerName];let reason;let body;@@ -207,18 +208,18 @@ function checkMentionWarning(name, response, context) {here: context.siteSettings.here_mention,count: hereCount,});- } else if (response.users.includes(name)) {- reason = response.user_reasons?.[name];+ } else if (response.users.includes(lowerName)) {+ reason = response.user_reasons?.[lowerName];if (reason) {body = i18n(`composer.cannot_see_mention.${reason}`, {username: name,});}- } else if (response.groups[name]) {- const userCount = response.groups[name]?.user_count || 0;- const notifiedCount = response.groups[name]?.notified_count || 0;- reason = response.group_reasons?.[name];+ } else if (group) {+ const userCount = group.user_count || 0;+ const notifiedCount = group.notified_count || 0;+ reason = response.group_reasons?.[lowerName];const groupLink = getURL(`/g/${name}/members`);diff --git a/spec/requests/composer_controller_spec.rb b/spec/requests/composer_controller_spec.rbindex d7291727987..754d8819aaf 100644--- a/spec/requests/composer_controller_spec.rb+++ b/spec/requests/composer_controller_spec.rb@@ -28,46 +28,43 @@ RSpec.describe ComposerController do)end+ let(:base_names) do+ [+ "invaliduserorgroup",+ user.username,+ group.name,+ invisible_group.name,+ unmessageable_group.name,+ unmentionable_group.name,+ ]+ end++ let(:expected_groups) do+ {+ group.name => {+ "user_count" => group.user_count,+ },+ unmessageable_group.name => {+ "user_count" => unmessageable_group.user_count,+ },+ unmentionable_group.name => {+ "user_count" => unmentionable_group.user_count,+ },+ }+ end+before { sign_in(current_user) }context "without a topic" doit "finds mentions" do- get "/composer/mentions.json",- params: {- names: [- "invaliduserorgroup",- user.username,- group.name,- invisible_group.name,- unmessageable_group.name,- unmentionable_group.name,- ],- }+ get "/composer/mentions.json", params: { names: base_names }expect(response.status).to eq(200)-expect(response.parsed_body["users"]).to contain_exactly(user.username)expect(response.parsed_body["user_reasons"]).to eq({})-- expect(response.parsed_body["groups"]).to eq(- {- group.name => {- "user_count" => group.user_count,- },- unmessageable_group.name => {- "user_count" => unmessageable_group.user_count,- },- unmentionable_group.name => {- "user_count" => unmentionable_group.user_count,- },- },- )+ expect(response.parsed_body["groups"]).to eq(expected_groups)expect(response.parsed_body["group_reasons"]).to eq(- { unmentionable_group.name => "not_mentionable" },- )-- expect(response.parsed_body["max_users_notified_per_group_mention"]).to eq(- SiteSetting.max_users_notified_per_group_mention,+ unmentionable_group.name => "not_mentionable",)endend@@ -76,42 +73,15 @@ RSpec.describe ComposerController dofab!(:topic)it "finds mentions" do- get "/composer/mentions.json",- params: {- names: [- "invaliduserorgroup",- user.username,- group.name,- invisible_group.name,- unmessageable_group.name,- unmentionable_group.name,- ],- topic_id: topic.id,- }+ get "/composer/mentions.json", params: { names: base_names, topic_id: topic.id }expect(response.status).to eq(200)-expect(response.parsed_body["users"]).to contain_exactly(user.username)expect(response.parsed_body["user_reasons"]).to eq({})-- expect(response.parsed_body["groups"]).to eq(- group.name => {- "user_count" => group.user_count,- },- unmessageable_group.name => {- "user_count" => unmessageable_group.user_count,- },- unmentionable_group.name => {- "user_count" => unmentionable_group.user_count,- },- )+ expect(response.parsed_body["groups"]).to eq(expected_groups)expect(response.parsed_body["group_reasons"]).to eq(unmentionable_group.name => "not_mentionable",)-- expect(response.parsed_body["max_users_notified_per_group_mention"]).to eq(- SiteSetting.max_users_notified_per_group_mention,- )endend@@ -135,46 +105,22 @@ RSpec.describe ComposerController doget "/composer/mentions.json",params: {- names: [- "invaliduserorgroup",- user.username,- allowed_user.username,- group.name,- invisible_group.name,- unmessageable_group.name,- unmentionable_group.name,- ],+ names: base_names + [allowed_user.username],topic_id: topic.id,}expect(response.status).to eq(200)-expect(response.parsed_body["users"]).to contain_exactly(user.username,allowed_user.username,)expect(response.parsed_body["user_reasons"]).to eq(user.username => "private")-- expect(response.parsed_body["groups"]).to eq(- group.name => {- "user_count" => group.user_count,- },- unmessageable_group.name => {- "user_count" => unmessageable_group.user_count,- },- unmentionable_group.name => {- "user_count" => unmentionable_group.user_count,- },- )+ expect(response.parsed_body["groups"]).to eq(expected_groups)expect(response.parsed_body["group_reasons"]).to eq(group.name => "not_allowed",unmessageable_group.name => "not_allowed",unmentionable_group.name => "not_mentionable",)-- expect(response.parsed_body["max_users_notified_per_group_mention"]).to eq(- SiteSetting.max_users_notified_per_group_mention,- )endit "returns notified_count" do@@ -217,46 +163,22 @@ RSpec.describe ComposerController doit "finds mentions" doget "/composer/mentions.json",params: {- names: [- "invaliduserorgroup",- user.username,- allowed_user.username,- group.name,- invisible_group.name,- unmessageable_group.name,- unmentionable_group.name,- ],+ names: base_names + [allowed_user.username],allowed_names: [allowed_user.username, unmentionable_group.name],}expect(response.status).to eq(200)-expect(response.parsed_body["users"]).to contain_exactly(user.username,allowed_user.username,)expect(response.parsed_body["user_reasons"]).to eq(user.username => "private")-- expect(response.parsed_body["groups"]).to eq(- group.name => {- "user_count" => group.user_count,- },- unmessageable_group.name => {- "user_count" => unmessageable_group.user_count,- },- unmentionable_group.name => {- "user_count" => unmentionable_group.user_count,- },- )+ expect(response.parsed_body["groups"]).to eq(expected_groups)expect(response.parsed_body["group_reasons"]).to eq(group.name => "not_allowed",unmessageable_group.name => "not_allowed",unmentionable_group.name => "not_mentionable",)-- expect(response.parsed_body["max_users_notified_per_group_mention"]).to eq(- SiteSetting.max_users_notified_per_group_mention,- )endit "returns notified_count" do@@ -328,21 +250,89 @@ RSpec.describe ComposerController doendend- context "with an invalid topic" do- it "returns an error" do+ context "with mixed-case names" do+ fab!(:mixed_case_user) { Fabricate(:user, username: "SomeUser") }+ fab!(:mixed_case_group) do+ Fabricate(+ :group,+ name: "MixedCaseGroup",+ messageable_level: Group::ALIAS_LEVELS[:everyone],+ mentionable_level: Group::ALIAS_LEVELS[:everyone],+ )+ end++ before { sign_in(Fabricate(:admin)) }++ it "matches users case-insensitively when checking category access" do+ category = Fabricate(:private_category, group: mixed_case_group)+ topic_in_category = Fabricate(:topic, category: category)+get "/composer/mentions.json",params: {- names: [- "invaliduserorgroup",- user.username,- group.name,- invisible_group.name,- unmessageable_group.name,- unmentionable_group.name,- ],- topic_id: -1,+ names: [mixed_case_user.username, mixed_case_user.username.upcase],+ topic_id: topic_in_category.id,}+ expect(response.status).to eq(200)+ expect(response.parsed_body["users"]).to contain_exactly("someuser")+ expect(response.parsed_body["user_reasons"]).to eq("someuser" => "category")+ end++ it "matches mentionable groups case-insensitively" do+ get "/composer/mentions.json",+ params: {+ names: [mixed_case_group.name.upcase, mixed_case_group.name.downcase],+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body["groups"]).to eq(+ "mixedcasegroup" => {+ "user_count" => mixed_case_group.user_count,+ },+ )+ expect(response.parsed_body["group_reasons"]).to be_empty+ end++ it "matches mentioned groups case-insensitively in private messages" do+ pm = Fabricate(:private_message_topic)++ get "/composer/mentions.json",+ params: {+ names: [mixed_case_group.name.upcase],+ topic_id: pm.id,+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body["group_reasons"]).to eq("mixedcasegroup" => "not_allowed")+ end++ it "matches allowed_names users case-insensitively" do+ get "/composer/mentions.json",+ params: {+ names: [mixed_case_user.username.upcase],+ allowed_names: [mixed_case_user.username.upcase],+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body["user_reasons"]).to eq({})+ end++ it "matches allowed_names groups case-insensitively" do+ get "/composer/mentions.json",+ params: {+ names: [mixed_case_group.name.upcase],+ allowed_names: [mixed_case_group.name.upcase],+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body["group_reasons"]).to be_empty+ end+ end++ context "with an invalid topic" do+ it "returns an error" do+ get "/composer/mentions.json", params: { names: base_names, topic_id: -1 }+expect(response.status).to eq(403)endend