A platform for community discussion. Free, open, simple.
FIX: everyone pseudogroup roadmap part 1 (#43798)
Martin Brennane8a3809dcdb9
diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rbindex 499c1ad94e2..9cad350538e 100644--- a/app/controllers/categories_controller.rb+++ b/app/controllers/categories_controller.rb@@ -157,6 +157,21 @@ class CategoriesController < ApplicationControllerrender_serialized(@category, CategorySerializer)end+ def evaluate_permissions+ Category::EvaluatePermissions.call(service_params) do+ on_success { render json: success_json.merge(current_user_will_lose_access: false) }+ on_failed_contract { |contract| render_json_error(contract.errors.full_messages) }+ on_failed_policy(:user_will_have_access) do+ render_json_error(+ I18n.t("category.errors.self_lockout"),+ extras: {+ current_user_will_lose_access: true,+ },+ )+ end+ end+ end+MAX_DESCRIPTION_PARAM_LENGTH = CategoryCreator::MAX_DESCRIPTION_LENGTHdef creatediff --git a/app/services/category/evaluate_permissions.rb b/app/services/category/evaluate_permissions.rbnew file mode 100644index 00000000000..2499760f748--- /dev/null+++ b/app/services/category/evaluate_permissions.rb@@ -0,0 +1,33 @@+# frozen_string_literal: true++class Category::EvaluatePermissions+ include Service::Base++ params do+ attribute :group_ids, :array, default: -> { [] }++ validate :group_ids_are_integers++ def effective_group_ids+ group_ids.presence || [Group::AUTO_GROUPS[:staff]]+ end++ private++ def group_ids_are_integers+ errors.add(:group_ids, :invalid) if group_ids.any? { |group_id| !group_id.is_a?(Integer) }+ end+ end++ policy :user_will_have_access++ private++ # TODO (martin) When categories move to ACL, we will need to update this+ def user_will_have_access(guardian:, params:)+ # Categories still treat everyone as public, regardless of granular pseudogroup behavior.+ return true if params.effective_group_ids.include?(Group::AUTO_GROUPS[:everyone])++ guardian.is_admin? || guardian.user.in_any_groups?(params.effective_group_ids)+ end+enddiff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 240dcc98da5..f875b311870 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -1116,6 +1116,7 @@ en:post_template: "%{replace_paragraph}\n\nUse the following paragraphs for a longer description, or to establish category guidelines or rules:\n\n- Why should people use this category? What is it for?\n\n- How exactly is this different than the other categories we already have?\n\n- What should topics in this category generally contain?\n\n- Do we need this category? Can we merge with another category, or subcategory?\n"errors:not_found: "Category not found!"+ self_lockout: "You are about to change category permissions in a way that will remove your own access. Are you sure you want to proceed?"uncategorized_parent: "Uncategorized can't have a parent category"self_parent: "A subcategory's parent cannot be itself"depth: "You can't nest a subcategory under another"@@ -3187,7 +3188,7 @@ en:experimental_impersonation_time_limit_minutes: "How long before an impersonation session is automatically ended."page_loading_indicator: "Configure the loading indicator which appears during page navigations within Discourse. 'Spinner' is a full page indicator. 'Slider' shows a narrow bar at the top of the screen."show_user_menu_avatars: "Show user avatars in the user menu"- about_page_hidden_groups: "Do not show members of specific groups on the /about page."+ about_page_hidden_groups: "Do not show admins or moderators who are also members of these specific groups on the /about page."about_page_extra_groups: "Groups to show on the about page below the moderators."about_page_extra_groups_initial_members: "Number of members to expand on each group on the about page."about_page_extra_groups_show_description: "Whether to include the group descriptions on the about page."diff --git a/config/routes.rb b/config/routes.rbindex 6b7224189fa..1cb2cc9be6c 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -1431,6 +1431,7 @@ Discourse::Application.routes.draw doget "/c", to: redirect(relative_url_root + "categories")resources :categories, only: %i[index create update destroy]+ post "categories/evaluate_permissions" => "categories#evaluate_permissions"post "categories/:id/convert_nested_replies" => "categories#convert_nested_replies"post "categories/reorder" => "categories#reorder"get "categories/types" => "categories#types"diff --git a/config/site_settings.yml b/config/site_settings.ymlindex 3be744dbe68..801820c62b2 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -557,7 +557,7 @@ basic:about_page_hidden_groups:default: ""type: group_list- disallowed_groups: "4"+ disallowed_groups: "0|4|5"area: "group_permissions"about_page_extra_groups:client: truediff --git a/frontend/discourse/admin/controllers/edit-category/tabs.js b/frontend/discourse/admin/controllers/edit-category/tabs.jsindex ea17776c081..a47e3a5c78e 100644--- a/frontend/discourse/admin/controllers/edit-category/tabs.js+++ b/frontend/discourse/admin/controllers/edit-category/tabs.js@@ -5,7 +5,6 @@ import { next } from "@ember/runloop";import { service } from "@ember/service";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";-import { AUTO_GROUPS } from "discourse/lib/constants";import { registeredEditCategoryTabs } from "discourse/lib/edit-category-tabs";import getURL from "discourse/lib/get-url";import { homepageNavigationDestination } from "discourse/lib/homepage-router-overrides";@@ -87,7 +86,6 @@ const DISCUSSION_TYPE_ID = "discussion";* @property {boolean} isDirty*/export default class EditCategoryTabsController extends Controller {- @service currentUser;@service dialog;@service site;@service siteSettings;@@ -373,12 +371,18 @@ export default class EditCategoryTabsController extends Controller {const { visibility, ...categoryData } = data;this.model.setProperties(categoryData);- // If permissions is empty or not set, ensure it's an empty array (public category)+ // Category serialization converts an empty permission list to staff-only access.if (!this.model.permissions?.length) {this.model.set("permissions", []);}- const lostAccess = this._wouldLoseAccess();+ let lostAccess;+ try {+ lostAccess = await this.#wouldLoseAccess();+ } catch (error) {+ popupAjaxError(error);+ return;+ }if (lostAccess) {const confirmed = await this.dialog.yesNoConfirm({@@ -541,27 +545,25 @@ export default class EditCategoryTabsController extends Controller {});}- _wouldLoseAccess() {- if (this.currentUser.admin) {+ async #wouldLoseAccess(category = this.model) {+ try {+ await ajax("/categories/evaluate_permissions.json", {+ type: "POST",+ contentType: "application/json",+ data: JSON.stringify({+ group_ids: category.permissions.map(+ (permission) => permission.group_id+ ),+ }),+ });return false;- }+ } catch (error) {+ if (error.jqXHR?.responseJSON?.extras?.current_user_will_lose_access) {+ return true;+ }- const permissions = this.model.permissions;- if (!permissions?.length) {- return false;+ throw error;}-- const userGroupIds = new Set(- this.currentUser.visibleGroups.map((g) => g.id)- );-- // TODO (martin) Update this with granular_anonymous_and_logged_in_groups_permissions to- // do a server-side check, since this is only checking against the current user's visible- // groups, it should check against _all_ their groups.- return !permissions.some(- (p) =>- p.group_id === AUTO_GROUPS.everyone.id || userGroupIds.has(p.group_id)- );}_stashVisibleSiteTexts() {diff --git a/frontend/discourse/tests/helpers/create-pretender.js b/frontend/discourse/tests/helpers/create-pretender.jsindex ef4e92ee46f..7b0bab303b3 100644--- a/frontend/discourse/tests/helpers/create-pretender.js+++ b/frontend/discourse/tests/helpers/create-pretender.js@@ -719,6 +719,13 @@ export function applyDefaultHandlers() {return response({ category });});+ pretender.post("/categories/evaluate_permissions.json", () =>+ response({+ success: "OK",+ current_user_will_lose_access: false,+ })+ );+pretender.post("/categories", () =>response(fixturesByUrl["/c/11/show.json"]));diff --git a/frontend/discourse/tests/unit/controllers/edit-category-tabs-test.js b/frontend/discourse/tests/unit/controllers/edit-category-tabs-test.jsindex 8af238793de..f54768d0b94 100644--- a/frontend/discourse/tests/unit/controllers/edit-category-tabs-test.js+++ b/frontend/discourse/tests/unit/controllers/edit-category-tabs-test.js@@ -1,8 +1,10 @@import { getOwner } from "@ember/owner";import { setupTest } from "ember-qunit";import { module, test } from "qunit";+import sinon from "sinon";import pretender, {parsePostData,+ response,} from "discourse/tests/helpers/create-pretender";function fakeFormApi(siteTexts = {}) {@@ -24,6 +26,31 @@ function fakeFormApi(siteTexts = {}) {};}+function setupCategoryModel(controller, permissions) {+ const savedCategory = { category_types: {}, id: 1 };+ const updatedCategory = {+ id: 1,+ setupGroupsAndPermissions() {},+ };++ controller.model = {+ categoryTypes: {},+ id: 1,+ permissions,+ save: sinon.stub().resolves({ category: savedCategory }),+ set(name, value) {+ this[name] = value;+ },+ setProperties(properties) {+ Object.assign(this, properties);+ },+ };++ sinon.stub(controller.site, "updateCategory").returns(updatedCategory);++ return controller.model;+}+module("Unit | Controller | edit-category-tabs", function (hooks) {setupTest(hooks);@@ -109,6 +136,89 @@ module("Unit | Controller | edit-category-tabs", function (hooks) {);});+ test("saveCategory evaluates the proposed group IDs before saving", async function (assert) {+ const permissions = [+ { group_id: 12, permission_type: 1 },+ { group_id: 34, permission_type: 2 },+ ];+ const model = setupCategoryModel(this.controller, permissions);+ let evaluatedGroupIds;++ pretender.post("/categories/evaluate_permissions.json", (request) => {+ evaluatedGroupIds = JSON.parse(request.requestBody).group_ids;+ return response({ success: "OK", current_user_will_lose_access: false });+ });++ await this.controller.saveCategory({ permissions });++ assert.deepEqual(+ evaluatedGroupIds,+ [12, 34],+ "the evaluation receives every proposed group ID"+ );+ assert.true(+ model.save.calledOnce,+ "the category is saved after evaluation"+ );+ });++ test("saveCategory stops when the user cancels an access-loss warning", async function (assert) {+ const permissions = [{ group_id: 12, permission_type: 1 }];+ const model = setupCategoryModel(this.controller, permissions);+ const confirm = sinon+ .stub(this.controller.dialog, "yesNoConfirm")+ .resolves(false);++ pretender.post("/categories/evaluate_permissions.json", () =>+ response(422, {+ errors: ["You will lose access."],+ extras: { current_user_will_lose_access: true },+ })+ );++ await this.controller.saveCategory({ permissions });++ assert.true(confirm.calledOnce, "the access-loss warning is shown");+ assert.false(model.save.called, "the category is not saved");+ });++ test("saveCategory proceeds when the user confirms an access-loss warning", async function (assert) {+ const permissions = [{ group_id: 12, permission_type: 1 }];+ const model = setupCategoryModel(this.controller, permissions);+ sinon.stub(this.controller.dialog, "yesNoConfirm").resolves(true);+ const transitionTo = sinon.stub(this.controller.router, "transitionTo");++ pretender.post("/categories/evaluate_permissions.json", () =>+ response(422, {+ errors: ["You will lose access."],+ extras: { current_user_will_lose_access: true },+ })+ );++ await this.controller.saveCategory({ permissions });++ assert.true(model.save.calledOnce, "the category is saved");+ assert.true(+ transitionTo.calledOnce,+ "the user is redirected after losing access"+ );+ });++ test("saveCategory reports an unexpected evaluation error without saving", async function (assert) {+ const permissions = [{ group_id: 12, permission_type: 1 }];+ const model = setupCategoryModel(this.controller, permissions);+ const alert = sinon.stub(this.controller.dialog, "alert");++ pretender.post("/categories/evaluate_permissions.json", () =>+ response(500, { errors: ["Evaluation failed."] })+ );++ await this.controller.saveCategory({ permissions });++ assert.true(alert.calledOnce, "the evaluation error is shown");+ assert.false(model.save.called, "the category is not saved");+ });+test("saving writes customizable text for every edited language at once", async function (assert) {const key = "js.solved.shared_issue.label";const name = "st_label";diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-translation-topic-admin.gjs b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-translation-topic-admin.gjsindex 765f4991870..077c93f6baa 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-translation-topic-admin.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-translation-topic-admin.gjs@@ -22,16 +22,7 @@ export default apiInitializer((api) => {return;}- const allowedGroups = settings.content_localization_allowed_groups- .split("|")- .map((id) => parseInt(id, 10));-- const userGroupIds = currentUser.groups.map((g) => g.id);- const hasPermission = allowedGroups.some((groupId) =>- userGroupIds.includes(groupId)- );-- if (!hasPermission) {+ if (!currentUser.in_any_content_localization_allowed_groups) {return;}diff --git a/plugins/discourse-ai/lib/guardian_extensions.rb b/plugins/discourse-ai/lib/guardian_extensions.rbindex e65bcaee501..8af60bf77bf 100644--- a/plugins/discourse-ai/lib/guardian_extensions.rb+++ b/plugins/discourse-ai/lib/guardian_extensions.rb@@ -6,12 +6,7 @@ module DiscourseAireturn false if !SiteSetting.ai_summarization_enabledif target.class == Topic && target.private_message?- allowed =- SiteSetting.ai_pm_summarization_allowed_groups_map.any? do |group_id|- user.group_ids.include?(group_id)- end-- return false if !allowed+ return false if !in_any_groups?(SiteSetting.ai_pm_summarization_allowed_groups_map)endcan_summarize = can_request_summary?@@ -54,7 +49,7 @@ module DiscourseAireturn falseend- ai_agent.allowed_group_ids.to_a.any? { |group_id| user.group_ids.include?(group_id) }+ in_any_groups?(ai_agent.allowed_group_ids.to_a)enddef can_debug_ai_bot_conversation?(target)@@ -67,7 +62,7 @@ module DiscourseAireturn falseend- user.in_any_groups?(SiteSetting.ai_bot_debugging_allowed_groups_map)+ in_any_groups?(SiteSetting.ai_bot_debugging_allowed_groups_map)enddef can_send_pm_to_ai_bot?(target)@@ -86,7 +81,7 @@ module DiscourseAireturn falseend- return false if !user.in_any_groups?(SiteSetting.ai_bot_public_sharing_allowed_groups_map)+ return false if !in_any_groups?(SiteSetting.ai_bot_public_sharing_allowed_groups_map)# In future we may add other valid targets for AI conversation sharing,# for now we only support topics.diff --git a/plugins/discourse-ai/lib/translation/entry_point.rb b/plugins/discourse-ai/lib/translation/entry_point.rbindex 5a3339b5043..5c35200f489 100644--- a/plugins/discourse-ai/lib/translation/entry_point.rb+++ b/plugins/discourse-ai/lib/translation/entry_point.rb@@ -71,6 +71,10 @@ module DiscourseAiSiteSetting.ai_translation_backfill_start_date = 5.days.ago.utc.to_date.iso8601endend++ plugin.add_to_serializer(:current_user, :in_any_content_localization_allowed_groups) do+ object.in_any_groups?(SiteSetting.content_localization_allowed_groups_map)+ endendendenddiff --git a/plugins/discourse-templates/config/settings.yml b/plugins/discourse-templates/config/settings.ymlindex 215f3c79ff5..a07ce9c8e5f 100644--- a/plugins/discourse-templates/config/settings.yml+++ b/plugins/discourse-templates/config/settings.yml@@ -13,7 +13,9 @@ discourse_templates:type: booleandiscourse_templates_groups_allowed_private_templates:default: ""+ mandatory_values: "1|2"type: group_list+ disallowed_groups: "4"discourse_templates_private_templates_tags:default: ""type: tag_listdiff --git a/plugins/discourse-templates/lib/discourse_templates/user_extension.rb b/plugins/discourse-templates/lib/discourse_templates/user_extension.rbindex b74f7badec1..1c0eedba26d 100644--- a/plugins/discourse-templates/lib/discourse_templates/user_extension.rb+++ b/plugins/discourse-templates/lib/discourse_templates/user_extension.rb@@ -25,16 +25,7 @@ module DiscourseTemplates::UserExtensionreturn false unless SiteSetting.discourse_templates_enable_private_templatesreturn false unless SiteSetting.tagging_enabledreturn false if SiteSetting.discourse_templates_private_templates_tags.blank?- return true if guardian.is_staff?- allowed_groups_ids =- SiteSetting.discourse_templates_groups_allowed_private_templates&.split("|")&.map(&:to_i)-- allowed_groups_ids.any? do |group_id|- return true if group_id == Group::AUTO_GROUPS[:everyone]-- # the user can use templates if belongs to at least one of the allowed groups- GroupUser.exists?(group_id: group_id, user_id: id)- end+ in_any_groups?(SiteSetting.discourse_templates_groups_allowed_private_templates_map)endenddiff --git a/plugins/discourse-templates/spec/lib/user_extension_spec.rb b/plugins/discourse-templates/spec/lib/user_extension_spec.rbindex 175247afb96..434b9183b12 100644--- a/plugins/discourse-templates/spec/lib/user_extension_spec.rb+++ b/plugins/discourse-templates/spec/lib/user_extension_spec.rb@@ -107,16 +107,6 @@ describe DiscourseTemplates::UserExtension doexpect(user.can_use_private_templates?).to eq(false)end- it "is true when group is 'everyone'" do- expect(admin.can_use_private_templates?).to eq(true)- expect(moderator.can_use_private_templates?).to eq(true)- expect(user.can_use_private_templates?).to eq(false)-- SiteSetting.discourse_templates_groups_allowed_private_templates =- Group::AUTO_GROUPS[:everyone].to_s- expect(user.can_use_private_templates?).to eq(true)- end-it "only returns true to staff or members of the allowed groups" doexpect(admin.can_use_private_templates?).to eq(true)expect(moderator.can_use_private_templates?).to eq(true)diff --git a/spec/requests/categories_controller_spec.rb b/spec/requests/categories_controller_spec.rbindex 806523f376b..28f5456c69b 100644--- a/spec/requests/categories_controller_spec.rb+++ b/spec/requests/categories_controller_spec.rb@@ -538,6 +538,92 @@ RSpec.describe CategoriesController doendend+ describe "#evaluate_permissions" do+ fab!(:permitted_group) { Fabricate(:group, visibility_level: Group.visibility_levels[:owners]) }++ it "requires the user to be logged in" do+ post "/categories/evaluate_permissions.json",+ params: {+ group_ids: [permitted_group.id],+ },+ as: :json++ expect(response.status).to eq(403)+ end++ context "when a moderator evaluates public permissions" do+ fab!(:moderator)++ [false, true].each do |granular_permissions|+ it "retains access with granular pseudogroup behavior #{granular_permissions}" do+ SiteSetting.granular_anonymous_and_logged_in_groups_permissions = granular_permissions+ sign_in(moderator)+ category.set_permissions(everyone: :readonly)+ category.save!++ expect(moderator.guardian.can_see_category?(category)).to eq(true)++ post "/categories/evaluate_permissions.json",+ params: {+ group_ids: [Group::AUTO_GROUPS[:everyone]],+ },+ as: :json++ expect(response.status).to eq(200)+ expect(response.parsed_body).to include(+ "success" => "OK",+ "current_user_will_lose_access" => false,+ )+ end+ end+ end++ context "when logged in" do+ before { sign_in(user) }++ it "reports that the user retains access through a hidden group membership" do+ permitted_group.add(user)++ post "/categories/evaluate_permissions.json",+ params: {+ group_ids: [permitted_group.id],+ },+ as: :json++ expect(response.status).to eq(200)+ expect(response.parsed_body).to include(+ "success" => "OK",+ "current_user_will_lose_access" => false,+ )+ end++ it "warns when the user would lose access" do+ post "/categories/evaluate_permissions.json",+ params: {+ group_ids: [permitted_group.id],+ },+ as: :json++ expect(response.status).to eq(422)+ expect(response.parsed_body).to eq(+ {+ "errors" => [I18n.t("category.errors.self_lockout")],+ "extras" => {+ "current_user_will_lose_access" => true,+ },+ },+ )+ end++ it "rejects non-integer group IDs" do+ post "/categories/evaluate_permissions.json", params: { group_ids: ["invalid"] }, as: :json++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to contain_exactly("Group ids is invalid")+ end+ end+ end+describe "#create" doit "requires the user to be logged in" dopost "/categories.json"diff --git a/spec/services/category/evaluate_permissions_spec.rb b/spec/services/category/evaluate_permissions_spec.rbnew file mode 100644index 00000000000..d42ecdce328--- /dev/null+++ b/spec/services/category/evaluate_permissions_spec.rb@@ -0,0 +1,93 @@+# frozen_string_literal: true++RSpec.describe Category::EvaluatePermissions do+ describe described_class::Contract, type: :model do+ it { is_expected.to allow_values([], [1, 2]).for(:group_ids) }+ it { is_expected.not_to allow_values(["invalid"], [nil], [1, "invalid"]).for(:group_ids) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:current_user, :user)+ fab!(:group)+ fab!(:hidden_group) { Fabricate(:group, visibility_level: Group.visibility_levels[:owners]) }++ let(:params) { { group_ids: [group.id] } }+ let(:dependencies) { { guardian: current_user.guardian } }++ context "when the contract is invalid" do+ let(:params) { { group_ids: ["invalid"] } }++ it { is_expected.to fail_a_contract }+ end++ context "when the current user is an admin" do+ fab!(:current_user, :admin)++ it { is_expected.to run_successfully }+ end++ context "when the current user belongs to a permitted group" do+ before do+ group.add(current_user)+ current_user.reload+ end++ it { is_expected.to run_successfully }+ end++ context "when the current user's permitted group is hidden from them" do+ let(:params) { { group_ids: [hidden_group.id] } }++ before do+ hidden_group.add(current_user)+ current_user.reload+ end++ it { is_expected.to run_successfully }+ end++ context "when the current user does not belong to a permitted group" do+ it { is_expected.to fail_a_policy(:user_will_have_access) }+ end++ context "when permissions are empty and the current user is not staff" do+ let(:params) { { group_ids: [] } }++ it { is_expected.to fail_a_policy(:user_will_have_access) }+ end++ context "when permissions are empty and the current user is a moderator" do+ fab!(:current_user, :moderator)++ let(:params) { { group_ids: [] } }++ it { is_expected.to run_successfully }+ end++ context "when everyone is permitted with legacy pseudogroup behavior" do+ let(:params) { { group_ids: [Group::AUTO_GROUPS[:everyone]] } }++ before { SiteSetting.granular_anonymous_and_logged_in_groups_permissions = false }++ it { is_expected.to run_successfully }+ end++ context "when everyone is permitted with granular pseudogroup behavior" do+ let(:params) { { group_ids: [Group::AUTO_GROUPS[:everyone]] } }++ before { SiteSetting.granular_anonymous_and_logged_in_groups_permissions = true }++ it { is_expected.to run_successfully }+ end++ context "when logged-in users are permitted with granular pseudogroup behavior" do+ let(:params) { { group_ids: [Group::AUTO_GROUPS[:logged_in_users]] } }++ before { SiteSetting.granular_anonymous_and_logged_in_groups_permissions = true }++ it { is_expected.to run_successfully }+ end+ end+end