A platform for community discussion. Free, open, simple.
FEATURE: Access control list UI and backend (#41009)
Martin Brennan5823e4e3b246
diff --git a/.skills/discourse-acl-authoring/SKILL.md b/.skills/discourse-acl-authoring/SKILL.mdnew file mode 100644index 00000000000..9c5ad37b7b0--- /dev/null+++ b/.skills/discourse-acl-authoring/SKILL.md@@ -0,0 +1,40 @@+---+name: discourse-acl-authoring+description: Use when creating, editing, or reviewing Discourse access-control-list features built on AccessControlList, AclTarget, Guardian ACL helpers, AccessControlListManager, mandatory_acl, Site access_control metadata, plugin ACL target registration, or the DAccessControl UI component.+---++# Discourse ACL Authoring++Use this skill before adding or reviewing ACL-backed resource permissions in Discourse core or plugins.++## Workflow++1. Identify the target resource and desired permission vocabulary. Prefer simple strings such as `view`, `edit`, and `manage`, but confirm the target's domain semantics.+2. Read [references/backend-model.md](references/backend-model.md) when touching `AccessControlList`, `AclTarget`, `Acl::Target`, `Acl::User`, `Guardian`, `User#permission_acl`, or target visibility queries.+3. Read [references/manager-and-plugin-integration.md](references/manager-and-plugin-integration.md) when writing ACLs, creating target models, registering plugin target classes, serializing ACLs, or integrating services/controllers.+4. Read [references/frontend-d-access-control.md](references/frontend-d-access-control.md) when using or customizing `DAccessControl`.+5. Read [references/testing-and-review.md](references/testing-and-review.md) when adding specs or reviewing an ACL feature.+6. Also load `.skills/discourse-service-authoring` for `Service::Base` changes, `.skills/discourse-writing-rspec-tests` for RSpec, and `.skills/discourse-writing-js-tests` for QUnit.++## Non-Negotiables++- Put authorization at the caller boundary before `AccessControlListManager.call`; the manager is a destructive replacement service and currently assumes the caller already authorized the actor.+- Always call `AccessControlListManager` for writes, including empty submitted ACL arrays, so mandatory ACLs are injected and old rows are replaced intentionally.+- Treat `AccessControlList.flattened_list` as the API shape for UI/client payloads and `AccessControlList.expand_list` as the DB insert shape.+- Use Guardian ACL helpers or `AclTarget` visibility scopes for checks and target scopes instead of hand-querying ACL tables in controllers.+- Register plugin ACL targets with `DiscoursePluginRegistry.register_acl_target_class` so `Site#access_control` exposes mandatory ACL metadata to the frontend.+- Do not claim user ACL support is complete. Current authoring and UI flows are group-first; `allowed_user_ids` and user entries exist in lower layers but are not fully wired by `expand_list`, `preload_allowed`, cleanup jobs, or `DAccessControl`.++## Local Anchors++- Model and relation API: `app/models/access_control_list.rb`+- Target concern: `app/models/concerns/acl_target.rb`+- Permission lookup objects: `lib/acl/target.rb`, `lib/acl/user.rb`+- Guardian helpers: `lib/guardian.rb`+- User ACL cache: `app/models/user.rb`+- Write manager: `app/services/access_control_list_manager.rb`+- Deleted group cleanup: `app/jobs/regular/cleanup_acls_for_deleted.rb`, `app/models/group.rb`+- Site metadata: `app/models/site.rb`, `app/serializers/site_serializer.rb`+- Frontend component: `frontend/discourse/app/ui-kit/d-access-control.gjs`+- Core specs: `spec/models/access_control_list_spec.rb`, `spec/models/concerns/acl_target_spec.rb`, `spec/lib/acl/target_spec.rb`, `spec/jobs/regular/cleanup_acls_for_deleted_spec.rb`, `spec/services/access_control_list_manager_spec.rb`, `spec/serializers/site_serializer_spec.rb`, `frontend/discourse/tests/integration/components/d-access-control-test.gjs`+- Plugin consumer example: `plugins/discourse-kanban` or the external `discourse-kanban` checkout when present.diff --git a/.skills/discourse-acl-authoring/agents/openai.yaml b/.skills/discourse-acl-authoring/agents/openai.yamlnew file mode 100644index 00000000000..115142840cb--- /dev/null+++ b/.skills/discourse-acl-authoring/agents/openai.yaml@@ -0,0 +1,7 @@+interface:+ display_name: "Discourse ACL Authoring"+ short_description: "Build Discourse ACL-backed features"+ default_prompt: "Use $discourse-acl-authoring to add or review ACL-backed access control in Discourse."++policy:+ allow_implicit_invocation: truediff --git a/.skills/discourse-acl-authoring/references/backend-model.md b/.skills/discourse-acl-authoring/references/backend-model.mdnew file mode 100644index 00000000000..f90ae6f2268--- /dev/null+++ b/.skills/discourse-acl-authoring/references/backend-model.md@@ -0,0 +1,174 @@+# Backend Model and Permission Lookups++Use this reference when working with `AccessControlList`, `AclTarget`, `Acl::Target`, `Acl::User`, `Guardian`, or target visibility queries.++## Data Shape++`AccessControlList` stores one row per `(target_type, target_id, permission)`.++Important columns:++- `target_type`, `target_id`: polymorphic target.+- `permission`: freeform string such as `view`, `edit`, `manage`, or target-specific permissions.+- `allowed_group_ids`: bigint array of groups that hold the permission.+- `allowed_user_ids`: bigint array exists, but current authoring/UI support is incomplete.+- `owner`: string identifying the owning subsystem, usually `"core"` or a plugin name.++The model has a uniqueness validation and DB index for target + permission. Multiple groups for the same permission collapse into one row.++## Flattened vs Expanded ACLs++The frontend and service params use flattened entries:++```ruby+[+ { type: "group", id: group.id, permission: "view" },+ { type: "group", id: other_group.id, permission: "edit" },+]+```++`AccessControlList.expand_list(list, target, owner)` groups those entries by permission and returns rows suitable for `insert_all!`.++`AccessControlList.where(target: target).flattened_list` returns one entry per group per permission, including group metadata:++```ruby+{+ type: :group,+ id: group.id,+ permission: "view",+ mandatory: false,+ name: group.name,+ full_name: group.full_name,+ metadata: { auto_group: group.automatic? },+ target_id: target.id,+ target_type: target.class.polymorphic_name,+}+```++Pass `for_target:` only when every row is for the same target; mixed targets raise `Acl::MixedTargetError`.++## Matching Users and Groups++`AccessControlList.matching_user(user)` returns ACL rows applying to a user:++- Anonymous users match `Group::AUTO_GROUPS[:anonymous_users]`.+- Anonymous users also match `everyone` while `SiteSetting.granular_anonymous_and_logged_in_groups_permissions` is disabled.+- Logged-in users match direct user rows, `user.belonging_to_group_ids`, and `logged_in_users`.+- Logged-in users match `everyone` only while `SiteSetting.granular_anonymous_and_logged_in_groups_permissions` is disabled.++`AccessControlList.matching_group(group)` returns ACL rows granted directly to the group or directly to users in that group.++Use `AccessControlList.preload_allowed` before flattening relations that may include many rows. It batches group lookup and memoizes `allowed_groups_preloaded`; user preloading is still a TODO.++## Lookup Objects++`AccessControlList#target_acl(target)` builds `Acl::Target` for a single target:++```ruby+target.permission_acl.group_has_permission?(group, "view")+target.permission_acl.group_has_any_permission?(group.id, %w[edit manage])+target.permission_acl.permission_group_ids("view")+target.permission_acl.group_ids_with_any_permission(%w[view edit manage])+```++`permission_group_ids` and `group_ids_with_any_permission` return defensive array copies. Missing permissions return `[]`, not `nil`.++`AccessControlList#user_acl` builds `Acl::User` for a user:++```ruby+user.permission_acl.has_target_permission?(target, "view")+user.permission_acl.has_any_target_permission?(target, %w[edit manage])+user.permission_acl.target_ids_with_permission(TargetClass, "view")+user.permission_acl.target_ids_with_any_permissions(TargetClass, %w[view edit])+```++`User#permission_acl` and `Guardian::AnonymousUser#permission_acl` cache these lookups. Reload target records before reusing `target.permission_acl` after ACL writes.++## Guardian Helpers++Use the helper methods on `Guardian` instead of reaching into `user.permission_acl` from controllers:++```ruby+guardian.has_acl_permission?(target, "view")+guardian.has_any_acl_permission?(target, %w[edit manage])+guardian.target_ids_with_acl_permission(TargetClass, "view")+guardian.target_ids_with_any_acl_permissions(TargetClass, %w[view edit manage])+```++Models that include `AclTarget` also get visibility scopes:++```ruby+Board.with_acl_permission(guardian, "view")+Board.with_any_acl_permissions(guardian, %w[view edit manage])+```++Prefer these scopes for model index queries when they compose better with other filters. Use Guardian target-id helpers when the caller needs ids for more custom query construction.++Build domain-specific Guardian methods around those helpers:++```ruby+def can_read_board?(board)+ return true if board.anonymous_can_read?+ return true if can_write_board?(board)++ has_acl_permission?(board, "view")+end++def can_write_board?(board)+ has_any_acl_permission?(board, %w[edit manage])+end+```++If a permission also requires a global gate, make that explicit in the domain method name/copy. For example, a site setting gate plus ACL `manage` is not the same as ACL `manage` alone.++## AclTarget++Include `AclTarget` in any model that owns ACL rows:++```ruby+class Board < ActiveRecord::Base+ include AclTarget+end+```++The concern provides:++- `has_many :access_control_lists, as: :target, dependent: :destroy`+- `permission_acl`, backed by `AccessControlList.where(target: self).target_acl(self)`+- reload cache clearing for `@permission_acl`+- `.with_acl_permission(guardian, permission)`+- `.with_any_acl_permissions(guardian, permissions)`+- `.acl_target_key`, defaulting to `name`+- `.has_mandatory_acl?`+- `.acl_is_mandatory?(acl)`+- `mandatory_acl_as_expanded_list(owner)`++`AclTarget.acl_matches?(acl_a, acl_b)` is the shared comparator for mandatory ACL matching. It normalizes `type` to symbols and compares `permission` as strings.++## Mandatory ACLs++Define `self.mandatory_acl` on the target class when some grants must always exist:++```ruby+def self.mandatory_acl+ [{ type: :group, id: Group::AUTO_GROUPS[:admins], permission: "manage" }]+end+```++Mandatory entries are consumed by both backend writes and frontend rendering:++- `AccessControlList.inject_mandatory_acl(flattened_acl, target)` appends missing mandatory entries.+- `AccessControlListManager` calls that method before inserting rows.+- `flattened_list` marks matching entries with `mandatory: true`.+- `Site#access_control` exposes mandatory ACL metadata for registered targets.++Keep mandatory ACLs group-based unless user ACL support has been completed end-to-end.++## Stale References++`flattened_list` is defensive around stale data:++- Unknown `target_type` values are logged and skipped when no `for_target:` is provided.+- Deleted groups are skipped instead of raising while flattening.++This is a read-path fallback, not a substitute for validation. Validate group ids at the service/contract boundary, and rely on `Jobs::CleanupAclsForDeleted` to remove deleted group ids from persisted ACL rows.diff --git a/.skills/discourse-acl-authoring/references/frontend-d-access-control.md b/.skills/discourse-acl-authoring/references/frontend-d-access-control.mdnew file mode 100644index 00000000000..4fa895821d5--- /dev/null+++ b/.skills/discourse-acl-authoring/references/frontend-d-access-control.md@@ -0,0 +1,130 @@+# DAccessControl Frontend Usage++Use this reference when adding or reviewing UI that lets users edit ACLs.++## Component Contract++Import:++```gjs+import DAccessControl from "discourse/ui-kit/d-access-control";+```++Basic usage:++```gjs+<DAccessControl+ @groups={{this.site.groups}}+ @acl={{field.value}}+ @aclTarget="DiscourseKanban::Board"+ @onChange={{this.aclChanged}}+ @transformPermissionOptions={{this.transformPermissionOptions}}+/>+```++Arguments:++- `@groups`: group records available for selection. Each group should have `id`, `name`, `full_name`, and `automatic`.+- `@acl`: flattened ACL entries from the backend or form state.+- `@onChange`: called with the next flattened ACL array when the user adds/removes/changes a row.+- `@aclTarget`: optional key used to load mandatory ACL entries from `site.access_control.mandatory_acl`.+- `@transformPermissionOptions`: optional callback to customize default permission labels/descriptions or add target-specific permissions.++`@aclTarget` must match `target_class.acl_target_key`; by default this is the Ruby class name such as `"DiscourseKanban::Board"`.++## Controlled Component Behavior++`DAccessControl` is controlled by its parent. It calls `@onChange(nextAcl)` on user actions, and the parent must write the returned array back into form state.++Example:++```js+@action+aclChanged(acl) {+ this.formApi.set("acl", acl);+}+```++Mandatory ACL rows are injected for display from `this.site.access_control`. The component does not call `@onChange` during render when it injects mandatory rows. Backend saves must still call `AccessControlListManager` with the submitted ACL array so mandatory entries are injected server-side too.++## Permission Options++Default permissions:++- `view`, level 1+- `edit`, level 2+- `remove`, appended as a destructive option++Use `@transformPermissionOptions` for domain-specific copy or added permissions:++```js+@action+transformPermissionOptions(options) {+ const viewOption = options.find((option) => option.id === "view");+ viewOption.description = i18n("plugin.target.permission_view_description");++ options.push({+ id: "manage",+ level: 3,+ name: i18n("plugin.target.permission_manager"),+ description: i18n("plugin.target.permission_manager_description"),+ });++ return options;+}+```++Keep permission copy aligned with backend semantics. If a displayed `manage` role also requires a global site setting or staff gate, make that clear in the surrounding UI or choose a different label.++## Row Behavior++- Rows are sorted with mandatory rows first, then by group name.+- Mandatory rows show a lock icon, are styled with `--mandatory`, and have their permission select disabled.+- A mandatory ACL replaces an existing row for the same type/id in the component's display list.+- Newly added regular groups default to `edit`.+- Read-only default auto groups (`anonymous_users`, `everyone`, `trust_level_0`) default to `view`.+- Already selected groups are removed from the add-group chooser.+- Row DOM metadata uses `data-row-type` and `data-row-id`; tests should not rely on the old `data-group-id` attribute.++The component remains group-first. It can display entries derived from mandatory ACL metadata for groups, but it does not provide user picking or complete user ACL editing.++## FormKit Integration++When used inside a FormKit custom field:++```gjs+<form.Field+ @name="acl"+ @title={{i18n "plugin.target.access"}}+ @description={{i18n "plugin.target.access_description"}}+ @format="max"+ @type="custom"+ @validate={{this.validateAccess}}+ as |field|+>+ <field.Control>+ <DAccessControl+ @groups={{this.site.groups}}+ @acl={{field.value}}+ @aclTarget="Plugin::Target"+ @onChange={{this.aclChanged}}+ @transformPermissionOptions={{this.transformPermissionOptions}}+ />+ </field.Control>+</form.Field>+```++Validate the form state client-side for user experience, but rely on server-side validation and `AccessControlListManager` for actual enforcement.++## Testing++Core component tests live in `frontend/discourse/tests/integration/components/d-access-control-test.gjs`.++Consumer tests should cover:++- target-specific permission options are present+- `@aclTarget` renders mandatory rows from `site.access_control`+- mandatory rows are locked and not duplicated+- `@onChange` updates parent/form state when the user changes a row+- default ACL construction for new records includes expected groups, if the consumer builds defaults+- selectors use `.d-access-control__row[data-row-type="group"][data-row-id="..."]` for row assertionsdiff --git a/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md b/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.mdnew file mode 100644index 00000000000..af949b5d003--- /dev/null+++ b/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md@@ -0,0 +1,132 @@+# Manager, Services, and Plugin Integration++Use this reference when writing ACL rows, creating an ACL-backed target model, registering plugin targets, or serializing ACLs from controllers/services.++## AccessControlListManager++`AccessControlListManager` is the standard write path for replacing a target's ACLs.++```ruby+AccessControlListManager.call(+ guardian:,+ params: {+ target: board,+ flattened_acl: flattened_acl,+ owner: DiscourseKanban::PLUGIN_NAME,+ },+) do |result|+ on_success do |previous_permissions:, new_permissions:|+ # optional history/event work+ end++ on_failure do+ fail!(I18n.t("plugin.target.errors.acl_update_failed"))+ end+end+```++Behavior:++- validates `target` and `owner`+- fetches previous target permissions+- injects mandatory ACLs into `flattened_acl`+- fails `has_at_least_one_acl` if the final ACL list is empty+- destroys all current ACL rows for the target+- inserts expanded ACL rows+- logs a staff action with previous and new permission lookup data+- reloads the target after the transaction so `AclTarget#permission_acl` is rebuilt on the caller's instance++Important: the manager destructively replaces target ACL rows and does not currently authorize the actor itself. Authorize before calling it.++## Write Path Rules++- Call the manager even when the submitted ACL array is empty. Empty means "replace with mandatory ACLs if any"; skipping the manager leaves stale ACLs or creates ACL-less records.+- Do not mutate ACL rows manually from controllers. Use the manager from a service step.+- Pass a stable owner string, usually the plugin name constant.+- Keep side effects such as history rows, events, or MessageBus publishes outside the transaction unless they must roll back with the ACL write.+- When using `Service::Base`, follow `.skills/discourse-service-authoring`.++## Target Creation++For new target records with mandatory ACLs:++1. Authorize resource creation with a domain Guardian method.+2. Create the target.+3. Call `AccessControlListManager` with `flattened_acl: raw["acl"] || []`.+4. Fail the service if ACL creation fails.++This ensures mandatory ACL rows are inserted for API callers that omit `acl`.++For update flows, call the manager when ACL params are part of the contract. If ACL updates are optional, distinguish "key omitted" from "key present with empty array" deliberately.++## Plugin Target Registration++Plugin target classes must include `AclTarget` and be registered after initialization:++```ruby+after_initialize do+ DiscoursePluginRegistry.register_acl_target_class(DiscourseKanban::Board, self)+end+```++The registry is declared as `acl_target_classes` in `DiscoursePluginRegistry`. `Site#access_control` combines loaded core `AclTarget.target_classes` with plugin-registered classes and exposes mandatory ACLs by `acl_target_key`.++String registrations are allowed and resolved with `safe_constantize`; class registrations are preferred when the constant is available. Unresolved strings and registered classes that do not respond to `has_mandatory_acl?` are skipped from site metadata, with unresolved strings logged for debugging.++## Site Metadata++`SiteSerializer` includes `access_control`.++Shape:++```ruby+{+ mandatory_acl: {+ "DiscourseKanban::Board" => [+ { type: :group, id: Group::AUTO_GROUPS[:admins], permission: "manage" },+ ],+ },+}+```++The key is `target_class.acl_target_key`, which defaults to the class name. If a frontend passes `@aclTarget`, it must match this key exactly.++## Serializing Target ACLs++Use `AccessControlList.where(target: target).flattened_list` when returning ACLs to a client that edits them.++Only include ACL details for actors who can manage that specific target. Avoid using a broad global capability when per-target ACL management exists.++```ruby+def payload(target, include_acl:)+ {+ id: target.id,+ can_manage: guardian.can_manage_target?(target),+ acl: include_acl ? AccessControlList.where(target: target).flattened_list : nil,+ }+end+```++Use `TargetClass.with_acl_permission(guardian, permission)` or `TargetClass.with_any_acl_permissions(guardian, permissions)` for index scopes where the user should see targets reachable through ACLs. Use `guardian.target_ids_with_any_acl_permissions(TargetClass, permissions)` only when the id array is the cleaner interface for a custom query.++## Deleted Group Cleanup++`Group#clear_acls` enqueues `Jobs::CleanupAclsForDeleted` after a group is destroyed. The job removes the deleted group id from `allowed_group_ids`, updates `updated_at`, and deletes ACL rows with no remaining `allowed_group_ids` or `allowed_user_ids`.++User cleanup is not complete yet. Do not document deleted-user ACL cleanup as supported until the job handles `user_id`.++## Migrations++When migrating legacy permission columns into ACLs:++- Preserve previous semantics intentionally and document any security-tightening changes.+- Union mandatory ACL values into migrated rows; raw site setting rows may not include `mandatory_values`.+- Use `Group::AUTO_GROUPS` values or stable numeric IDs only when loading the Rails constants is unsafe in the migration context.+- Cover blank legacy arrays, customized group lists, and default setting fallbacks in migration specs when possible.++## Current Limitations++- `AccessControlList.expand_list` is group-first. It does not fully handle `{ type: "user" }` authoring yet.+- `preload_allowed`, `expand_list`, cleanup, and `DAccessControl` are still group-first even though lower-level matching scopes understand `allowed_user_ids`.+- `flattened_list` skips missing groups and unknown target classes defensively. Validate group IDs at the service/contract boundary where user input enters; do not rely on read-path skipping as data hygiene.+- The manager has caller-side authorization. Future core work may add a target policy hook; until then, do not expose it directly to untrusted callers.diff --git a/.skills/discourse-acl-authoring/references/testing-and-review.md b/.skills/discourse-acl-authoring/references/testing-and-review.mdnew file mode 100644index 00000000000..718a3f2de4d--- /dev/null+++ b/.skills/discourse-acl-authoring/references/testing-and-review.md@@ -0,0 +1,84 @@+# Testing and Review Checklist++Use this reference when adding specs or reviewing ACL-backed features.++## Backend Specs++For target models:++- Include `AclTarget`.+- Cover `mandatory_acl` if the target defines one.+- Cover domain helper methods such as `anonymous_can_read?` or `can_write?` that wrap `permission_acl`.+- Cover `.with_acl_permission` and `.with_any_acl_permissions` when index/list actions depend on the shared scopes.++For Guardian methods:++- Cover anonymous, logged-in, direct group membership, writer-implies-reader, and manager cases as applicable.+- Cover target-id list helpers when an index action scopes resources by ACL.+- If pseudo groups are involved, cover `granular_anonymous_and_logged_in_groups_permissions` behavior when relevant.++For services using `AccessControlListManager`:++- Creation with omitted `acl` persists mandatory ACLs.+- Creation with `acl: []` persists mandatory ACLs or fails closed when no mandatory ACL exists.+- Update with explicit `acl: []` replaces existing ACLs with mandatory ACLs.+- Update with a non-empty ACL replaces old rows and logs/records permission history if the feature has history.+- After a successful manager call, the target instance has been reloaded and should not retain a stale `permission_acl` cache.+- Unauthorized actors fail before the manager mutates ACL rows.+- Invalid group IDs fail at the service/contract boundary when user input can supply IDs.++For cleanup behavior:++- Destroying a group enqueues `:cleanup_acls_for_deleted`.+- `Jobs::CleanupAclsForDeleted` removes the group id from ACL rows.+- ACL rows with no remaining group or user ids are deleted.+- ACL rows that still have user ids are preserved.++For lookup objects:++- `Acl::Target#permission_group_ids` returns `[]` for missing permissions and a defensive copy for present permissions.+- `Acl::Target#group_ids_with_any_permission` replaces the older `multi_permission_group_ids` name.+- `Acl::User#target_ids_with_permission` and `#target_ids_with_any_permissions` return defensive array copies.++For migration specs:++- Blank legacy arrays.+- Existing read/write/manage group values.+- Default setting fallback when no setting row exists.+- Raw setting rows that omit mandatory values.++## Frontend Specs++For `DAccessControl` consumers:++- Rendered permissions match target-specific labels/descriptions.+- Mandatory ACL from `site.access_control.mandatory_acl[targetKey]` appears and is locked.+- Existing rows with the same group as a mandatory row are not duplicated.+- `onChange` writes updated ACL arrays into parent state.+- The final save payload includes the intended ACL array.++Use `.skills/discourse-writing-js-tests` for QUnit patterns.++## Review Checklist++Ask these questions during code review:++- Is every ACL write routed through `AccessControlListManager`?+- Does the caller authorize the actor before the manager can replace ACL rows?+- Does the service distinguish omitted ACL params from explicit empty ACL params when that matters?+- Are mandatory ACLs enforced in both backend writes and frontend display?+- Does the UI `@aclTarget` string match the target's `acl_target_key`?+- Is ACL serialization limited to users who can manage the specific target?+- Are list/index queries using `Target.with_acl_permission`, `Target.with_any_acl_permissions`, `guardian.target_ids_with_acl_permission`, or `target_ids_with_any_acl_permissions` instead of ad hoc SQL?+- Are group IDs validated before persistence when they come from params?+- Are plugin target classes registered with `DiscoursePluginRegistry.register_acl_target_class`?+- Do tests cover anonymous users and pseudo-group semantics if `anonymous_users`, `logged_in_users`, or `everyone` can appear in ACLs?+- Do tests cover stale group rows or missing plugin target classes if the code serializes ACLs that may outlive their original target or group?++## Known Sharp Edges++- `AccessControlListManager` currently assumes caller-side authorization.+- Group support is complete enough for current UI; user ACL support is not.+- `DAccessControl` injects mandatory rows for display but does not notify the parent on render.+- Mandatory ACLs from site settings need extra care in migrations because raw stored settings may omit `mandatory_values`.+- `flattened_list` skips stale group IDs and unknown target classes, so a missing row can disappear from serialized ACL output while cleanup or validation catches up.diff --git a/app/assets/stylesheets/common/components/_index.scss b/app/assets/stylesheets/common/components/_index.scssindex 2ac7cdcd050..078e7e0ac3c 100644--- a/app/assets/stylesheets/common/components/_index.scss+++ b/app/assets/stylesheets/common/components/_index.scss@@ -12,6 +12,7 @@@import "buttons";@import "d-segmented-control";@import "d-select";+@import "d-access-control";@import "color-input";@import "char-counter";@import "conditional-loading-section";diff --git a/app/assets/stylesheets/common/components/d-access-control.scss b/app/assets/stylesheets/common/components/d-access-control.scssnew file mode 100644index 00000000000..f681beaae9f--- /dev/null+++ b/app/assets/stylesheets/common/components/d-access-control.scss@@ -0,0 +1,62 @@+.d-access-control {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ width: 100%;++ &__chooser {+ width: 100%;+ }++ &__rows {+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ }++ &__row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-2);+ padding: var(--space-1) var(--space-2);+ border-bottom: 1px solid var(--content-border-color);++ &.--mandatory {+ color: var(--d-input-text-color--disabled);+ }+ }++ &__group-name {+ flex: 1 1 auto;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ display: flex;+ align-items: center;++ svg.d-icon {+ margin-right: var(--space-1);+ }+ }++ &__permission {+ flex: 0 0 auto;+ width: auto;+ }++ &__permission-divider {+ border-top: 1px solid var(--content-border-color);+ }++ &__permission-remove {+ .texts span {+ color: var(--danger) !important;+ }+ }++ &__add {+ width: 100%;+ }+}diff --git a/app/jobs/regular/cleanup_acls_for_deleted.rb b/app/jobs/regular/cleanup_acls_for_deleted.rbnew file mode 100644index 00000000000..c720ad5dfe8--- /dev/null+++ b/app/jobs/regular/cleanup_acls_for_deleted.rb@@ -0,0 +1,29 @@+# frozen_string_literal: true++module Jobs+ class CleanupAclsForDeleted < ::Jobs::Base+ def execute(args)+ group_id = args[:group_id]++ # TODO (martin) Handle users in a followup PR+ user_id = args[:user_id]++ return if group_id.blank? && user_id.blank?++ if group_id.present?+ AccessControlList.where("allowed_group_ids @> ARRAY[?]::bigint[]", group_id).update_all(+ [+ "allowed_group_ids = array_remove(allowed_group_ids, ?), updated_at = ?",+ group_id,+ Time.zone.now,+ ],+ )+ end++ AccessControlList+ .where("allowed_group_ids = '{}'::bigint[]")+ .where("allowed_user_ids = '{}'::bigint[]")+ .delete_all+ end+ end+enddiff --git a/app/models/access_control_list.rb b/app/models/access_control_list.rbnew file mode 100644index 00000000000..c90f35dad5c--- /dev/null+++ b/app/models/access_control_list.rb@@ -0,0 +1,286 @@+# frozen_string_literal: true++class AccessControlList < ActiveRecord::Base+ attr_accessor :allowed_groups_preloaded, :allowed_users_preloaded++ # NOTE: permission column is freeform, but some common+ # types are below. In the UI these would generally be+ # displayed as a role (e.g. adding -er), like Viewer,+ # Editor, Manager, Owner, etc:+ #+ # - view+ # - edit+ # - manage+ # - own+ #+ # For categories for example we may have:+ #+ # - view+ # - manage+ # - create_post+ # - create_topic+ #+ # Generally the creator of whatever the linked target+ # record will become an owner by default.++ belongs_to :target, polymorphic: true++ validates :target_id, uniqueness: { scope: %i[target_type permission] }++ before_create { self.owner = "core" if owner.blank? }++ def allowed_users+ @allowed_users ||= User.where(id: allowed_user_ids).to_a+ end++ def allowed_groups+ if @allowed_groups_preloaded.present?+ @allowed_groups ||= @allowed_groups_preloaded+ else+ @allowed_groups ||= Group.where(id: allowed_group_ids).to_a+ end+ end++ def self.relation+ super.extending(AccessControlListRelationMethods)+ end++ scope :allowing_user,+ ->(user_id) { where("allowed_user_ids @> ARRAY[:user_id]::bigint[]", user_id:) }+ scope :allowing_any_user,+ ->(user_ids) { where("allowed_user_ids && ARRAY[:user_ids]::bigint[]", user_ids:) }+ scope :allowing_group,+ ->(group_id) { where("allowed_group_ids @> ARRAY[:group_id]::bigint[]", group_id:) }+ scope :allowing_any_group,+ ->(group_ids) { where("allowed_group_ids && ARRAY[:group_ids]::bigint[]", group_ids:) }+ scope :allowing_users_in_group,+ ->(group_id) do+ where(+ "allowed_user_ids && ARRAY(SELECT user_id FROM group_users WHERE group_id = :group_id)::bigint[]",+ group_id:,+ )+ end+ scope :allowing_anonymous_users, -> { allowing_group(Group::AUTO_GROUPS[:anonymous_users]) }+ scope :with_permission, ->(target, permission) { where(target:, permission:) }++ scope :matching_user,+ ->(user) do+ if user.nil?+ auto_group_ids = [Group::AUTO_GROUPS[:anonymous_users]]++ # TODO (martin) Remove when granular_anonymous_and_logged_in_groups_permissions becomes permanent,+ # it's similar logic to User.in_any_groups?+ if !SiteSetting.granular_anonymous_and_logged_in_groups_permissions+ auto_group_ids << Group::AUTO_GROUPS[:everyone]+ end++ allowing_any_group(auto_group_ids)+ else+ auto_group_ids = [Group::AUTO_GROUPS[:logged_in_users]]++ # TODO (martin) Remove when granular_anonymous_and_logged_in_groups_permissions becomes permanent,+ # it's similar logic to User.in_any_groups?+ if !SiteSetting.granular_anonymous_and_logged_in_groups_permissions+ auto_group_ids << Group::AUTO_GROUPS[:everyone]+ end++ allowing_any_user([user.id]).or(+ allowing_any_group(user.belonging_to_group_ids + auto_group_ids),+ )+ end+ end++ scope :matching_group,+ ->(group) { allowing_any_group([group.id]).or(allowing_users_in_group(group.id)) }++ def self.inject_mandatory_acl(flattened_acl, target)+ return flattened_acl if !target.class.has_mandatory_acl?++ target.class.mandatory_acl.each do |mandatory_acl|+ next if flattened_acl.any? { |acl| AclTarget.acl_matches?(acl, mandatory_acl) }++ flattened_acl << mandatory_acl+ end++ flattened_acl+ end++ # Takes a list in this format, which is the same+ # format from flattened_list that will come from the UI:+ #+ # { type: "group", id: 3, permission: "edit" }]+ #+ # And converts into ACL records that can be inserted into the DB with+ # .insert_all+ def self.expand_list(list, target, owner)+ permissions_expanded =+ list.each_with_object({}) do |entry, permissions|+ permissions[entry[:permission]] ||= {}+ # TODO (martin) Handle allowed_user_ids here too in a followup PR when we allow adding them in the UI.+ permissions[entry[:permission]][:allowed_group_ids] ||= []++ if entry[:type].to_sym == :group+ permissions[entry[:permission]][:allowed_group_ids] << entry[:id]+ # TODO (martin) Handle allowed_user_ids here too in a followup PR when we allow adding them in the UI.+ end+ end++ permissions_expanded.map do |permission_name, permission|+ {+ permission: permission_name,+ # TODO (martin) Handle allowed_user_ids here too in a followup PR when we allow adding them in the UI.+ allowed_group_ids: permission[:allowed_group_ids],+ target_type: target.class.polymorphic_name,+ target_id: target.id,+ owner: owner,+ }+ end+ end++ module AccessControlListRelationMethods+ # Batch-loads the allowed users and groups for every ACL in the relation+ # using two queries total (one per table), then memoizes the records onto+ # each ACL so #allowed_users / #allowed_groups don't trigger N+1s. Returns+ # the (now loaded) relation so it stays chainable.+ def preload_allowed+ acls = to_a++ groups_by_id = Group.where(id: acls.flat_map(&:allowed_group_ids).uniq).index_by(&:id)++ # TODO (martin) Handle users here too in a followup PR+ # users_by_id = User.where(id: acls.flat_map(&:allowed_user_ids).uniq).index_by(&:id)++ acls.each do |acl|+ acl.allowed_groups_preloaded ||= acl.allowed_group_ids.filter_map { |id| groups_by_id[id] }++ # TODO (martin) Handle users here too in a followup PR+ end++ self+ end++ # Used to display a list of user/group -> permission mappings+ # in the UI, and also to construct the TargetAcl and UserAcl+ # objects used for permission checks in Ruby.+ #+ # Takes an ActiveRecord::Relation of AccessControlList records and returns+ # an array of hashes in this format:+ #+ # {+ # type: :group,+ # id: 3,+ # permission: "edit",+ # name: "Group Name", # only for groups+ # full_name: "Full Group Name", # only for groups+ # metadata: {+ # auto_group: true/false, # only for groups+ # },+ # target_id: 123, # only if for_target is not provided+ # target_type: "Category" # only if for_target is not provided+ # }+ #+ # If for_target is provided, then mixed Relations of+ # AccessControlList records with different targets will NOT+ # be allowed, as this is intended to be used for constructing+ # the TargetAcl for a specific target record e.g. a Category.+ def flattened_list(for_target: nil)+ preload_allowed++ if for_target.present?+ raise Acl::MixedTargetError if map(&:target).uniq.length > 1+ end++ flattened_list = []+ each do |access_control_list|+ target_klass =+ if for_target+ for_target.class+ else+ constantized_target = access_control_list.target_type.safe_constantize++ if constantized_target.nil?+ Rails.logger.warn(+ "[ACL] Unknown target type (#{access_control_list.target_type}) for ACL (#{access_control_list.id}), maybe the plugin is gone or the class has been renamed? Skipping...",+ )+ end++ constantized_target+ end++ next if target_klass.nil?++ access_control_list.allowed_group_ids.each do |group_id|+ allowed_group =+ access_control_list.allowed_groups_preloaded.find { |ag| ag.id == group_id }++ next if allowed_group.nil?++ mandatory =+ target_klass.acl_is_mandatory?(+ { type: :group, id: group_id, permission: access_control_list.permission },+ )++ list_entry = {+ type: :group,+ id: group_id,+ mandatory:,+ permission: access_control_list.permission,+ name: allowed_group.name,+ full_name: allowed_group.full_name,+ metadata: {+ auto_group: allowed_group.automatic?,+ },+ }++ if for_target.present?+ list_entry[:target_id] = for_target.id+ list_entry[:target_type] = target_klass.polymorphic_name+ else+ list_entry[:target_id] = access_control_list.target_id+ list_entry[:target_type] = target_klass.polymorphic_name+ end++ flattened_list << list_entry+ end++ # TODO (martin) Properly handle users in a followup PR when we allow adding+ # them in the UI.+ end++ flattened_list+ end++ # Used to easily access permissions for a single target, e.g. a Category,+ # accessed via the permission_acl method on a Model that has ACLs.+ def target_acl(target)+ ::Acl::Target.new(flattened_list(for_target: target))+ end++ # Used to easily access permissions for a single user,+ # accessed via the permission_acl method on User.+ def user_acl+ ::Acl::User.new(flattened_list)+ end+ end+end++# == Schema Information+#+# Table name: access_control_lists+#+# id :bigint not null, primary key+# allowed_group_ids :bigint default([]), not null, is an Array+# allowed_user_ids :bigint default([]), not null, is an Array+# owner :string(100) not null+# permission :string(100) not null+# target_type :string(255) not null+# created_at :datetime not null+# updated_at :datetime not null+# target_id :bigint not null+#+# Indexes+#+# idx_access_control_lists_allowed_group_ids (allowed_group_ids) USING gin+# idx_access_control_lists_allowed_user_ids (allowed_user_ids) USING gin+# idx_on_target_type_target_id_permission_f472902150 (target_type,target_id,permission) UNIQUE+#diff --git a/app/models/concerns/acl_target.rb b/app/models/concerns/acl_target.rbnew file mode 100644index 00000000000..2da848b9204--- /dev/null+++ b/app/models/concerns/acl_target.rb@@ -0,0 +1,78 @@+# frozen_string_literal: true++module AclTarget+ extend ActiveSupport::Concern++ def self.acl_matches?(acl_a, acl_b)+ acl_a[:type].to_sym == acl_b[:type].to_sym && acl_a[:id] == acl_b[:id] &&+ acl_a[:permission].to_s == acl_b[:permission].to_s+ end++ def self.target_classes+ loaded_target_classes+ end++ def self.loaded_target_classes+ @loaded_target_classes ||= []+ end++ included do+ AclTarget.loaded_target_classes << self if !AclTarget.loaded_target_classes.include?(self)++ has_many :access_control_lists,+ as: :target,+ class_name: "AccessControlList",+ dependent: :destroy++ scope :with_acl_permission,+ ->(guardian, permission) do+ where(+ id:+ AccessControlList+ .matching_user(guardian.user)+ .where(target_type: polymorphic_name, permission: permission)+ .select(:target_id),+ )+ end++ scope :with_any_acl_permissions,+ ->(guardian, permissions) do+ where(+ id:+ AccessControlList+ .matching_user(guardian.user)+ .where(target_type: polymorphic_name, permission: Array.wrap(permissions))+ .select(:target_id),+ )+ end++ def reload(options = nil)+ @permission_acl = nil+ super+ end+ end++ def permission_acl+ @permission_acl ||= AccessControlList.where(target: self).target_acl(self)+ end++ def mandatory_acl_as_expanded_list(owner)+ return [] if !self.class.has_mandatory_acl?+ AccessControlList.expand_list(self.class.mandatory_acl, self, owner)+ end++ class_methods do+ def acl_target_key+ name+ end++ def has_mandatory_acl?+ defined?(mandatory_acl).present? && mandatory_acl.length.positive?+ end++ def acl_is_mandatory?(acl)+ has_mandatory_acl? &&+ mandatory_acl.any? { |mandatory_acl| AclTarget.acl_matches?(acl, mandatory_acl) }+ end+ end+enddiff --git a/app/models/group.rb b/app/models/group.rbindex ff3808b58a0..40e78323b32 100644--- a/app/models/group.rb+++ b/app/models/group.rb@@ -62,6 +62,7 @@ class Group < ActiveRecord::Basebefore_destroy :cache_group_users_for_destroyed_event, prepend: trueafter_destroy :expire_cache+ after_destroy :clear_aclsafter_save :destroy_deletionsafter_save :update_primary_groupafter_save :update_title@@ -88,6 +89,11 @@ class Group < ActiveRecord::BaseSvgSprite.expire_cacheend+ # TODO (martin) Also do this for User when following up access_control_list+ def clear_acls+ Jobs.enqueue(:cleanup_acls_for_deleted, group_id: id)+ end+validate :name_format_validatorvalidates :name, presence: truevalidate :automatic_membership_email_domains_validator@@ -549,6 +555,9 @@ class Group < ActiveRecord::Basegroup.name = default_nameend+ group.full_name =+ I18n.t("groups.default_full_names.#{name}", locale: SiteSetting.default_locale)+# the everyone, anonymous_users, and logged_in_users groups are special — they# represent implicit populations (unauthenticated visitors, or all logged-in# users) that cannot be enumerated via group_users rows.diff --git a/app/models/site.rb b/app/models/site.rbindex ed464dae8aa..b001ea2e3c5 100644--- a/app/models/site.rb+++ b/app/models/site.rb@@ -53,6 +53,40 @@ class SiteUserField.includes(:user_field_options).order(:position).allend+ def access_control+ self.class.access_control+ end++ def self.access_control+ target_classes =+ (+ AclTarget.target_classes ++ DiscoursePluginRegistry.acl_target_classes.filter_map do |target_class|+ if target_class.is_a?(String)+ target_class = target_class.safe_constantize+ if target_class.nil?+ Rails.logger.warn(+ "[ACL] Unknown target class in plugin registry for site (#{target_class}) maybe the plugin is gone, the class has been renamed, or the class does not include AclTarget",+ )+ end+ target_class+ else+ target_class+ end+ end+ ).compact.uniq++ {+ mandatory_acl:+ target_classes.each_with_object({}) do |target_class, mandatory_acl|+ next if !target_class.respond_to?(:has_mandatory_acl?)+ next if !target_class.has_mandatory_acl?++ mandatory_acl[target_class.acl_target_key] = target_class.mandatory_acl+ end,+ }+ end+def self.categories_cache_key"site_categories_#{I18n.locale}_#{Discourse.git_version}"enddiff --git a/app/models/user.rb b/app/models/user.rbindex 2113f073642..e686460da3c 100644--- a/app/models/user.rb+++ b/app/models/user.rb@@ -583,6 +583,10 @@ class User < ActiveRecord::Base@belonging_to_group_ids ||= group_users.pluck(:group_id)end+ def permission_acl+ @permission_acl ||= AccessControlList.matching_user(self).user_acl+ end+def group_granted_trust_levelGroupUser.where(user_id: id).includes(:group).maximum("groups.grant_trust_level")end@@ -676,6 +680,7 @@ class User < ActiveRecord::Base@ignored_user_ids = nil@muted_user_ids = nil@belonging_to_group_ids = nil+ @permission_acl = nilsuperend@@ -1784,6 +1789,7 @@ class User < ActiveRecord::Baseend@belonging_to_group_ids = nil+ @permission_acl = nilenddef emaildiff --git a/app/models/user_history.rb b/app/models/user_history.rbindex b090bfa9fc8..1dd770d8aaf 100644--- a/app/models/user_history.rb+++ b/app/models/user_history.rb@@ -169,6 +169,7 @@ class UserHistory < ActiveRecord::Baseupcoming_change_available: 124,notified_about_composer_education: 125, # not used anymorerecover_post: 126,+ change_access_control_list_permissions: 127,)end@@ -297,6 +298,7 @@ class UserHistory < ActiveRecord::Baseupcoming_change_toggledchange_site_setting_groupsupcoming_change_available+ change_access_control_list_permissions]enddiff --git a/app/serializers/site_serializer.rb b/app/serializers/site_serializer.rbindex 146bcbd5a85..4161fd6eedf 100644--- a/app/serializers/site_serializer.rb+++ b/app/serializers/site_serializer.rb@@ -54,6 +54,7 @@ class SiteSerializer < ApplicationSerializer:admin_config_login_routes,:email_configured,:upcoming_changes_with_css,+ :access_control,)has_many :archetypes, embed: :objects, serializer: ArchetypeSerializer@@ -131,6 +132,7 @@ class SiteSerializer < ApplicationSerializer.select(:id,:name,+ :full_name,:flair_icon,:flair_upload_id,:flair_bg_color,@@ -141,6 +143,7 @@ class SiteSerializer < ApplicationSerializer{id: g.id,name: g.name,+ full_name: g.full_name.presence || g.name,flair_url: g.flair_url,flair_bg_color: g.flair_bg_color,flair_color: g.flair_color,diff --git a/app/services/access_control_list_manager.rb b/app/services/access_control_list_manager.rbnew file mode 100644index 00000000000..acd775c07c1--- /dev/null+++ b/app/services/access_control_list_manager.rb@@ -0,0 +1,71 @@+# frozen_string_literal: true++class AccessControlListManager+ include Service::Base++ params do+ attribute :target+ attribute :flattened_acl, :array+ attribute :owner, :string++ validates :target, presence: true+ validates :owner, presence: true, length: { maximum: 100 }+ end++ # NOTE (martin): Maybe we need some way of defining a policy here to see+ # if the guardian has the permission to change ACLs for the target?+ # For now, we assume that the caller of this service has already done the+ # necessary guardian checks (e.g. can_manage_board? for a kanban board)++ model :previous_permissions, optional: true+ model :flattened_acl_with_mandatory, optional: true+ policy :has_at_least_one_acl++ transaction do+ step :destroy_acls+ step :insert_acls+ step :log_permission_changes+ end++ step :reload_target++ private++ def fetch_previous_permissions(params:)+ AccessControlList.where(target: params.target)+ end++ def destroy_acls(previous_permissions:, params:)+ @context[:previous_permissions] = previous_permissions.target_acl(+ params.target,+ ).permission_lookup+ previous_permissions.destroy_all+ end++ def fetch_flattened_acl_with_mandatory(params:)+ AccessControlList.inject_mandatory_acl(params.flattened_acl, params.target)+ end++ def has_at_least_one_acl(flattened_acl_with_mandatory:)+ flattened_acl_with_mandatory.any?+ end++ def insert_acls(params:, flattened_acl_with_mandatory:)+ bulk_insert_list =+ AccessControlList.expand_list(flattened_acl_with_mandatory, params.target, params.owner)+ @context[:new_permissions] = Acl::Target.new(flattened_acl_with_mandatory).permission_lookup+ AccessControlList.insert_all!(bulk_insert_list)+ end++ def log_permission_changes(guardian:, previous_permissions:, new_permissions:, params:)+ StaffActionLogger.new(guardian.user).log_access_control_list_permission_change(+ params.target,+ previous_permissions,+ new_permissions,+ )+ end++ def reload_target(params:)+ params.target.reload+ end+enddiff --git a/app/services/staff_action_logger.rb b/app/services/staff_action_logger.rbindex 756fc8e4ea9..92e5c778879 100644--- a/app/services/staff_action_logger.rb+++ b/app/services/staff_action_logger.rb@@ -350,6 +350,34 @@ class StaffActionLogger)end+ def log_access_control_list_permission_change(+ target,+ previous_permissions,+ new_permissions,+ opts = {}+ )+ previous_permissions_details =+ previous_permissions.map { |permission_name, permission| <<~STR }.join("\n")+ #{permission_name}:+ -> #{permission.map { |k, v| "#{k}: #{v.join(", ")}" }.join(",")}+ STR++ new_permissions_details =+ new_permissions.map { |permission_name, permission| <<~STR }.join("\n")+ #{permission_name}:+ -> #{permission.map { |k, v| "#{k}: #{v.join(", ")}" }.join(",")}+ STR++ UserHistory.create!(+ params(opts).merge(+ action: UserHistory.actions[:change_access_control_list_permissions],+ subject: "#{target.class.polymorphic_name} (#{target.id})",+ previous_value: previous_permissions_details,+ new_value: new_permissions_details,+ ),+ )+ end+def theme_json(theme)ThemeSerializer.new(theme, root: false, include_theme_field_values: true).to_jsonenddiff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex daaef90f5be..46d6f475245 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -48,6 +48,16 @@ en:no_visible_children_hint: "This container block is not rendered because none of its children are visible."condition_failed_hint: "This block is not rendered because its conditions failed."head_hidden_tail_hint: "This block is not rendered because another block was rendered first in the `head` container."+ access_control:+ manage:+ access_permission_editor: "Editor"+ access_permission_editor_description: "Can create and edit content for this entity"+ access_permission_viewer: "Viewer"+ access_permission_viewer_description: "Can view content for this entity"+ access_permission_remove: "Remove"+ access_permission_remove_description: "Remove permission for this group"+ add_group: "Add group"+ mandatory_acl_tooltip: "This permission is mandatory for this entity and cannot be removed"carousel:go_to_slide: "Go to slide %{index}"previous: "Previous slide"@@ -8790,6 +8800,7 @@ en:discourse_id_regenerate_credentials: "regenerate Discourse ID credentials"configure_category_type: "configure category type"unconfigure_category_type: "unconfigure category type"+ change_access_control_list_permissions: "change access control list permissions"screened_emails:title: "Screened emails"description: "When someone tries to create a new account, the following email addresses will be checked and the registration will be blocked, or some other action performed."diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex df49fada86f..8a18387a378 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -684,6 +684,18 @@ en:trust_level_2: "trust_level_2"trust_level_3: "trust_level_3"trust_level_4: "trust_level_4"+ default_full_names:+ everyone: "Everyone"+ admins: "Admins"+ moderators: "Moderators"+ staff: "Staff"+ anonymous_users: "Anonymous users"+ logged_in_users: "Logged in users"+ trust_level_0: "Trust level 0"+ trust_level_1: "Trust level 1"+ trust_level_2: "Trust level 2"+ trust_level_3: "Trust level 3"+ trust_level_4: "Trust level 4"default_descriptions:everyone: "Automatic group including all members"staff: "Automatic group including admins and moderators"diff --git a/db/migrate/20260610064425_introduce_permission_acl_tables.rb b/db/migrate/20260610064425_introduce_permission_acl_tables.rbnew file mode 100644index 00000000000..a5fa1633dde--- /dev/null+++ b/db/migrate/20260610064425_introduce_permission_acl_tables.rb@@ -0,0 +1,35 @@+# frozen_string_literal: true+class IntroducePermissionAclTables < ActiveRecord::Migration[8.0]+ def up+ create_table :access_control_lists do |t|+ t.string :target_type, null: false, limit: 255+ t.bigint :target_id, null: false++ t.string :owner, null: false, limit: 100+ t.string :permission, null: false, limit: 100++ t.bigint :allowed_user_ids, array: true, null: false, default: []+ t.bigint :allowed_group_ids, array: true, null: false, default: []++ t.timestamps+ end++ add_index :access_control_lists, %i[target_type target_id permission], unique: true+ execute "CREATE INDEX idx_access_control_lists_allowed_user_ids ON access_control_lists USING GIN(allowed_user_ids)"+ execute "CREATE INDEX idx_access_control_lists_allowed_group_ids ON access_control_lists USING GIN(allowed_group_ids)"+ end++ def down+ drop_table :access_control_lists++ if index_exists?(:access_control_lists, :allowed_user_ids, using: :gin)+ execute "DROP INDEX idx_access_control_lists_allowed_user_ids"+ end+ if index_exists?(:access_control_lists, :allowed_group_ids, using: :gin)+ execute "DROP INDEX idx_access_control_lists_allowed_group_ids"+ end+ if index_exists?(:access_control_lists, %i[target_type target_id permission], unique: true)+ remove_index :access_control_lists, column: %i[target_type target_id permission]+ end+ end+enddiff --git a/db/structure.sql b/db/structure.sqlindex 0bd5a0ed42b..486585bd378 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -162,6 +162,42 @@ SET default_tablespace = '';SET default_table_access_method = heap;+--+-- Name: access_control_lists; Type: TABLE; Schema: public; Owner: -+--++CREATE TABLE public.access_control_lists (+ id bigint NOT NULL,+ target_type character varying(255) NOT NULL,+ target_id bigint NOT NULL,+ owner character varying(100) NOT NULL,+ permission character varying(100) NOT NULL,+ allowed_user_ids bigint[] DEFAULT '{}'::bigint[] NOT NULL,+ allowed_group_ids bigint[] DEFAULT '{}'::bigint[] NOT NULL,+ created_at timestamp(6) without time zone NOT NULL,+ updated_at timestamp(6) without time zone NOT NULL+);+++--+-- Name: access_control_lists_id_seq; Type: SEQUENCE; Schema: public; Owner: -+--++CREATE SEQUENCE public.access_control_lists_id_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+++--+-- Name: access_control_lists_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -+--++ALTER SEQUENCE public.access_control_lists_id_seq OWNED BY public.access_control_lists.id;++---- Name: ad_plugin_house_ads; Type: TABLE; Schema: public; Owner: ---@@ -12003,6 +12039,13 @@ CREATE SEQUENCE public.web_hooks_id_seqALTER SEQUENCE public.web_hooks_id_seq OWNED BY public.web_hooks.id;+--+-- Name: access_control_lists id; Type: DEFAULT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.access_control_lists ALTER COLUMN id SET DEFAULT nextval('public.access_control_lists_id_seq'::regclass);++---- Name: ad_plugin_house_ads id; Type: DEFAULT; Schema: public; Owner: ---@@ -14159,6 +14202,14 @@ ALTER TABLE ONLY public.web_hook_events_daily_aggregates ALTER COLUMN id SET DEFALTER TABLE ONLY public.web_hooks ALTER COLUMN id SET DEFAULT nextval('public.web_hooks_id_seq'::regclass);+--+-- Name: access_control_lists access_control_lists_pkey; Type: CONSTRAINT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.access_control_lists+ ADD CONSTRAINT access_control_lists_pkey PRIMARY KEY (id);++---- Name: ad_plugin_house_ads ad_plugin_house_ads_pkey; Type: CONSTRAINT; Schema: public; Owner: ---@@ -16773,6 +16824,20 @@ CREATE INDEX directory_column_index ON public.directory_columns USING btree (enaCREATE UNIQUE INDEX discourse_post_event_invitees_post_id_user_id_idx ON public.discourse_post_event_invitees USING btree (post_id, user_id);+--+-- Name: idx_access_control_lists_allowed_group_ids; Type: INDEX; Schema: public; Owner: -+--++CREATE INDEX idx_access_control_lists_allowed_group_ids ON public.access_control_lists USING gin (allowed_group_ids);+++--+-- Name: idx_access_control_lists_allowed_user_ids; Type: INDEX; Schema: public; Owner: -+--++CREATE INDEX idx_access_control_lists_allowed_user_ids ON public.access_control_lists USING gin (allowed_user_ids);++---- Name: idx_ai_bot_conversation_stars_topic_id; Type: INDEX; Schema: public; Owner: ---@@ -17263,6 +17328,13 @@ CREATE UNIQUE INDEX idx_on_llm_model_id_feature_name_2b0b794b27 ON public.llm_feCREATE UNIQUE INDEX idx_on_target_id_target_type_summary_type_3355609fbb ON public.ai_summaries USING btree (target_id, target_type, summary_type);+--+-- Name: idx_on_target_type_target_id_permission_f472902150; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX idx_on_target_type_target_id_permission_f472902150 ON public.access_control_lists USING btree (target_type, target_id, permission);++---- Name: idx_post_voting_comment_custom_fields; Type: INDEX; Schema: public; Owner: ---@@ -22213,6 +22285,7 @@ INSERT INTO "schema_migrations" (version) VALUES('20260612092612'),('20260610205840'),('20260610075829'),+('20260610064425'),('20260609050938'),('20260608104742'),('20260607161322'),diff --git a/frontend/discourse/admin/models/staff-action-log.js b/frontend/discourse/admin/models/staff-action-log.jsindex da03ee62028..4a323af4d1f 100644--- a/frontend/discourse/admin/models/staff-action-log.js+++ b/frontend/discourse/admin/models/staff-action-log.js@@ -6,8 +6,10 @@ import RestModel from "discourse/models/rest";import { i18n } from "discourse-i18n";function format(label, value, escape = true) {+ const labelBr = value && value.toString().includes("\n") ? "<br/>" : " ";+ value = value ? value.toString() : "";return value- ? `<b>${i18n(label)}</b>: ${escape ? escapeExpression(value) : value}`+ ? `<b>${i18n(label)}:</b>${labelBr} ${escape ? escapeExpression(value.replaceAll("\n", "<br/>")) : value.replaceAll("\n", "<br/>")}`: "";}@@ -78,9 +80,15 @@ export default class StaffActionLog extends RestModel {];if (!this.useCustomModalForDetails) {- lines.push(format("admin.logs.staff_actions.new_value", this.new_value));lines.push(- format("admin.logs.staff_actions.previous_value", this.previous_value)+ format("admin.logs.staff_actions.new_value", this.new_value, false)+ );+ lines.push(+ format(+ "admin.logs.staff_actions.previous_value",+ this.previous_value,+ false+ ));}diff --git a/frontend/discourse/app/ui-kit/d-access-control.gjs b/frontend/discourse/app/ui-kit/d-access-control.gjsnew file mode 100644index 00000000000..1536603d63d--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-access-control.gjs@@ -0,0 +1,292 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { fn, hash } from "@ember/helper";+import { action } from "@ember/object";+import { service } from "@ember/service";+import DTooltip from "discourse/float-kit/components/d-tooltip";+import { AUTO_GROUPS } from "discourse/lib/constants";+import ComboBox from "discourse/select-kit/components/combo-box";+import DropdownSelectBox from "discourse/select-kit/components/dropdown-select-box";+import DButton from "discourse/ui-kit/d-button";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import dIcon from "discourse/ui-kit/helpers/d-icon";+import { i18n } from "discourse-i18n";++const EDIT_PERMISSION = "edit";+const READ_ONLY_PERMISSION = "view";+const READ_ONLY_DEFAULT_AUTO_GROUPS = [+ AUTO_GROUPS.anonymous_users.id,+ AUTO_GROUPS.everyone.id,+ AUTO_GROUPS.trust_level_0.id,+];+const REMOVE_ACTION = {+ id: "remove",+ name: i18n("access_control.manage.access_permission_remove"),+ description: i18n(+ "access_control.manage.access_permission_remove_description"+ ),+};++function defaultPermissions() {+ return [+ {+ id: READ_ONLY_PERMISSION,+ level: 1,+ name: i18n("access_control.manage.access_permission_viewer"),+ description: i18n(+ "access_control.manage.access_permission_viewer_description"+ ),+ },+ {+ id: EDIT_PERMISSION,+ level: 2,+ name: i18n("access_control.manage.access_permission_editor"),+ description: i18n(+ "access_control.manage.access_permission_editor_description"+ ),+ },+ ];+}++export default class DAccessControl extends Component {+ @service site;++ @tracked addingGroup = false;++ constructor() {+ super(...arguments);+ this.permissionOptions = this.buildPermissionOptions();+ }++ /**+ * If a transformPermissionOptions function is provided, it is passed all+ * default permissions and can change the name, description, or level of+ * these options, OR add new options, returning the new array.+ *+ * The level property is used to sort the options, and is an indicator+ * of the level of access the permission provides, since e.g. Edit is a+ * higher level of access than View, and to Edit by definition you need+ * to be able to View.+ *+ * Otherwise, the default permissions are used.+ */+ buildPermissionOptions() {+ const permissions =+ this.args.transformPermissionOptions?.(defaultPermissions()) ||+ defaultPermissions();++ return [+ ...permissions.sort((a, b) => a.level - b.level),+ {+ ...REMOVE_ACTION,+ classNames:+ "d-access-control__permission-divider d-access-control__permission-remove",+ },+ ];+ }++ get availableGroups() {+ const taken = new Set(this.selectedGroupIds);+ return (this.args.groups || [])+ .filter((group) => !taken.has(group.id))+ .sort((a, b) => {+ if (a.automatic !== b.automatic) {+ return a.automatic ? -1 : 1;+ }++ return (a.full_name || a.name).localeCompare(b.full_name || b.name);+ });+ }++ get selectedGroupIds() {+ return this.acl+ .filter((entry) => entry.type === "group")+ .map((entry) => entry.id);+ }++ get mandatoryAcl() {+ if (!this.args.aclTarget) {+ return [];+ }++ return this.site.access_control?.mandatory_acl?.[this.args.aclTarget] || [];+ }++ get acl() {+ if (!this.mandatoryAcl.length) {+ return this.args.acl || [];+ }++ const mandatoryEntryKeys = new Set(+ this.mandatoryAcl.map((entry) => `${entry.type}-${entry.id}`)+ );+ const acl = (this.args.acl || []).filter(+ (entry) => !mandatoryEntryKeys.has(`${entry.type}-${entry.id}`)+ );++ this.mandatoryAcl.forEach((entry) => {+ if (entry.type !== "group") {+ return;+ }++ const group = (this.args.groups || []).find((g) => g.id === entry.id);+ if (group) {+ acl.push({+ type: "group",+ id: entry.id,+ name: group.name,+ full_name: group.full_name,+ permission: entry.permission,+ metadata: {+ auto_group: group.automatic,+ },+ mandatory: true,+ });+ }+ });++ return acl;+ }++ // TODO (martin) How are we going to deal with users that have the Owner permission+ // here if we don't want to expose that in the UI?+ get rows() {+ return this.acl+ .map((entry) => ({+ key: `${entry.type}-${entry.id}-${entry.permission}`,+ id: entry.id,+ permission: entry.permission,+ name: entry.full_name,+ type: entry.type,+ mandatory: entry.mandatory,+ }))+ .sort((a, b) => {+ if (a.mandatory !== b.mandatory) {+ return a.mandatory ? -1 : 1;+ }++ return (a.name || "").localeCompare(b.name || "");+ });+ }++ @action+ startAdding() {+ this.addingGroup = true;+ }++ @action+ onGroupChosen(groupId) {+ if (groupId == null) {+ this.addingGroup = false;+ return;+ }++ const selectedGroup = (this.args.groups || []).find(+ (group) => group.id === groupId+ );++ const newPermission = {+ id: selectedGroup.id,+ name: selectedGroup.name,+ full_name: selectedGroup.full_name,+ type: "group",+ permission: READ_ONLY_DEFAULT_AUTO_GROUPS.includes(selectedGroup.id)+ ? READ_ONLY_PERMISSION+ : EDIT_PERMISSION,+ metadata: {+ auto_group: selectedGroup.automatic,+ },+ };++ const next = [...this.acl, newPermission];++ this.args.onChange(next);+ this.addingGroup = false;+ }++ @action+ onPermissionChange(groupId, permission) {+ if (permission === REMOVE_ACTION.id) {+ this.args.onChange(+ this.acl.filter(+ (entry) => !(entry.type === "group" && entry.id === groupId)+ )+ );+ return;+ }++ const next = this.acl.map((entry) =>+ entry.type === "group" && entry.id === groupId+ ? { ...entry, permission }+ : entry+ );+ this.args.onChange(next);+ }+ // TODO (martin) How are we going to deal with users that have the Owner permission+ // here if we don't want to expose that in the UI?++ <template>+ <div class="d-access-control">+ {{#if this.rows.length}}+ <div class="d-access-control__rows">+ {{#each this.rows key="key" as |row|}}+ <div+ class={{dConcatClass+ "d-access-control__row"+ (if row.mandatory "--mandatory")+ }}+ data-row-type={{row.type}}+ data-row-id={{row.id}}+ >+ <span class="d-access-control__group-name">{{#if row.mandatory}}+ <DTooltip+ @content={{i18n+ "access_control.manage.mandatory_acl_tooltip"+ }}+ >+ <:trigger>+ {{dIcon "lock"}}+ </:trigger>+ </DTooltip>+ {{/if}}+ {{row.name}}</span>+ <DropdownSelectBox+ class="d-access-control__permission"+ @value={{row.permission}}+ @content={{this.permissionOptions}}+ @onChange={{fn this.onPermissionChange row.id}}+ @options={{hash+ showCaret=true+ showFullTitle=true+ disabled=row.mandatory+ }}+ />+ </div>+ {{/each}}+ </div>+ {{/if}}++ {{#if this.addingGroup}}+ <ComboBox+ class="d-access-control__chooser"+ @value={{null}}+ @content={{this.availableGroups}}+ @onChange={{this.onGroupChosen}}+ @labelProperty="full_name"+ @options={{hash+ none="access_control.manage.add_group"+ expandedOnInsert=true+ filterable=true+ }}+ />+ {{else}}+ <DButton+ class="d-access-control__add btn-default"+ @icon="plus"+ @label="access_control.manage.add_group"+ @action={{this.startAdding}}+ />+ {{/if}}+ </div>+ </template>+}diff --git a/frontend/discourse/tests/integration/components/d-access-control-test.gjs b/frontend/discourse/tests/integration/components/d-access-control-test.gjsnew file mode 100644index 00000000000..aed2d36ed78--- /dev/null+++ b/frontend/discourse/tests/integration/components/d-access-control-test.gjs@@ -0,0 +1,465 @@+import { tracked } from "@glimmer/tracking";+import { click, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { AUTO_GROUPS } from "discourse/lib/constants";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import selectKit from "discourse/tests/helpers/select-kit-helper";+import DAccessControl from "discourse/ui-kit/d-access-control";+import { i18n } from "discourse-i18n";++// A non-automatic group, plus the "logged_in_users" auto group (id: 5) which is one of+// the groups that defaults to view-only access when added.+const GROUPS = [+ { id: 42, name: "team_a", full_name: "Team A", automatic: false },+ {+ id: AUTO_GROUPS.logged_in_users.id,+ name: "logged_in_users",+ full_name: "Logged In Users",+ automatic: true,+ },+ {+ id: AUTO_GROUPS.trust_level_0.id,+ name: "trust_level_0",+ full_name: "Trust level 0",+ automatic: true,+ },+];++// Builds a controlled-component wrapper: `onChange` writes the next acl back into+// tracked state so the component re-renders the way it would in a real parent.+function controlledState(initialAcl = []) {+ return new (class {+ @tracked acl = initialAcl;+ onChangeCalls = [];++ onChange = (next) => {+ this.onChangeCalls.push(next);+ this.acl = next;+ };+ })();+}++module("Integration | Component | DAccessControl", function (hooks) {+ setupRenderingTest(hooks);++ test("adds a group with the default permission via the availableGroups ComboBox", async function (assert) {+ const state = controlledState();++ await render(+ <template>+ <DAccessControl+ @groups={{GROUPS}}+ @acl={{state.acl}}+ @onChange={{state.onChange}}+ />+ </template>+ );++ assert+ .dom(".d-access-control__row")+ .doesNotExist("starts with no acl rows");++ await click(".d-access-control__add");++ const chooser = selectKit(".d-access-control__chooser");+ await chooser.expand();+ await chooser.expand();++ assert+ .dom(".d-access-control__chooser .select-kit-row[data-value='42']")+ .exists("availableGroups are listed in the chooser");++ await chooser.selectRowByValue(42);++ assert.strictEqual(+ state.onChangeCalls.length,+ 1,+ "onChange is called when a group is chosen"+ );++ const [added] = state.onChangeCalls[0];+ assert.strictEqual(added.id, 42, "adds the chosen group");+ assert.strictEqual(added.type, "group", "marks the entry as a group");+ assert.strictEqual(+ added.permission,+ "edit",+ "applies the default edit permission for a regular group"+ );++ assert+ .dom(".d-access-control__row .d-access-control__group-name")+ .hasText("Team A", "renders the newly added group row");+ });++ test("a read-only default group is added with the view permission", async function (assert) {+ const state = controlledState();++ await render(+ <template>+ <DAccessControl+ @groups={{GROUPS}}+ @acl={{state.acl}}+ @onChange={{state.onChange}}+ />+ </template>+ );++ await click(".d-access-control__add");++ const chooser = selectKit(".d-access-control__chooser");+ await chooser.expand();+ await chooser.expand();+ await chooser.selectRowByValue(AUTO_GROUPS.trust_level_0.id);++ const [added] = state.onChangeCalls[0];+ assert.strictEqual(+ added.permission,+ "view",+ "applies the default view permission for a read-only default group"+ );+ });++ test("transformPermissionOptions can change descriptions and add options", async function (assert) {+ const state = controlledState([+ {+ type: "group",+ id: 999,+ permission: "view",+ name: "Some Group",+ full_name: "Some Group",+ },+ ]);++ const transformPermissionOptions = (permissions) => [+ ...permissions.map((permission) =>+ permission.id === "view"+ ? { ...permission, description: "Custom view description" }+ : permission+ ),+ { id: "juggler", level: 3, name: "Juggler", description: "Full control" },+ ];++ await render(+ <template>+ <DAccessControl+ @groups={{GROUPS}}+ @acl={{state.acl}}+ @onChange={{state.onChange}}+ @transformPermissionOptions={{transformPermissionOptions}}+ />+ </template>+ );++ const permission = selectKit(".d-access-control__permission");+ await permission.expand();++ assert.strictEqual(+ permission.rowByValue("view").description(),+ "Custom view description",+ "uses the transformed description for an existing option"+ );++ assert.true(+ permission.rowByValue("juggler").exists(),+ "renders the added permission option"+ );+ assert.strictEqual(+ permission.rowByValue("juggler").label(),+ "Juggler",+ "the added option keeps its name"+ );+ });++ test("loads multiple existing acl groups with their permissions", async function (assert) {+ const state = controlledState([+ {+ type: "group",+ id: 999,+ permission: "view",+ name: "Some Group",+ full_name: "Some Group",+ },+ {+ type: "group",+ id: 1001,+ permission: "edit",+ name: "Another Group",+ full_name: "Another Group",+ },+ ]);++ await render(+ <template>+ <DAccessControl+ @groups={{GROUPS}}+ @acl={{state.acl}}+ @onChange={{state.onChange}}+ />+ </template>+ );++ assert+ .dom(".d-access-control__row")+ .exists({ count: 2 }, "renders a row per acl entry");++ const rows = [...document.querySelectorAll(".d-access-control__row")];++ assert+ .dom(".d-access-control__group-name", rows[0])+ .hasText("Another Group", "renders the first group name");+ assert.strictEqual(+ rows[0].querySelector(".select-kit-header").dataset.value,+ "edit",+ "loads the first group's permission"+ );++ assert+ .dom(".d-access-control__group-name", rows[1])+ .hasText("Some Group", "renders the second group name");+ assert.strictEqual(+ rows[1].querySelector(".select-kit-header").dataset.value,+ "view",+ "loads the second group's permission"+ );+ });++ test("the Remove option removes the acl row", async function (assert) {+ const state = controlledState([+ {+ type: "group",+ id: 999,+ permission: "view",+ name: "Some Group",+ full_name: "Some Group",+ },+ {+ type: "group",+ id: 1001,+ permission: "edit",+ name: "Another Group",+ full_name: "Another Group",+ },+ ]);++ await render(+ <template>+ <DAccessControl+ @groups={{GROUPS}}+ @acl={{state.acl}}+ @onChange={{state.onChange}}+ />+ </template>+ );++ assert.dom(".d-access-control__row").exists({ count: 2 });++ // selectKit() targets the first matching dropdown, i.e. the "Some Group" row.+ const permission = selectKit(".d-access-control__permission");+ await permission.expand();+ await permission.selectRowByValue("remove");++ assert+ .dom(".d-access-control__row")+ .exists({ count: 1 }, "removes the row whose permission was removed");+ assert+ .dom(".d-access-control__group-name")+ .hasText("Some Group", "keeps the remaining row");+ });++ test("calls the onChange arg when a permission changes", async function (assert) {+ const state = controlledState([+ {+ type: "group",+ id: 999,+ permission: "view",+ name: "Some Group",+ full_name: "Some Group",+ },+ ]);++ await render(+ <template>+ <DAccessControl+ @groups={{GROUPS}}+ @acl={{state.acl}}+ @onChange={{state.onChange}}+ />+ </template>+ );++ const permission = selectKit(".d-access-control__permission");+ await permission.expand();+ await permission.selectRowByValue("edit");++ assert.strictEqual(+ state.onChangeCalls.length,+ 1,+ "onChange is called once"+ );+ assert.strictEqual(+ state.onChangeCalls[0][0].permission,+ "edit",+ "onChange receives the acl with the updated permission"+ );+ });++ test("uses the default permission option labels", async function (assert) {+ const state = controlledState([+ {+ type: "group",+ id: 999,+ permission: "view",+ name: "Some Group",+ full_name: "Some Group",+ },+ ]);++ await render(+ <template>+ <DAccessControl+ @groups={{GROUPS}}+ @acl={{state.acl}}+ @onChange={{state.onChange}}+ />+ </template>+ );++ const permission = selectKit(".d-access-control__permission");+ await permission.expand();++ assert.strictEqual(+ permission.rowByValue("view").label(),+ i18n("access_control.manage.access_permission_viewer"),+ "renders the default viewer option"+ );+ assert.strictEqual(+ permission.rowByValue("edit").label(),+ i18n("access_control.manage.access_permission_editor"),+ "renders the default editor option"+ );+ });++ test("puts mandatory permissions at the top of the rows and disables removing the permission", async function (assert) {+ const state = controlledState([+ {+ type: "group",+ id: 999,+ permission: "view",+ name: "Some Group",+ full_name: "Some Group",+ mandatory: true,+ },+ {+ type: "group",+ id: 1001,+ permission: "edit",+ name: "Another Group",+ full_name: "Another Group",+ },+ ]);++ await render(+ <template>+ <DAccessControl+ @groups={{GROUPS}}+ @acl={{state.acl}}+ @onChange={{state.onChange}}+ />+ </template>+ );++ const rows = [...document.querySelectorAll(".d-access-control__row")];+ assert.dom(rows[0]).hasClass("--mandatory", "the mandatory row is first");+ assert+ .dom(+ rows[0].querySelector(+ ".d-access-control__permission.dropdown-select-box"+ )+ )+ .hasClass(+ "is-disabled",+ "the mandatory row's permission select is disabled"+ );+ });++ test("injects mandatory acl rows for the target", async function (assert) {+ this.site.access_control = {+ mandatory_acl: {+ TestTarget: [{ type: "group", id: 42, permission: "edit" }],+ },+ };+ const state = controlledState();++ await render(+ <template>+ <DAccessControl+ @groups={{GROUPS}}+ @acl={{state.acl}}+ @aclTarget="TestTarget"+ @onChange={{state.onChange}}+ />+ </template>+ );++ assert+ .dom(".d-access-control__row")+ .exists({ count: 1 }, "renders the mandatory row");+ assert+ .dom(".d-access-control__row")+ .hasClass("--mandatory", "marks the row as mandatory");+ assert+ .dom(".d-access-control__group-name")+ .hasText("Team A", "renders the mandatory group's name");++ assert.strictEqual(+ document.querySelector(".d-access-control__permission .select-kit-header")+ .dataset.value,+ "edit",+ "uses the mandatory permission"+ );+ assert.strictEqual(+ state.onChangeCalls.length,+ 0,+ "does not notify the parent during render"+ );+ });++ test("mandatory acl replaces an existing row for the same group", async function (assert) {+ this.site.access_control = {+ mandatory_acl: {+ TestTarget: [{ type: "group", id: 42, permission: "edit" }],+ },+ };+ const state = controlledState([+ {+ type: "group",+ id: 42,+ permission: "view",+ name: "Team A",+ full_name: "Team A",+ },+ ]);++ await render(+ <template>+ <DAccessControl+ @groups={{GROUPS}}+ @acl={{state.acl}}+ @aclTarget="TestTarget"+ @onChange={{state.onChange}}+ />+ </template>+ );++ assert+ .dom(".d-access-control__row")+ .exists({ count: 1 }, "does not render a duplicate group row");++ assert.strictEqual(+ document.querySelector(".d-access-control__permission .select-kit-header")+ .dataset.value,+ "edit",+ "uses the mandatory permission"+ );+ });+});diff --git a/lib/acl/mixed_target_error.rb b/lib/acl/mixed_target_error.rbnew file mode 100644index 00000000000..9c9e14696b0--- /dev/null+++ b/lib/acl/mixed_target_error.rb@@ -0,0 +1,6 @@+# frozen_string_literal: true++module Acl+ class MixedTargetError < StandardError+ end+enddiff --git a/lib/acl/target.rb b/lib/acl/target.rbnew file mode 100644index 00000000000..2f566424c82--- /dev/null+++ b/lib/acl/target.rb@@ -0,0 +1,42 @@+# frozen_string_literal: true+module Acl+ class Target+ attr_reader :group_lookup, :permission_lookup++ def initialize(flattened_acl_list)+ @group_lookup = {}+ @permission_lookup = {}++ flattened_acl_list.each do |acl|+ @permission_lookup[acl[:permission]] ||= { group_ids: [] }++ if acl[:type].to_sym == :group+ @group_lookup[acl[:id]] ||= []+ @group_lookup[acl[:id]] << acl[:permission]++ # TODO (martin) Handle users here too in a followup PR when we allow adding them in the UI.+ @permission_lookup[acl[:permission]][:group_ids] << acl[:id]+ end+ end+ end++ def group_has_permission?(group_or_id, permission)+ @group_lookup[group_or_id.is_a?(Numeric) ? group_or_id : group_or_id&.id]&.include?(+ permission,+ )+ end++ def group_has_any_permission?(group_or_id, permissions)+ group_permissions = @group_lookup[group_or_id.is_a?(Numeric) ? group_or_id : group_or_id&.id]+ (group_permissions || []).any? { |permission| permissions.include?(permission) }+ end++ def permission_group_ids(permission)+ ((@permission_lookup[permission] || {}).dig(:group_ids) || []).dup+ end++ def group_ids_with_any_permission(permissions)+ permissions.flat_map { |permission| permission_group_ids(permission) || [] }.uniq.dup+ end+ end+enddiff --git a/lib/acl/user.rb b/lib/acl/user.rbnew file mode 100644index 00000000000..267192291ec--- /dev/null+++ b/lib/acl/user.rb@@ -0,0 +1,51 @@+# frozen_string_literal: true++module Acl+ class User+ attr_reader :target_lookup, :permission_lookup++ def initialize(flattened_acl_list)+ @target_lookup = {}+ @permission_lookup = {}++ flattened_acl_list.each do |acl|+ @target_lookup[target_key(acl)] ||= []+ @target_lookup[target_key(acl)] << acl[:permission]++ @permission_lookup[acl[:permission]] ||= {}+ @permission_lookup[acl[:permission]][acl[:target_type]] ||= []+ @permission_lookup[acl[:permission]][acl[:target_type]] << acl[:target_id]+ end+ end++ def has_target_permission?(target, permission)+ @target_lookup[target_key(target)]&.include?(permission)+ end++ def has_any_target_permission?(target, permissions)+ target_permissions = @target_lookup[target_key(target)]+ (target_permissions || []).any? { |permission| permissions.include?(permission) }+ end++ def target_ids_with_permission(target_class, permission)+ ((@permission_lookup[permission] || {}).dig(target_class.polymorphic_name) || []).dup+ end++ def target_ids_with_any_permissions(target_class, permissions)+ permissions+ .flat_map { |permission| target_ids_with_permission(target_class, permission) }+ .uniq+ .dup+ end++ private++ def target_key(target)+ if target.is_a?(Hash)+ "#{target[:target_type]}_#{target[:target_id]}"+ else+ "#{target.class.polymorphic_name}_#{target.id}"+ end+ end+ end+enddiff --git a/lib/discourse_plugin_registry.rb b/lib/discourse_plugin_registry.rbindex 112faebc909..84e1f5c3c70 100644--- a/lib/discourse_plugin_registry.rb+++ b/lib/discourse_plugin_registry.rb@@ -141,6 +141,8 @@ class DiscoursePluginRegistrydefine_filtered_register :custom_filter_mappings+ define_filtered_register :acl_target_classes+define_filtered_register :reviewable_types do |singleton|singleton.define_singleton_method("reviewable_types_lookup") dopublic_send(:_raw_reviewable_types)diff --git a/lib/guardian.rb b/lib/guardian.rbindex 0d280c0a13d..120767860a3 100644--- a/lib/guardian.rb+++ b/lib/guardian.rb@@ -104,6 +104,10 @@ class Guardiandef in_any_groups?(group_ids)group_ids.include?(Group::AUTO_GROUPS[:anonymous_users])end++ def permission_acl+ @permission_acl ||= AccessControlList.matching_user(nil).user_acl+ endendattr_reader :request@@ -173,6 +177,26 @@ class Guardian@user.anonymous?end+ def has_acl_permission?(target, permission)+ @user.permission_acl.has_target_permission?(target, permission)+ end++ def has_any_acl_permission?(target, permissions)+ @user.permission_acl.has_any_target_permission?(target, permissions)+ end++ def target_ids_with_acl_permission(target_klass, permission)+ @user.permission_acl.target_ids_with_permission(target_klass, permission)+ end++ def target_ids_with_any_acl_permissions(target_klass, permissions)+ @user.permission_acl.target_ids_with_any_permissions(target_klass, permissions)+ end++ def in_any_groups?(group_ids)+ @user.in_any_groups?(group_ids)+ end+# Can the user see the object?def can_see?(obj)if objdiff --git a/plugins/discourse-ai/assets/javascripts/discourse/lib/show-ai-helper.js b/plugins/discourse-ai/assets/javascripts/discourse/lib/show-ai-helper.jsindex 137fe8a1ac9..eac9a5b25d0 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/lib/show-ai-helper.js+++ b/plugins/discourse-ai/assets/javascripts/discourse/lib/show-ai-helper.js@@ -4,6 +4,10 @@ export function showComposerAiHelper(currentUser,featureType) {+ if (!currentUser) {+ return false;+ }+const enableHelper = _helperEnabled(siteSettings);const enableAssistant = currentUser.can_use_assistant;const canShowInPM = siteSettings.ai_helper_allowed_in_pm;diff --git a/spec/fabricators/access_control_list_fabricator.rb b/spec/fabricators/access_control_list_fabricator.rbnew file mode 100644index 00000000000..189f9d05d34--- /dev/null+++ b/spec/fabricators/access_control_list_fabricator.rb@@ -0,0 +1,25 @@+# frozen_string_literal: true++Fabricator(:access_control_list) do+ target { Fabricate(:category) }+ permission { "view" }+ owner { "core" }+ allowed_user_ids { [] }+ allowed_group_ids { [] }+end++Fabricator(:access_control_list_with_users, from: :access_control_list) do+ transient :users+ allowed_user_ids { |attrs| attrs[:users].map(&:id) }+end++Fabricator(:access_control_list_with_groups, from: :access_control_list) do+ transient :groups+ allowed_group_ids { |attrs| attrs[:groups].map(&:id) }+end++Fabricator(:access_control_list_with_users_and_groups, from: :access_control_list) do+ transient :users, :groups+ allowed_user_ids { |attrs| attrs[:users].map(&:id) }+ allowed_group_ids { |attrs| attrs[:groups].map(&:id) }+enddiff --git a/spec/jobs/regular/cleanup_acls_for_deleted_spec.rb b/spec/jobs/regular/cleanup_acls_for_deleted_spec.rbnew file mode 100644index 00000000000..c2c7156c257--- /dev/null+++ b/spec/jobs/regular/cleanup_acls_for_deleted_spec.rb@@ -0,0 +1,37 @@+# frozen_string_literal: true++RSpec.describe Jobs::CleanupAclsForDeleted do+ context "when a group is deleted" do+ fab!(:group)+ fab!(:other_group, :group)+ fab!(:third_group, :group)+ fab!(:user)++ fab!(:access_control_list_1) do+ Fabricate(:access_control_list_with_groups, groups: [group, other_group])+ end+ fab!(:access_control_list_2) do+ Fabricate(:access_control_list_with_groups, groups: [other_group, third_group])+ end+ fab!(:access_control_list_3) { Fabricate(:access_control_list_with_groups, groups: [group]) }+ fab!(:access_control_list_4) do+ Fabricate(:access_control_list_with_users_and_groups, groups: [group], users: [user])+ end++ it "removes the group from associated access_control_list records when the group is destroyed" do+ group.destroy!+ described_class.new.execute(group_id: group.id)+ expect(access_control_list_1.reload.allowed_group_ids).to eq([other_group.id])+ expect(access_control_list_2.reload.allowed_group_ids).to eq([other_group.id, third_group.id])+ end++ it "destroys the ACL when the ACL record has no more allowed ids of users or groups" do+ acl_3_id = access_control_list_3.id+ acl_4_id = access_control_list_4.id+ group.destroy!+ described_class.new.execute(group_id: group.id)+ expect(AccessControlList.find_by(id: acl_3_id)).to eq(nil)+ expect(AccessControlList.find_by(id: acl_4_id)).not_to eq(nil)+ end+ end+enddiff --git a/spec/lib/acl/target_spec.rb b/spec/lib/acl/target_spec.rbnew file mode 100644index 00000000000..71bb1c3be20--- /dev/null+++ b/spec/lib/acl/target_spec.rb@@ -0,0 +1,89 @@+# frozen_string_literal: true++RSpec.describe Acl::Target do+ subject(:target_acl) { described_class.new(flattened_acl_list) }++ fab!(:group)++ # A single target (e.g. a Category) with two groups and one user entry.+ # `group` has view + edit, group 22 has view only, and a user entry exists+ # for the "manage" permission (users are ignored for group lookups).+ let(:flattened_acl_list) do+ [+ { type: :group, id: group.id, permission: "view", target_type: "Category", target_id: 5 },+ { type: :group, id: group.id, permission: "edit", target_type: "Category", target_id: 5 },+ { type: "group", id: 22, permission: "view", target_type: "Category", target_id: 5 },+ { type: :user, id: 99, permission: "manage", target_type: "Category", target_id: 5 },+ ]+ end++ describe "#group_has_permission?" do+ it "returns true when the group id holds the permission" do+ expect(target_acl.group_has_permission?(group.id, "view")).to eq(true)+ end++ it "accepts a group record as well as an id" do+ expect(target_acl.group_has_permission?(group, "edit")).to eq(true)+ end++ it "returns false when the group does not hold the permission" do+ expect(target_acl.group_has_permission?(22, "edit")).to eq(false)+ end++ it "returns nil for a group not present in the list" do+ expect(target_acl.group_has_permission?(123_456, "view")).to be_nil+ end++ it "does not grant group permissions from non-group entries" do+ expect(target_acl.group_has_permission?(99, "manage")).to be_nil+ end+ end++ describe "#group_has_any_permission?" do+ it "returns true when the group holds any of the permissions" do+ expect(target_acl.group_has_any_permission?(group.id, %w[manage edit])).to eq(true)+ end++ it "returns false when the group holds none of the permissions" do+ expect(target_acl.group_has_any_permission?(22, %w[edit manage])).to eq(false)+ end++ it "returns false for a group not present in the list" do+ expect(target_acl.group_has_any_permission?(123_456, %w[view edit])).to eq(false)+ end+ end++ describe "#permission_group_ids" do+ it "returns all group ids holding the permission" do+ expect(target_acl.permission_group_ids("view")).to contain_exactly(group.id, 22)+ end++ it "returns only the matching groups for a more restrictive permission" do+ expect(target_acl.permission_group_ids("edit")).to contain_exactly(group.id)+ end++ it "returns an empty array when only non-group entries hold the permission" do+ expect(target_acl.permission_group_ids("manage")).to eq([])+ end++ it "returns an empty array for a permission that is not present" do+ expect(target_acl.permission_group_ids("own")).to eq([])+ end+ end++ describe "#group_ids_with_any_permission" do+ it "returns the unique group ids across all the permissions" do+ expect(target_acl.group_ids_with_any_permission(%w[view edit])).to contain_exactly(+ group.id,+ 22,+ )+ end++ it "ignores permissions that are not present" do+ expect(target_acl.group_ids_with_any_permission(%w[view own])).to contain_exactly(+ group.id,+ 22,+ )+ end+ end+enddiff --git a/spec/lib/acl/user_spec.rb b/spec/lib/acl/user_spec.rbnew file mode 100644index 00000000000..6735c340521--- /dev/null+++ b/spec/lib/acl/user_spec.rb@@ -0,0 +1,89 @@+# frozen_string_literal: true++RSpec.describe Acl::User do+ subject(:user_acl) { described_class.new(flattened_acl_list) }++ fab!(:category)+ fab!(:topic)++ fab!(:other_topic, :topic)++ # The flattened permissions a single user has across multiple targets: view ++ # edit on a Category, and view on a Topic.+ let(:flattened_acl_list) do+ [+ { type: :group, id: 10, permission: "view", target_type: "Category", target_id: category.id },+ { type: :group, id: 10, permission: "edit", target_type: "Category", target_id: category.id },+ { type: :group, id: 11, permission: "view", target_type: "Topic", target_id: topic.id },+ ]+ end++ describe "#has_target_permission?" do+ it "returns true when the target record holds the permission" do+ expect(user_acl.has_target_permission?(category, "view")).to eq(true)+ end++ it "accepts a target hash as well as a record" do+ expect(+ user_acl.has_target_permission?(+ { target_type: "Category", target_id: category.id },+ "edit",+ ),+ ).to eq(true)+ end++ it "returns false when the target does not hold the permission" do+ expect(user_acl.has_target_permission?(topic, "edit")).to eq(false)+ end++ it "returns nil for a target absent from the list" do+ expect(user_acl.has_target_permission?(other_topic, "view")).to be_nil+ end+ end++ describe "#has_any_target_permission?" do+ it "returns true when the target holds any of the permissions" do+ expect(user_acl.has_any_target_permission?(category, %w[manage edit])).to eq(true)+ end++ it "returns false when the target holds none of the permissions" do+ expect(user_acl.has_any_target_permission?(topic, %w[edit manage])).to eq(false)+ end++ it "returns false for a target absent from the list" do+ expect(user_acl.has_any_target_permission?(other_topic, %w[view edit])).to eq(false)+ end+ end++ describe "#target_ids_with_permission" do+ it "returns the target ids of the given class holding the permission" do+ expect(user_acl.target_ids_with_permission(Category, "view")).to contain_exactly(category.id)+ end++ it "scopes the ids to the requested target class" do+ expect(user_acl.target_ids_with_permission(Topic, "view")).to contain_exactly(topic.id)+ end++ it "returns an empty array when no target of that class holds the permission" do+ expect(user_acl.target_ids_with_permission(Category, "manage")).to eq([])+ end++ it "returns an empty array when the class has no entry for the permission" do+ expect(user_acl.target_ids_with_permission(Topic, "edit")).to eq([])+ end+ end++ describe "#target_ids_with_any_permissions" do+ it "returns the unique target ids across all the permissions" do+ expect(user_acl.target_ids_with_any_permissions(Category, %w[view edit])).to contain_exactly(+ category.id,+ )+ end++ it "scopes the combined ids to the requested target class" do+ expect(user_acl.target_ids_with_any_permissions(Topic, %w[view edit])).to contain_exactly(+ topic.id,+ )+ end+ end+enddiff --git a/spec/lib/guardian_spec.rb b/spec/lib/guardian_spec.rbindex 8154c363deb..f8a4f7e7d00 100644--- a/spec/lib/guardian_spec.rb+++ b/spec/lib/guardian_spec.rb@@ -55,6 +55,78 @@ RSpec.describe Guardian doendend+ describe "acl permissions" do+ fab!(:acl_user) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:acl_group) { Fabricate(:group).tap { |group| group.add(acl_user) } }+ fab!(:member_category, :category)+ fab!(:anon_category, :category)+ fab!(:member_acl) do+ Fabricate(+ :access_control_list_with_groups,+ target: member_category,+ permission: "view",+ groups: [acl_group],+ )+ end+ fab!(:anon_acl) do+ Fabricate(+ :access_control_list,+ target: anon_category,+ permission: "view",+ allowed_group_ids: [Group::AUTO_GROUPS[:anonymous_users]],+ )+ end++ before do+ Category.stubs(:has_mandatory_acl?).returns(false)+ Category.stubs(:acl_is_mandatory?).returns(false)+ end++ describe "#has_acl_permission?" do+ it "is true when a group the user belongs to grants the permission" do+ expect(acl_user.guardian.has_acl_permission?(member_category, "view")).to eq(true)+ end++ it "is false when the user's groups do not grant the permission" do+ expect(acl_user.guardian.has_acl_permission?(member_category, "edit")).to eq(false)+ end++ it "is falsey when there is no acl entry matching the user for the target" do+ expect(acl_user.guardian.has_acl_permission?(anon_category, "view")).to be_falsey+ end++ it "grants anonymous users permissions via the anonymous_users group" do+ expect(Guardian.new.has_acl_permission?(anon_category, "view")).to eq(true)+ end++ it "does not grant anonymous users permissions from member-only groups" do+ expect(Guardian.new.has_acl_permission?(member_category, "view")).to be_falsey+ end+ end++ describe "#has_any_acl_permission?" do+ it "is true when any of the permissions are granted" do+ expect(acl_user.guardian.has_any_acl_permission?(member_category, %w[edit view])).to eq(+ true,+ )+ end++ it "is false when none of the permissions are granted" do+ expect(acl_user.guardian.has_any_acl_permission?(member_category, %w[edit manage])).to eq(+ false,+ )+ end++ it "is true for anonymous users when the anonymous group grants one" do+ expect(Guardian.new.has_any_acl_permission?(anon_category, %w[edit view])).to eq(true)+ end++ it "is false for anonymous users without a matching group" do+ expect(Guardian.new.has_any_acl_permission?(member_category, %w[edit view])).to eq(false)+ end+ end+ end+describe "can_enable_safe_mode" dofab!(:user)fab!(:moderator)diff --git a/spec/models/access_control_list_spec.rb b/spec/models/access_control_list_spec.rbnew file mode 100644index 00000000000..15e79ab01c3--- /dev/null+++ b/spec/models/access_control_list_spec.rb@@ -0,0 +1,263 @@+# frozen_string_literal: true++RSpec.describe AccessControlList do+ fab!(:target, :category)+ fab!(:group) { Fabricate(:group, name: "marketing", full_name: "Marketing Team") }+ fab!(:other_group) { Fabricate(:group, name: "support", full_name: "Support Team") }++ describe ".expand_list" do+ it "collapses multiple groups sharing a permission into one record" do+ list = [+ { type: "group", id: group.id, permission: "view" },+ { type: "group", id: other_group.id, permission: "view" },+ ]++ result = described_class.expand_list(list, target, "core")++ expect(result.size).to eq(1)+ entry = result.first+ expect(entry).to match(+ permission: "view",+ allowed_group_ids: contain_exactly(group.id, other_group.id),+ target_type: "Category",+ target_id: target.id,+ owner: "core",+ )+ end++ it "produces a separate record per distinct permission" do+ list = [+ { type: "group", id: group.id, permission: "view" },+ { type: "group", id: group.id, permission: "edit" },+ ]++ result = described_class.expand_list(list, target, "core")++ expect(result.map { |entry| entry[:permission] }).to contain_exactly("view", "edit")+ expect(result.find { |entry| entry[:permission] == "edit" }[:allowed_group_ids]).to(+ contain_exactly(group.id),+ )+ end++ it "accepts a symbol type and a custom owner" do+ list = [{ type: :group, id: group.id, permission: "view" }]++ result = described_class.expand_list(list, target, "chat")++ expect(result.first[:allowed_group_ids]).to contain_exactly(group.id)+ expect(result.first[:owner]).to eq("chat")+ end++ it "returns records that insert_all! can persist as valid acls" do+ list = [+ { type: "group", id: group.id, permission: "view" },+ { type: "group", id: other_group.id, permission: "edit" },+ ]++ described_class.insert_all!(described_class.expand_list(list, target, "core"))++ acls = described_class.where(target: target)+ expect(acls.pluck(:permission)).to contain_exactly("view", "edit")+ expect(acls.find_by(permission: "view").allowed_group_ids).to contain_exactly(group.id)+ expect(acls.find_by(permission: "edit").allowed_group_ids).to contain_exactly(other_group.id)+ end+ end++ describe ".inject_mandatory_acl" do+ let(:mandatory_acl) { { type: :group, id: group.id, permission: "manage" } }++ before do+ target.class.stubs(:has_mandatory_acl?).returns(true)+ target.class.stubs(:mandatory_acl).returns([mandatory_acl])+ end++ it "adds missing mandatory acl entries" do+ flattened_acl = [{ type: "group", id: other_group.id, permission: "view" }]++ result = described_class.inject_mandatory_acl(flattened_acl, target)++ expect(result).to contain_exactly(+ { type: "group", id: other_group.id, permission: "view" },+ mandatory_acl,+ )+ end++ it "does not duplicate mandatory acl entries" do+ flattened_acl = [{ type: "group", id: group.id, permission: "manage" }]++ result = described_class.inject_mandatory_acl(flattened_acl, target)++ expect(result).to contain_exactly({ type: "group", id: group.id, permission: "manage" })+ end+ end++ describe ".flattened_list" do+ fab!(:view_acl) do+ Fabricate(+ :access_control_list_with_groups,+ target: target,+ permission: "view",+ groups: [group],+ )+ end++ fab!(:edit_acl) do+ Fabricate(+ :access_control_list_with_groups,+ target: target,+ permission: "edit",+ groups: [group, other_group],+ )+ end++ before { target.class.stubs(:acl_is_mandatory?).returns(false) }++ it "returns one entry per group per acl with the group metadata" do+ list = described_class.where(target: target).flattened_list++ expect(list.size).to eq(3)++ view_entry = list.find { |entry| entry[:permission] == "view" }+ expect(view_entry).to include(+ type: :group,+ id: group.id,+ permission: "view",+ name: group.name,+ full_name: group.full_name,+ target_type: "Category",+ target_id: target.id,+ )+ expect(view_entry[:metadata]).to eq({ auto_group: false })+ end++ it "emits an entry for every allowed group on an acl" do+ list = described_class.where(target: target, permission: "edit").flattened_list++ expect(list.map { |entry| entry[:id] }).to contain_exactly(group.id, other_group.id)+ end++ it "flags automatic groups in the metadata" do+ Fabricate(+ :access_control_list_with_groups,+ target: target,+ permission: "manage",+ groups: [Group.find(Group::AUTO_GROUPS[:admins])],+ )++ entry = described_class.where(target: target, permission: "manage").flattened_list.first++ expect(entry[:metadata]).to eq({ auto_group: true })+ end++ it "marks mandatory acl entries" do+ target+ .class+ .stubs(:acl_is_mandatory?)+ .with({ type: :group, id: group.id, permission: "view" })+ .returns(true)++ list = described_class.where(target: target).flattened_list++ expect(list.map { |entry| entry.slice(:id, :permission, :mandatory) }).to contain_exactly(+ { id: group.id, permission: "view", mandatory: true },+ { id: group.id, permission: "edit", mandatory: false },+ { id: other_group.id, permission: "edit", mandatory: false },+ )+ end++ it "returns an empty array when there are no acls" do+ expect(described_class.where(target: Fabricate(:category)).flattened_list).to eq([])+ end++ it "does not error if one of the groups is deleted" do+ group.destroy!+ expect { described_class.where(target: target).flattened_list }.not_to raise_error+ end++ context "when for_target is provided" do+ it "stamps every entry with the given target's id and type" do+ list = described_class.where(target: target).flattened_list(for_target: target)++ expect(list.map { |entry| entry[:target_type] }.uniq).to eq(["Category"])+ expect(list.map { |entry| entry[:target_id] }.uniq).to eq([target.id])+ end++ it "raises when the relation spans more than one target" do+ Fabricate(:access_control_list_with_groups, permission: "view", groups: [group])++ expect { described_class.all.flattened_list(for_target: target) }.to raise_error(+ Acl::MixedTargetError,+ )+ end+ end+ end++ describe ".preload_allowed" do+ it "populates allowed_groups_preloaded from allowed_group_ids" do+ acl = Fabricate(:access_control_list_with_groups, groups: [group, other_group])++ loaded = described_class.where(id: acl.id).preload_allowed.first++ expect(loaded.allowed_groups_preloaded.map(&:id)).to contain_exactly(group.id, other_group.id)+ end++ it "loads the allowed groups for the whole relation without an N+1" do+ one = Fabricate(:access_control_list_with_groups, groups: [group])++ queries_for_one =+ track_sql_queries do+ described_class+ .where(id: one.id)+ .preload_allowed+ .each { |acl| acl.allowed_groups_preloaded }+ end++ two = Fabricate(:access_control_list_with_groups, groups: [group])+ three = Fabricate(:access_control_list_with_groups, groups: [other_group])++ queries_for_many =+ track_sql_queries do+ described_class+ .where(id: [one.id, two.id, three.id])+ .preload_allowed+ .each { |acl| acl.allowed_groups_preloaded }+ end++ expect(queries_for_many.size).to eq(queries_for_one.size)+ end+ end++ describe ".matching_user" do+ fab!(:user)+ fab!(:member_group) { Fabricate(:group).tap { |new_group| new_group.add(user) } }+ fab!(:non_member_group, :group)+ fab!(:group_acl) { Fabricate(:access_control_list_with_groups, groups: [member_group]) }+ fab!(:other_group_acl) do+ Fabricate(:access_control_list_with_groups, groups: [non_member_group])+ end+ fab!(:direct_user_acl) { Fabricate(:access_control_list_with_users, users: [user]) }+ fab!(:anonymous_acl) do+ Fabricate(:access_control_list, allowed_group_ids: [Group::AUTO_GROUPS[:anonymous_users]])+ end++ it "matches acls allowing a group the user belongs to" do+ expect(described_class.matching_user(user)).to include(group_acl)+ end++ it "matches acls that allow the user directly" do+ expect(described_class.matching_user(user)).to include(direct_user_acl)+ end++ it "does not match acls for groups the user does not belong to" do+ expect(described_class.matching_user(user)).not_to include(other_group_acl, anonymous_acl)+ end++ it "matches the anonymous group acl for a nil user" do+ expect(described_class.matching_user(nil)).to include(anonymous_acl)+ end++ it "does not match member group acls for a nil user" do+ expect(described_class.matching_user(nil)).not_to include(group_acl, direct_user_acl)+ end+ end+enddiff --git a/spec/models/concerns/acl_target_spec.rb b/spec/models/concerns/acl_target_spec.rbnew file mode 100644index 00000000000..fa5d5b5f1e0--- /dev/null+++ b/spec/models/concerns/acl_target_spec.rb@@ -0,0 +1,67 @@+# frozen_string_literal: true++RSpec.describe AclTarget do+ let(:target_class) do+ Class.new(ActiveRecord::Base) do+ include AclTarget++ self.table_name = "posts"++ def self.name+ "AclTargetSpecTarget"+ end+ end+ end++ it "adds mandatory acl class methods" do+ expect(target_class).to respond_to(:has_mandatory_acl?, :acl_is_mandatory?)+ end++ it "registers loaded target classes" do+ expect(described_class.target_classes).to include(target_class)+ end++ describe ".acl_target_key" do+ it "returns the class name" do+ expect(target_class.acl_target_key).to eq("AclTargetSpecTarget")+ end+ end++ describe ".has_mandatory_acl?" do+ it "returns false without mandatory acl entries" do+ expect(target_class).not_to have_mandatory_acl++ target_class.define_singleton_method(:mandatory_acl) { [] }++ expect(target_class).not_to have_mandatory_acl+ end++ it "returns true with mandatory acl entries" do+ target_class.define_singleton_method(:mandatory_acl) do+ [{ type: :group, id: 1, permission: "view" }]+ end++ expect(target_class).to have_mandatory_acl+ end+ end++ describe ".acl_is_mandatory?" do+ before do+ target_class.define_singleton_method(:mandatory_acl) do+ [{ type: :group, id: 1, permission: "view" }, { type: :user, id: 2, permission: "edit" }]+ end+ end++ it "returns true for matching mandatory acl entries" do+ expect(target_class.acl_is_mandatory?({ type: :group, id: 1, permission: "view" })).to eq(+ true,+ )+ end++ it "returns false for different acl entries" do+ expect(target_class.acl_is_mandatory?({ type: :group, id: 1, permission: "edit" })).to eq(+ false,+ )+ end+ end+enddiff --git a/spec/models/group_spec.rb b/spec/models/group_spec.rbindex 64c3961cd5b..f098ff5e45e 100644--- a/spec/models/group_spec.rb+++ b/spec/models/group_spec.rb@@ -1,9 +1,9 @@# frozen_string_literal: trueRSpec.describe Group do- let(:admin) { Fabricate(:admin) }- let(:user) { Fabricate(:user) }- let(:group) { Fabricate(:group) }+ fab!(:admin)+ fab!(:user)+ fab!(:group)it_behaves_like "it has custom fields"@@ -561,20 +561,20 @@ RSpec.describe Group doendit "Can update moderator/staff/admin groups correctly" do- admin = Fabricate(:admin)+ other_admin = Fabricate(:admin)moderator = Fabricate(:moderator)Group.refresh_automatic_groups!(:admins, :staff, :moderators)- expect(Group[:admins].human_users).to contain_exactly(admin)+ expect(Group[:admins].human_users).to contain_exactly(admin, other_admin)expect(Group[:moderators].human_users).to contain_exactly(moderator)- expect(Group[:staff].human_users).to contain_exactly(moderator, admin)+ expect(Group[:staff].human_users).to contain_exactly(moderator, admin, other_admin)- admin.admin = false- admin.save+ other_admin.admin = false+ other_admin.saveGroup.refresh_automatic_group!(:admins)- expect(Group[:admins].human_users).to be_empty+ expect(Group[:admins].human_users).to contain_exactly(admin)moderator.revoke_moderation!@@ -628,9 +628,9 @@ RSpec.describe Group doendit "Correctly updates all automatic groups upon request" do- admin = Fabricate(:admin)- user = Fabricate(:user)- user.change_trust_level!(TrustLevel[2])+ other_admin = Fabricate(:admin)+ other_user = Fabricate(:user)+ other_user.change_trust_level!(TrustLevel[2])DB.exec("UPDATE groups SET user_count = 0 WHERE id = #{Group::AUTO_GROUPS[:trust_level_2]}")@@ -641,19 +641,19 @@ RSpec.describe Group dog = Group[:admins]expect(g.human_users.count).to eq(g.user_count)- expect(g.human_users).to contain_exactly(admin)+ expect(g.human_users).to contain_exactly(admin, other_admin)g = Group[:admins]expect(g.human_users.count).to eq(g.user_count)- expect(g.human_users).to contain_exactly(admin)+ expect(g.human_users).to contain_exactly(admin, other_admin)g = Group[:trust_level_1]expect(g.human_users.count).to eq(g.user_count)- expect(g.human_users).to contain_exactly(admin, user)+ expect(g.human_users).to contain_exactly(admin, other_admin, user, other_user)g = Group[:trust_level_2]expect(g.human_users.count).to eq(g.user_count)- expect(g.human_users).to contain_exactly(admin, user)+ expect(g.human_users).to contain_exactly(admin, other_admin, other_user)endit "can set members via usernames helper" do@@ -1894,4 +1894,12 @@ RSpec.describe Group doexpect(Group.find_by_email("[email protected]")).to eq(nil)endend++ context "when a group is deleted" do+ it "enqueues a job to update the associated access_control_list records" do+ expect_enqueued_with(job: :cleanup_acls_for_deleted, args: { group_id: group.id }) do+ group.destroy!+ end+ end+ endenddiff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rbindex 95600cb8dcf..06d5dd63795 100644--- a/spec/models/user_spec.rb+++ b/spec/models/user_spec.rb@@ -4245,4 +4245,39 @@ RSpec.describe User doendendend++ describe "acl permissions" do+ fab!(:acl_user) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:acl_group) { Fabricate(:group).tap { |group| group.add(acl_user) } }+ fab!(:viewable_category, :category)+ fab!(:editable_category, :category)+ fab!(:view_acl) do+ Fabricate(+ :access_control_list_with_groups,+ target: viewable_category,+ permission: "view",+ groups: [acl_group],+ )+ end+ fab!(:edit_acl) do+ Fabricate(+ :access_control_list_with_groups,+ target: editable_category,+ permission: "edit",+ groups: [acl_group],+ )+ end++ before do+ Category.stubs(:has_mandatory_acl?).returns(true)+ Category.stubs(:acl_is_mandatory?).returns(true)+ end++ describe "#permission_acl" do+ it "builds an Acl::User from the acls matching the user and memoizes it" do+ expect(acl_user.permission_acl).to be_a(Acl::User)+ expect(acl_user.permission_acl).to equal(acl_user.permission_acl)+ end+ end+ endenddiff --git a/spec/requests/api/schemas/json/site_response.json b/spec/requests/api/schemas/json/site_response.jsonindex ba761e4c7be..9f1cc0dc4e8 100644--- a/spec/requests/api/schemas/json/site_response.json+++ b/spec/requests/api/schemas/json/site_response.json@@ -275,74 +275,68 @@},"groups": {"type": "array",- "items":- {- "type": "object",- "additionalProperties": false,- "properties": {- "id": {- "type": "integer"- },- "name": {- "type": "string"- },- "flair_url": {- "type": [- "string",- "null"- ]- },- "flair_bg_color": {- "type": [- "string",- "null"- ]- },- "flair_color": {- "type": [- "string",- "null"- ]- },- "automatic": {- "type": [- "boolean"- ]- }+ "items": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "id": {+ "type": "integer"},- "required": [- "id",- "name",- "flair_url",- "flair_bg_color",- "flair_color",- "automatic"- ]- }+ "name": {+ "type": "string"+ },+ "full_name": {+ "type": "string"+ },+ "flair_url": {+ "type": [+ "string",+ "null"+ ]+ },+ "flair_bg_color": {+ "type": [+ "string",+ "null"+ ]+ },+ "flair_color": {+ "type": [+ "string",+ "null"+ ]+ },+ "automatic": {+ "type": [+ "boolean"+ ]+ }+ },+ "required": [+ "id",+ "name",+ "flair_url",+ "flair_bg_color",+ "flair_color",+ "automatic"+ ]+ }},"filters": {"type": "array",- "items": {-- }+ "items": {}},"periods": {"type": "array",- "items": {-- }+ "items": {}},"top_menu_items": {"type": "array",- "items": {-- }+ "items": {}},"anonymous_top_menu_items": {"type": "array",- "items": {-- }+ "items": {}},"uncategorized_category_id": {"type": "integer"@@ -352,127 +346,137 @@},"post_action_types": {"type": "array",- "items":- {- "type": "object",- "additionalProperties": false,- "properties": {- "id": {- "type": ["integer", "null"]- },- "name_key": {- "type": ["string", "null"]- },- "name": {- "type": "string"- },- "description": {- "type": "string"- },- "short_description": {- "type": "string"- },- "is_flag": {- "type": "boolean"- },- "require_message": {- "type": "boolean"- },- "enabled": {- "type": "boolean"- },- "applies_to": {- "type": "array"- },- "is_used": {- "type": "boolean"- },- "position": {- "type": "integer"- },- "auto_action_type": {- "type": "boolean"- },- "system": {- "type": "boolean"- }+ "items": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "id": {+ "type": [+ "integer",+ "null"+ ]},- "required": [- "id",- "name_key",- "name",- "description",- "short_description",- "is_flag",- "require_message",- "enabled",- "applies_to",- "is_used",- "auto_action_type"- ]- }+ "name_key": {+ "type": [+ "string",+ "null"+ ]+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "short_description": {+ "type": "string"+ },+ "is_flag": {+ "type": "boolean"+ },+ "require_message": {+ "type": "boolean"+ },+ "enabled": {+ "type": "boolean"+ },+ "applies_to": {+ "type": "array"+ },+ "is_used": {+ "type": "boolean"+ },+ "position": {+ "type": "integer"+ },+ "auto_action_type": {+ "type": "boolean"+ },+ "system": {+ "type": "boolean"+ }+ },+ "required": [+ "id",+ "name_key",+ "name",+ "description",+ "short_description",+ "is_flag",+ "require_message",+ "enabled",+ "applies_to",+ "is_used",+ "auto_action_type"+ ]+ }},"topic_flag_types": {"type": "array",- "items":- {- "type": "object",- "additionalProperties": false,- "properties": {- "id": {- "type": ["integer", "null"]- },- "name_key": {- "type": ["string", "null"]- },- "name": {- "type": "string"- },- "description": {- "type": "string"- },- "short_description": {- "type": "string"- },- "is_flag": {- "type": "boolean"- },- "require_message": {- "type": "boolean"- },- "enabled": {- "type": "boolean"- },- "applies_to": {- "type": "array"- },- "is_used": {- "type": "boolean"- },- "position": {- "type": "integer"- },- "auto_action_type": {- "type": "boolean"- },- "system": {- "type": "boolean"- }+ "items": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "id": {+ "type": [+ "integer",+ "null"+ ]},- "required": [- "id",- "name_key",- "name",- "description",- "short_description",- "is_flag",- "require_message",- "enabled",- "applies_to",- "is_used",- "auto_action_type"- ]- }+ "name_key": {+ "type": [+ "string",+ "null"+ ]+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "short_description": {+ "type": "string"+ },+ "is_flag": {+ "type": "boolean"+ },+ "require_message": {+ "type": "boolean"+ },+ "enabled": {+ "type": "boolean"+ },+ "applies_to": {+ "type": "array"+ },+ "is_used": {+ "type": "boolean"+ },+ "position": {+ "type": "integer"+ },+ "auto_action_type": {+ "type": "boolean"+ },+ "system": {+ "type": "boolean"+ }+ },+ "required": [+ "id",+ "name_key",+ "name",+ "description",+ "short_description",+ "is_flag",+ "require_message",+ "enabled",+ "applies_to",+ "is_used",+ "auto_action_type"+ ]+ }},"can_create_tag": {"type": "boolean"@@ -501,7 +505,11 @@"type": "string"}},- "required": ["id", "name", "slug"]+ "required": [+ "id",+ "name",+ "slug"+ ]}},"wizard_required": {@@ -521,80 +529,79 @@},"topic_featured_link_allowed_category_ids": {"type": "array",- "items": {-- }+ "items": {}},"user_themes": {"type": "array",- "items":- {- "type": "object",- "additionalProperties": false,- "properties": {- "theme_id": {- "type": "integer"- },- "name": {- "type": "string"- },- "default": {- "type": "boolean"- },- "color_scheme_id": {- "type": [- "integer",- "null"- ]- },- "dark_color_scheme_id": {- "type": [- "integer",- "null"- ]- },- "only_theme_color_schemes": {- "type": "boolean"- }+ "items": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "theme_id": {+ "type": "integer"},- "required": [- "theme_id",- "name",- "default",- "color_scheme_id"- ]- }+ "name": {+ "type": "string"+ },+ "default": {+ "type": "boolean"+ },+ "color_scheme_id": {+ "type": [+ "integer",+ "null"+ ]+ },+ "dark_color_scheme_id": {+ "type": [+ "integer",+ "null"+ ]+ },+ "only_theme_color_schemes": {+ "type": "boolean"+ }+ },+ "required": [+ "theme_id",+ "name",+ "default",+ "color_scheme_id"+ ]+ }},"user_color_schemes": {"type": "array",- "items":- {- "type": "object",- "additionalProperties": false,- "properties": {- "id": {- "type": "integer"- },- "name": {- "type": "string"- },- "is_dark": {- "type": "boolean"- },- "theme_id": {- "type": ["integer", "null"]- },- "colors": {- "type": "array"- }+ "items": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "id": {+ "type": "integer"},- "required": [- "id",- "name",- "is_dark",- "colors"- ]- }+ "name": {+ "type": "string"+ },+ "is_dark": {+ "type": "boolean"+ },+ "theme_id": {+ "type": [+ "integer",+ "null"+ ]+ },+ "colors": {+ "type": "array"+ }+ },+ "required": [+ "id",+ "name",+ "is_dark",+ "colors"+ ]+ }},"default_light_color_scheme": {"type": [@@ -617,8 +624,7 @@"custom_emoji_translation": {"type": "object","additionalProperties": false,- "properties": {- }+ "properties": {}},"watched_words_replace": {"type": [@@ -632,327 +638,314 @@"null"]},- "markdown_additional_options" : {+ "markdown_additional_options": {"type": "object"},- "hashtag_configurations" : {+ "hashtag_configurations": {"type": "object"},- "hashtag_icons" : {+ "hashtag_icons": {"type": "object"},- "displayed_about_plugin_stat_groups" : {+ "displayed_about_plugin_stat_groups": {"type": "array"},"categories": {"type": "array",- "items":- {- "type": "object",- "additionalProperties": false,- "properties": {- "id": {- "type": "integer"- },- "name": {- "type": "string"- },- "color": {- "type": "string"- },- "text_color": {- "type": "string"- },- "style_type": {- "type": "string"- },- "emoji": {- "type": [- "string",- "null"- ]- },- "icon": {- "type": [- "string",- "null"- ]- },- "slug": {- "type": "string"- },- "topic_count": {- "type": "integer"- },- "post_count": {- "type": "integer"- },- "position": {- "type": "integer"- },- "description": {- "type": [- "string",- "null"- ]- },- "description_text": {- "type": [- "string",- "null"- ]- },- "description_excerpt": {- "type": [- "string",- "null"- ]- },- "topic_url": {- "type": "string"- },- "read_restricted": {- "type": "boolean"- },- "permission": {- "type": "integer"- },- "notification_level": {- "type": "integer"- },- "topic_template": {- "type": [- "string",- "null"- ]- },- "topic_title_placeholder": {- "type": [- "string",- "null"- ]- },- "has_children": {- "type": "boolean"- },- "subcategory_count": {- "type": [- "integer",- "null"- ]- },- "sort_order": {- "type": [- "string",- "null"- ]- },- "sort_ascending": {- "type": [- "string",- "null"- ]- },- "show_subcategory_list": {- "type": "boolean"- },- "num_featured_topics": {- "type": "integer"- },- "default_view": {- "type": [- "string",- "null"- ]- },- "subcategory_list_style": {- "type": "string"- },- "default_top_period": {- "type": "string"- },- "default_list_filter": {- "type": "string"- },- "minimum_required_tags": {- "type": "integer"- },- "navigate_to_first_post_after_read": {- "type": "boolean"- },- "allowed_tags": {- "type": "array",- "items": {-- }- },- "allowed_tag_groups": {- "type": "array",- "items": {-- }- },- "allow_global_tags": {- "type": "boolean"- },- "required_tag_groups": {- "type": "array",- "items":- {- "type": "object",- "additionalProperties": false,- "properties": {- "name": {- "type": "string"- },- "min_count": {- "type": "integer"- }- },- "required": [- "name",- "min_count"- ]+ "items": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "id": {+ "type": "integer"+ },+ "name": {+ "type": "string"+ },+ "color": {+ "type": "string"+ },+ "text_color": {+ "type": "string"+ },+ "style_type": {+ "type": "string"+ },+ "emoji": {+ "type": [+ "string",+ "null"+ ]+ },+ "icon": {+ "type": [+ "string",+ "null"+ ]+ },+ "slug": {+ "type": "string"+ },+ "topic_count": {+ "type": "integer"+ },+ "post_count": {+ "type": "integer"+ },+ "position": {+ "type": "integer"+ },+ "description": {+ "type": [+ "string",+ "null"+ ]+ },+ "description_text": {+ "type": [+ "string",+ "null"+ ]+ },+ "description_excerpt": {+ "type": [+ "string",+ "null"+ ]+ },+ "topic_url": {+ "type": "string"+ },+ "read_restricted": {+ "type": "boolean"+ },+ "permission": {+ "type": "integer"+ },+ "notification_level": {+ "type": "integer"+ },+ "topic_template": {+ "type": [+ "string",+ "null"+ ]+ },+ "topic_title_placeholder": {+ "type": [+ "string",+ "null"+ ]+ },+ "has_children": {+ "type": "boolean"+ },+ "subcategory_count": {+ "type": [+ "integer",+ "null"+ ]+ },+ "sort_order": {+ "type": [+ "string",+ "null"+ ]+ },+ "sort_ascending": {+ "type": [+ "string",+ "null"+ ]+ },+ "show_subcategory_list": {+ "type": "boolean"+ },+ "num_featured_topics": {+ "type": "integer"+ },+ "default_view": {+ "type": [+ "string",+ "null"+ ]+ },+ "subcategory_list_style": {+ "type": "string"+ },+ "default_top_period": {+ "type": "string"+ },+ "default_list_filter": {+ "type": "string"+ },+ "minimum_required_tags": {+ "type": "integer"+ },+ "navigate_to_first_post_after_read": {+ "type": "boolean"+ },+ "allowed_tags": {+ "type": "array",+ "items": {}+ },+ "allowed_tag_groups": {+ "type": "array",+ "items": {}+ },+ "allow_global_tags": {+ "type": "boolean"+ },+ "required_tag_groups": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "name": {+ "type": "string"+ },+ "min_count": {+ "type": "integer"}- },- "read_only_banner": {- "type": [- "string",- "null"- ]- },- "uploaded_logo": {- "type": [- "string",- "null"- ]- },- "uploaded_logo_dark": {- "type": [- "string",- "null"+ },+ "required": [+ "name",+ "min_count"]- },- "uploaded_background": {- "type": [- "string",- "null"- ]- },- "uploaded_background_dark": {- "type": [- "string",- "null"- ]- },- "can_edit": {- "type": "boolean"- },- "custom_fields": {- "type": [- "object",- "null"- ],- "additionalProperties": true- },- "parent_category_id": {- "type": "integer"- },- "form_template_ids": {- "type": "array",- "items": {}- },- "category_types": {- "type": "object",- "additionalProperties": true}},- "required": [- "id",- "name",- "color",- "text_color",- "slug",- "topic_count",- "post_count",- "position",- "topic_url",- "read_restricted",- "permission",- "notification_level",- "topic_template",- "topic_title_placeholder",- "has_children",- "subcategory_count",- "sort_order",- "sort_ascending",- "show_subcategory_list",- "num_featured_topics",- "default_view",- "subcategory_list_style",- "default_top_period",- "default_list_filter",- "minimum_required_tags",- "navigate_to_first_post_after_read",- "allowed_tags",- "allowed_tag_groups",- "allow_global_tags",- "required_tag_groups",- "read_only_banner",- "uploaded_logo",- "uploaded_logo_dark",- "uploaded_background",- "uploaded_background_dark",- "can_edit"- ]- }+ "read_only_banner": {+ "type": [+ "string",+ "null"+ ]+ },+ "uploaded_logo": {+ "type": [+ "string",+ "null"+ ]+ },+ "uploaded_logo_dark": {+ "type": [+ "string",+ "null"+ ]+ },+ "uploaded_background": {+ "type": [+ "string",+ "null"+ ]+ },+ "uploaded_background_dark": {+ "type": [+ "string",+ "null"+ ]+ },+ "can_edit": {+ "type": "boolean"+ },+ "custom_fields": {+ "type": [+ "object",+ "null"+ ],+ "additionalProperties": true+ },+ "parent_category_id": {+ "type": "integer"+ },+ "form_template_ids": {+ "type": "array",+ "items": {}+ },+ "category_types": {+ "type": "object",+ "additionalProperties": true+ }+ },+ "required": [+ "id",+ "name",+ "color",+ "text_color",+ "slug",+ "topic_count",+ "post_count",+ "position",+ "topic_url",+ "read_restricted",+ "permission",+ "notification_level",+ "topic_template",+ "topic_title_placeholder",+ "has_children",+ "subcategory_count",+ "sort_order",+ "sort_ascending",+ "show_subcategory_list",+ "num_featured_topics",+ "default_view",+ "subcategory_list_style",+ "default_top_period",+ "default_list_filter",+ "minimum_required_tags",+ "navigate_to_first_post_after_read",+ "allowed_tags",+ "allowed_tag_groups",+ "allow_global_tags",+ "required_tag_groups",+ "read_only_banner",+ "uploaded_logo",+ "uploaded_logo_dark",+ "uploaded_background",+ "uploaded_background_dark",+ "can_edit"+ ]+ }},"archetypes": {"type": "array",- "items":- {- "type": "object",- "additionalProperties": false,- "properties": {- "id": {- "type": "string"- },- "name": {- "type": "string"- },- "options": {- "type": "array",- "items": {-- }- }+ "items": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "id": {+ "type": "string"},- "required": [- "id",- "name",- "options"- ]- }+ "name": {+ "type": "string"+ },+ "options": {+ "type": "array",+ "items": {}+ }+ },+ "required": [+ "id",+ "name",+ "options"+ ]+ }},"user_fields": {"type": "array",- "items": {-- }+ "items": {}},"auth_providers": {"type": "array",- "items": {-- }+ "items": {}},- "whispers_allowed_groups_names" : {+ "whispers_allowed_groups_names": {"type": "array"},- "denied_emojis" : {+ "denied_emojis": {"type": "array"},- "valid_flag_applies_to_types" : {+ "valid_flag_applies_to_types": {"type": "array"},"navigation_menu_site_top_tags": {@@ -964,8 +957,21 @@"full_name_visible_in_signup": {"type": "boolean"},- "admin_config_login_routes" : {+ "admin_config_login_routes": {"type": "array"+ },+ "access_control": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "mandatory_acl": {+ "type": "object",+ "additionalProperties": true+ }+ },+ "required": [+ "mandatory_acl"+ ]}},"required": [@@ -1004,4 +1010,4 @@"full_name_visible_in_signup","email_configured"]-}+}\ No newline at end of filediff --git a/spec/requests/users_controller_spec.rb b/spec/requests/users_controller_spec.rbindex b9967bf44c0..aca3a894e81 100644--- a/spec/requests/users_controller_spec.rb+++ b/spec/requests/users_controller_spec.rb@@ -5733,7 +5733,7 @@ RSpec.describe UsersController do}expect(response.status).to eq(200)groups = response.parsed_body["groups"]- expect(groups).to eq([{ "name" => "admins", "full_name" => nil }])+ expect(groups).to eq([{ "name" => "admins", "full_name" => "Admins" }])DiscoursePluginRegistry.reset!enddiff --git a/spec/serializers/site_serializer_spec.rb b/spec/serializers/site_serializer_spec.rbindex 9f3673e43e5..b68117f5b87 100644--- a/spec/serializers/site_serializer_spec.rb+++ b/spec/serializers/site_serializer_spec.rb@@ -32,6 +32,57 @@ RSpec.describe SiteSerializer doendend+ describe "#access_control" do+ let(:target_class) do+ Class.new(ActiveRecord::Base) do+ include AclTarget++ self.table_name = "posts"++ def self.name+ "SiteSerializerSpecTarget"+ end++ def self.mandatory_acl+ [{ type: :group, id: Group::AUTO_GROUPS[:admins], permission: "manage" }]+ end+ end+ end++ after { DiscoursePluginRegistry.reset_register!(:acl_target_classes) }++ it "includes mandatory ACLs by target class" do+ target_class++ serialized = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json++ expect(serialized.dig(:access_control, :mandatory_acl)).to include(+ "SiteSerializerSpecTarget" => [+ { type: :group, id: Group::AUTO_GROUPS[:admins], permission: "manage" },+ ],+ )+ end++ it "includes plugin-registered target classes" do+ Object.const_set(:SiteSerializerSpecTarget, target_class)+ AclTarget.loaded_target_classes.delete(target_class)+ DiscoursePluginRegistry.register_acl_target_class(+ "SiteSerializerSpecTarget",+ Plugin::Instance.new,+ )++ serialized = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json++ expect(serialized.dig(:access_control, :mandatory_acl)).to include(+ "SiteSerializerSpecTarget" => [+ { type: :group, id: Group::AUTO_GROUPS[:admins], permission: "manage" },+ ],+ )+ ensure+ Object.send(:remove_const, :SiteSerializerSpecTarget) if defined?(SiteSerializerSpecTarget)+ end+ end+it "includes category custom fields only if its preloaded" docategory.custom_fields["enable_marketplace"] = truecategory.save_custom_fieldsdiff --git a/spec/services/access_control_list_manager_spec.rb b/spec/services/access_control_list_manager_spec.rbnew file mode 100644index 00000000000..13d70cce7c6--- /dev/null+++ b/spec/services/access_control_list_manager_spec.rb@@ -0,0 +1,166 @@+# frozen_string_literal: true++RSpec.describe AccessControlListManager do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:target) }+ it { is_expected.to validate_presence_of(:owner) }+ it { is_expected.to validate_length_of(:owner).is_at_most(100) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:admin)+ fab!(:category)+ fab!(:group)+ fab!(:other_group, :group)++ let(:params) { { target:, flattened_acl:, owner: } }+ let(:dependencies) { { guardian: } }+ let(:guardian) { admin.guardian }+ let(:target) { category }+ let(:owner) { "test_owner" }++ let(:flattened_acl) do+ [+ { type: "group", id: group.id, permission: "view" },+ { type: "group", id: other_group.id, permission: "edit" },+ ]+ end++ before do+ Category.stubs(:has_mandatory_acl?).returns(false)+ Category.stubs(:acl_is_mandatory?).returns(false)+ end++ context "when the contract is invalid" do+ let(:owner) { "" }++ it { is_expected.to fail_a_contract }+ end++ context "when no ACLs are provided" do+ let(:flattened_acl) { [] }++ it { is_expected.to fail_a_policy(:has_at_least_one_acl) }+ end++ context "when everything is ok" do+ it { is_expected.to run_successfully }++ it "creates one access control list per permission for the target" do+ expect { result }.to change { AccessControlList.where(target: category).count }.from(0).to(+ 2,+ )++ view_acl = AccessControlList.find_by(target: category, permission: "view")+ edit_acl = AccessControlList.find_by(target: category, permission: "edit")+ expect(view_acl.allowed_group_ids).to contain_exactly(group.id)+ expect(edit_acl.allowed_group_ids).to contain_exactly(other_group.id)+ end++ it "stamps the records with the given owner" do+ result++ expect(AccessControlList.where(target: category).pluck(:owner).uniq).to eq(["test_owner"])+ end++ it "logs the permission change as a staff action" do+ expect { result }.to change {+ UserHistory.where(+ action: UserHistory.actions[:change_access_control_list_permissions],+ ).count+ }.by(1)++ log = UserHistory.last+ expect(log.subject).to eq("Category (#{category.id})")+ expect(log.new_value).to include("view", "edit")+ expect(log.previous_value).to eq("")+ end+ end++ context "when permissions already exist for the target" do+ fab!(:existing_acl) do+ Fabricate(+ :access_control_list_with_groups,+ target: category,+ permission: "manage",+ groups: [group],+ )+ end++ it "replaces the previous access control lists" do+ existing_id = existing_acl.id+ result++ expect(AccessControlList.where(target: category).pluck(:permission)).to contain_exactly(+ "view",+ "edit",+ )+ expect(AccessControlList.find_by(id: existing_id)).to be_nil+ end++ it "records the previous permissions in the staff action log" do+ result++ log = UserHistory.last+ expect(log.subject).to eq("Category (#{category.id})")+ expect(log.new_value).to include("view", "edit")+ expect(log.previous_value).to include("manage")+ end+ end++ describe "mandatory ACL" do+ context "when the target does not have mandatory ACLs" do+ before { Category.stubs(:has_mandatory_acl?).returns(false) }++ it "does not modify the flattened ACL" do+ result++ expect(AccessControlList.where(target: category).pluck(:permission)).to contain_exactly(+ "edit",+ "view",+ )+ end+ end++ context "when the target has mandatory ACLs" do+ before do+ Category.stubs(:has_mandatory_acl?).returns(true)+ Category.stubs(:mandatory_acl).returns(+ [{ type: :group, id: Group::AUTO_GROUPS[:admins], permission: "manage" }],+ )+ end++ it "injects the mandatory ACL into the list of ACLs to be created" do+ result++ expect(AccessControlList.where(target: category).pluck(:permission)).to contain_exactly(+ "view",+ "edit",+ "manage",+ )++ manage_acl = AccessControlList.find_by(target: category, permission: "manage")+ expect(manage_acl.allowed_group_ids).to contain_exactly(Group::AUTO_GROUPS[:admins])+ end++ context "when the mandatory ACL is already included in the flattened ACL" do+ let(:flattened_acl) do+ [+ { type: "group", id: group.id, permission: "view" },+ { type: "group", id: other_group.id, permission: "edit" },+ { type: "group", id: Group::AUTO_GROUPS[:admins], permission: "manage" },+ ]+ end++ it "does not create duplicate ACLs" do+ result++ expect(AccessControlList.where(target: category, permission: "manage").count).to eq(1)+ end+ end+ end+ end+ end+enddiff --git a/spec/system/admin_groups_list_spec.rb b/spec/system/admin_groups_list_spec.rbindex 1cd5ad4c6f3..a4310d9a4ae 100644--- a/spec/system/admin_groups_list_spec.rb+++ b/spec/system/admin_groups_list_spec.rb@@ -14,18 +14,18 @@ describe "Admin Users Page" doadmin_groups_page.visitexpect(admin_groups_page).to have_groups(- %w[- admins- group_a- group_b- group_c- moderators- staff- trust_level_0- trust_level_1- trust_level_2- trust_level_3- trust_level_4+ [+ "Admins",+ "group_a",+ "group_b",+ "group_c",+ "Moderators",+ "Staff",+ "Trust level 0",+ "Trust level 1",+ "Trust level 2",+ "Trust level 3",+ "Trust level 4",],)