A platform for community discussion. Free, open, simple.
FEATURE: Implement Owner functionality for ACLs (#44882)
Martin Brennan2cf4cb76ccab
diff --git a/.skills/discourse-acl-authoring/SKILL.md b/.skills/discourse-acl-authoring/SKILL.mdindex 6c348363e6b..741a2d146c3 100644--- a/.skills/discourse-acl-authoring/SKILL.md+++ b/.skills/discourse-acl-authoring/SKILL.md@@ -1,6 +1,6 @@---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, banned_acl, loss_warning_permissions, ACL modification evaluation, Site access_control metadata, plugin ACL target registration, DAccessControl, or DAccessControlField.+description: Use when creating, editing, or reviewing Discourse access-control-list features built on AccessControlList, AclTarget, Guardian ACL helpers, AccessControlList::Apply, mandatory_acl, banned_acl, loss_warning_permissions, ACL modification evaluation, Site access_control metadata, plugin ACL target registration, DAccessControl, or DAccessControlField.---# Discourse ACL Authoring@@ -18,18 +18,20 @@ Use this skill before adding or reviewing ACL-backed resource permissions in Dis## Non-Negotiables-- Define or inherit `ACL_PERMISSIONS = Acl::Permissions.new(...)` on every ACL target. Use its named readers in permission declarations; the manager validates final grants against its values before replacing rows.+- Define or inherit `ACL_PERMISSIONS = Acl::Permissions.new(...)` on every ACL target. Use its named readers in permission declarations; the replacement service validates final grants against its values before replacing rows.- Every permission option added by `transformPermissionOptions(options)` must have an ID matching the target's server-side `ACL_PERMISSIONS`. Adding a UI option does not declare a server permission.-- 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 `owner` as a reserved, user-only permission supplied through the replacement service's dedicated owner-user argument. Never accept owner grants from the ordinary flattened ACL argument.+- Preserve owner grants during destructive ACL replacement. An owner implicitly satisfies every other permission check for the target, including target-id scopes.+- Put ordinary ACL authorization at the caller boundary before `AccessControlList::Apply.call`. When `owner_user_ids` is supplied, the service separately requires the actor to be a current owner or admin.+- Always call `AccessControlList::Apply` 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_for_bulk_insert` 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 and banned ACL metadata to the frontend.-- Treat `banned_acl` as a server-enforced restriction. `DAccessControl` hides banned permission choices for UX, but `AccessControlListManager` must still reject submitted banned entries.+- Treat `banned_acl` as a server-enforced restriction. `DAccessControl` hides banned permission choices for UX, but `AccessControlList::Apply` must still reject submitted banned entries.- Define `loss_warning_permissions` as permission strings whose loss by the current actor requires confirmation. Provide the target-specific server translation used by `AccessControlList::EvaluateModification`.- Prefer `DAccessControlField` inside FormKit. It owns required-permission validation, evaluates the proposed ACL, and uses FormKit's `preventSubmit` to cancel a submission without manufacturing a validation error.- Keep the default class-name `acl_target_key` when using `DAccessControlField`; its `@aclTarget.type` currently serves as both the Ruby class identifier and frontend metadata key.-- User grants are supported by backend storage/lookups and the frontend user/group search picker. Mandatory user ACL display still needs explicit UI support; the component's mandatory injection remains group-first.+- User grants are supported by backend storage/lookups and the frontend user/group search picker. Owner rows are distinct from mandatory ACL rows and render after them. Authorized owner managers can add user owners or remove an owner while at least one remains, except that `DAccessControl` does not offer new owners while `@isNew` is true; groups can never own a target. Other mandatory user ACL display still needs explicit UI support; the component's class-level mandatory injection remains group-first.## Local Anchors@@ -39,10 +41,10 @@ Use this skill before adding or reviewing ACL-backed resource permissions in Dis- 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`+- Write service: `app/services/access_control_list/apply.rb`- Modification evaluation: `app/services/access_control_list/evaluate_modification.rb`, `app/controllers/access_control_lists_controller.rb`- Deleted grantee cleanup: `app/jobs/regular/cleanup_acls_for_deleted.rb`, `app/models/group.rb`, `app/models/user.rb`- Site metadata: `app/models/site.rb`, `app/serializers/site_serializer.rb`- Frontend components: `frontend/discourse/app/ui-kit/d-access-control.gjs`, `frontend/discourse/app/ui-kit/d-access-control-field.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/services/access_control_list/evaluate_modification_spec.rb`, `spec/serializers/site_serializer_spec.rb`, `frontend/discourse/tests/integration/components/d-access-control-test.gjs`, `frontend/discourse/tests/integration/components/form-kit/field-test.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/apply_spec.rb`, `spec/services/access_control_list/evaluate_modification_spec.rb`, `spec/serializers/site_serializer_spec.rb`, `frontend/discourse/tests/integration/components/d-access-control-test.gjs`, `frontend/discourse/tests/integration/components/form-kit/field-test.gjs`- Plugin consumer example: `plugins/boards`, especially `app/models/boards/board.rb` and its create/update services and request specs.diff --git a/.skills/discourse-acl-authoring/references/backend-model.md b/.skills/discourse-acl-authoring/references/backend-model.mdindex c71210e9207..0e0015c72d4 100644--- a/.skills/discourse-acl-authoring/references/backend-model.md+++ b/.skills/discourse-acl-authoring/references/backend-model.md@@ -9,10 +9,14 @@ Use this reference when working with `AccessControlList`, `AclTarget`, `Acl::TarImportant columns:- `target_type`, `target_id`: polymorphic target.-- `permission`: string ID declared by the target's `ACL_PERMISSIONS`, such as `view`, `edit`, or `manage`. The manager enforces this vocabulary; direct bulk inserts bypass that policy.+- `permission`: string ID declared by the target's `ACL_PERMISSIONS`, such as `view`, `edit`, `manage`, or the built-in `owner`. The manager enforces this vocabulary; direct bulk inserts bypass that policy.- `allowed_group_ids`: bigint array of groups that hold the permission.- `allowed_user_ids`: bigint array of users that hold the permission. Backend storage/lookups and the frontend search picker support user grants; mandatory user ACL display still needs explicit UI support.-- `owner`: string identifying the owning subsystem, usually `"core"` or a plugin name.+- `source`: string identifying the subsystem that produced the ACL row, usually `"core"` or a plugin name. This provenance column is unrelated to the `owner` permission.++`owner` is a reserved, user-only permission automatically included by `Acl::Permissions`. Owners implicitly satisfy every other permission lookup for their target. Do not grant it to groups or expose it through an ordinary permission picker.++The system user is a valid owner even though its ID is negative. Owner contracts may accept `Discourse::SYSTEM_USER_ID` as the sole non-positive user ID, but must still verify that every requested owner resolves to an existing user.The model has a uniqueness validation and DB index for target + permission. Multiple groups for the same permission collapse into one row.@@ -27,7 +31,7 @@ The frontend and service params use flattened entries:]```-`AccessControlList.expand_list_for_bulk_insert(list, target, owner)` groups those entries by permission and returns rows suitable for `insert_all!`. It fills both `allowed_group_ids` and `allowed_user_ids`.+`AccessControlList.expand_list_for_bulk_insert(list, target, source)` groups those entries by permission and returns rows suitable for `insert_all!`. It fills both `allowed_group_ids` and `allowed_user_ids`.`AccessControlList.where(target: target).flattened_list` returns one entry per group or user per permission. Group entries include group metadata:@@ -89,6 +93,8 @@ 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.+For user lookups, an `owner` grant satisfies `has_*permission?`, `permission_user_ids`, and target-id queries for every other permission. Group lookups remain exact because groups cannot own ACL targets.+## Guardian HelpersUse the helper methods on `Guardian` instead of reaching into `user.permission_acl` from controllers:@@ -96,6 +102,8 @@ Use the helper methods on `Guardian` instead of reaching into `user.permission_a```rubyguardian.has_acl_permission?(target, "view")guardian.has_any_acl_permission?(target, %w[edit manage])+guardian.is_acl_owner?(target)+guardian.can_manage_acl_owner?(target)guardian.target_ids_with_acl_permission(TargetClass, "view")guardian.target_ids_with_any_acl_permissions(TargetClass, %w[view edit manage])```@@ -107,6 +115,8 @@ Board.with_acl_permission(guardian, "view")Board.with_any_acl_permissions(guardian, %w[view edit manage])```+These scopes include targets owned directly by the current user, even when `owner` is not listed explicitly.+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:@@ -138,7 +148,7 @@ class Board < ActiveRecord::Baseend```-Every target must define or inherit `ACL_PERMISSIONS`. Use named readers such as `ACL_PERMISSIONS.manage` in mandatory, banned, and loss-warning declarations; an unknown reader raises `NoMethodError`. The permission set and its string values are frozen. The manager validates the final ACL list, including injected mandatory entries, against `ACL_PERMISSIONS.values` before replacing any rows. A missing constant raises `NameError` to expose an incorrectly implemented target; an unknown submitted permission fails the service policy.+Every target must define or inherit `ACL_PERMISSIONS`. `Acl::Permissions` automatically adds the reserved `owner` permission and exposes `ACL_PERMISSIONS.owner`. Use named readers such as `ACL_PERMISSIONS.manage` in mandatory, banned, and loss-warning declarations; an unknown reader raises `NoMethodError`. The permission set and its string values are frozen. The manager validates the final ACL list, including injected mandatory and owner entries, against `ACL_PERMISSIONS.values` before replacing any rows. A missing constant raises `NameError` to expose an incorrectly implemented target; an unknown submitted permission fails the service policy.The concern provides:@@ -178,13 +188,13 @@ endMandatory 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.+- `AccessControlList::Apply` calls that method before inserting rows.- `flattened_list` marks matching entries with `mandatory: true`.- `Site#access_control` exposes mandatory ACL metadata for registered targets.Banned entries are consumed by both backend writes and frontend rendering:-- `AccessControlListManager` rejects submitted ACLs that match the target class's `banned_acl` via the `has_no_banned_acl` policy.+- `AccessControlList::Apply` rejects submitted ACLs that match the target class's `banned_acl` via the `has_no_banned_acl` policy.- `Site#access_control` exposes banned ACL metadata for registered targets.- `DAccessControl` filters banned permission options for the matching grantee.@@ -202,6 +212,8 @@ endThis is advisory, unlike `mandatory_acl` or `banned_acl`. It does not prevent persistence. `AccessControlList::EvaluateModification` checks the proposed ACL before save and reports when it would not grant the current user every configured permission.+For creation evaluations, where `target_id` is absent, the evaluator includes the current user's prospective `owner` grant. An owner satisfies all loss-warning permissions, matching the authoritative owner record that the target's create service will persist.+The concern provides:- `.has_loss_warning_permissions?` to detect non-empty configuration.diff --git a/.skills/discourse-acl-authoring/references/frontend-d-access-control.md b/.skills/discourse-acl-authoring/references/frontend-d-access-control.mdindex 299bd678072..8728cf5d6ba 100644--- a/.skills/discourse-acl-authoring/references/frontend-d-access-control.md+++ b/.skills/discourse-acl-authoring/references/frontend-d-access-control.md@@ -28,6 +28,7 @@ Arguments:- `@acl`: flattened ACL entries from the backend or form state. The backend can emit group and user entries, and this component can add groups from the preloaded `@groups` list plus user/group search results from the ACL grantee search endpoint.- `@onChange`: called with the next flattened ACL array when the user adds/removes/changes a row.- `@aclTarget`: optional object with `type`, `id`, and `name`. `type` identifies the registered Ruby target class, `id` identifies an existing target when present, and `name` is used in validation copy. The component uses `type` to load mandatory and banned ACL metadata.+- `@isNew`: prevents ordinary user rows from being promoted to owners during target creation. Initial ownership remains the responsibility of the create service.- `@transformPermissionOptions`: optional callback to customize default permission labels/descriptions or add target-specific permissions whose IDs are declared in the target's server-side `ACL_PERMISSIONS`.Example target descriptor:@@ -57,9 +58,9 @@ aclChanged(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.+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 `AccessControlList::Apply` with the submitted ACL array so mandatory entries are injected server-side too.-Banned ACL rows are also read from `this.site.access_control`. The component filters matching permission options for the row's grantee by comparing `permission`, `type`, and `id`. This is only a UX guard; backend saves must still go through `AccessControlListManager`, which rejects banned entries.+Banned ACL rows are also read from `this.site.access_control`. The component filters matching permission options for the row's grantee by comparing `permission`, `type`, and `id`. This is only a UX guard; backend saves must still go through `AccessControlList::Apply`, which rejects banned entries.## Permission Options@@ -88,7 +89,7 @@ transformPermissionOptions(options) {}```-Every permission option added by `transformPermissionOptions(options)` must have an `id` that exactly matches a string in the target's server-side `ACL_PERMISSIONS.values`. For the example above, the target must declare `ACL_PERMISSIONS = Acl::Permissions.new(:view, :edit, :manage)`. Adding an option in JavaScript does not register a permission on the server: `AccessControlListManager` rejects unsupported IDs before changing ACL rows. The `remove` option is a UI action that deletes a grant, not a persisted permission, so do not add it to `ACL_PERMISSIONS`.+Every permission option added by `transformPermissionOptions(options)` must have an `id` that exactly matches a string in the target's server-side `ACL_PERMISSIONS.values`. For the example above, the target must declare `ACL_PERMISSIONS = Acl::Permissions.new(:view, :edit, :manage)`. Adding an option in JavaScript does not register a permission on the server: `AccessControlList::Apply` rejects unsupported IDs before changing ACL rows. The `remove` option is a UI action that deletes a grant, not a persisted permission, so do not add it to `ACL_PERMISSIONS`.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.@@ -96,11 +97,15 @@ Target-specific options added via `@transformPermissionOptions` can still be ban## Row Behavior-- Rows are sorted with mandatory rows first, then by group name.+- Rows are sorted with mandatory rows first, owner rows second, then regular groups and users.+- Owner rows do not display the mandatory badge. Their permission control is enabled only when `@canManageOwners` is true.- 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.- Banned permissions are filtered per row only when the banned entry's `type`, `id`, and `permission` match the row.-- The remove action remains available unless the row is mandatory.+- The remove action remains available unless the row is mandatory, except authorized owner rows expose Remove.+- When `@canManageOwners` is true, user rows expose Owner unless `@isNew` is true, and owner rows expose only Owner and Remove. Group rows never expose Owner. Ownership still uses a dedicated save payload rather than `@transformPermissionOptions` or ordinary ACL params.+- Owner options use `@aclTarget.name` in their description, so consumers should provide a translated, sentence-compatible target name such as `board`.+- Submit the dedicated `owner_user_ids` payload only when editing an existing target and the actor can manage its owners. Omit it during ordinary edits by non-owners, and omit it during creation unless an admin is intentionally choosing the initial owner set. An empty owner array is still an ownership mutation, not "unchanged".- Newly added regular groups default to `edit`.- Read-only default auto groups (`anonymous_users`, `everyone`, `trust_level_0`) default to `view`.- Already selected grantees are removed from the add-group chooser's preloaded and remote results.@@ -158,7 +163,7 @@ Keep post-save lifecycle behavior in the consumer. For example, a modal can set`preventSubmit()` only affects the current validation pass. It does not roll back the edited ACL, mark the form invalid, or affect a later submission attempt.-Use low-level `DAccessControl` directly only when the surrounding UI is not a FormKit form or needs a materially different validation flow. Client validation and evaluation are UX safeguards; rely on server-side validation, authorization, and `AccessControlListManager` for enforcement.+Use low-level `DAccessControl` directly only when the surrounding UI is not a FormKit form or needs a materially different validation flow. Client validation and evaluation are UX safeguards; rely on server-side validation, authorization, and `AccessControlList::Apply` for enforcement.## Testing@@ -170,6 +175,9 @@ Consumer tests should cover:- `@aclTarget` renders mandatory rows from `site.access_control`- `@aclTarget` filters banned permissions from `site.access_control` for the matching grantee only- mandatory rows are locked and not duplicated+- mandatory rows precede owner rows; owner rows are user-only, have no mandatory badge, are locked without owner-management permission, are labelled Owner, and are unavailable as a selectable permission for other rows+- new targets do not offer Owner for ordinary user rows, even when the actor can manage owners+- creation and non-owner edit forms omit `owner_user_ids`, while authorized ownership edits submit the complete owner set- `@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.mdindex 83905d7e5f9..5bac8716b10 100644--- a/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md+++ b/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md@@ -1,21 +1,24 @@-# Manager, Services, and Plugin Integration+# ACL Replacement and Plugin IntegrationUse this reference when writing ACL rows, creating an ACL-backed target model, registering plugin targets, or serializing ACLs from controllers/services.-## AccessControlListManager+## AccessControlList::Apply-`AccessControlListManager` is the standard write path for replacing a target's ACLs.+`AccessControlList::Apply` is the standard write path for applying a target's complete ACL configuration. It resolves the registered target internally and serializes concurrent changes for the same target.```ruby-AccessControlListManager.call(+AccessControlList::Apply.call(guardian:,params: {- target: board,- flattened_acl: flattened_acl,- owner: Boards::PLUGIN_NAME,+ acl_target_type: board.class.name,+ acl_target_id: board.id,+ acl_entries: flattened_acl,+ source: Boards::PLUGIN_NAME,+ initial_owner_user_id: board.created_by_id,+ owner_user_ids: raw["owner_user_ids"],},) do |result|- on_success do |previous_permissions:, new_permissions:|+ on_success do |current_acl:, replacement:|# optional history/event workend@@ -27,25 +30,34 @@ endBehavior:-- validates `target` and `owner`-- fetches previous target permissions-- injects mandatory ACLs into `flattened_acl`+- validates the target identity, nested ordinary ACL entries, grantee identities, and `source`+- resolves the target only from registered ACL target classes+- locks the target identity around the read, validation, and replacement sequence+- reads previous target permissions directly from stored ACL rows+- resolves `initial_owner_user_id` only when the target has no valid stored owner and creates the initial owner grant from that user+- preserves existing owners when `owner_user_ids` is omitted; when supplied, treats it as the complete desired owner set+- allows any valid user to be the initial owner, but requires the actor to be an owner in the currently stored ACL or an admin whenever `owner_user_ids` is supplied; the actor does not need to remain in the requested set+- validates that every requested owner is a user and at least one owner remains+- rejects every `owner` entry in `acl_entries`; `owner_user_ids` is the only ownership mutation channel+- removes owners from lower direct user grants so one grantee does not render multiple ACL rows+- injects mandatory ACLs into `acl_entries`- resolves the target class's `ACL_PERMISSIONS` constant, including inherited declarations; a missing declaration raises `NameError`- fails `has_valid_permissions` if any final flattened ACL permission is absent from `ACL_PERMISSIONS.values`- fails `has_no_banned_acl` if any final flattened ACL entry matches the target class's `banned_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+- logs ordinary permission changes separately from owner additions and removals- 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.+Important: the service destructively replaces target ACL rows. Authorize ordinary permission changes before calling it; ownership changes are additionally authorized inside the service.++The service's `source` string is ACL row provenance, not target ownership. Pass the authoritative initial target owner's id separately as `initial_owner_user_id`; the service resolves the user model internally when the target has no owner. Use `owner_user_ids` only as the dedicated ownership mutation channel. Omit it to preserve owners and pass the complete desired set when a current owner or admin changes ownership. On an ownerless target, only an admin can supply `owner_user_ids`; a non-admin initial owner must add co-owners in a later call after ownership exists.## 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.+- Call the replacement service even when the submitted ACL array is empty. Empty means "replace with mandatory ACLs and owners"; skipping it leaves stale ACLs or creates ownerless records.+- Do not mutate ACL rows manually from controllers. Use the replacement service from a service step.+- Pass a stable source 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`.@@ -55,12 +67,13 @@ 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.+3. Call `AccessControlList::Apply` with the target's type and id plus `acl_entries: raw["acl"] || []`.+4. Pass the authoritative initial user's id as `initial_owner_user_id`; this may be any valid user. Do not trust an owner entry from `raw["acl"]`. Only an admin can also supply `owner_user_ids` while the target is still ownerless.+5. 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.+For update flows, call the replacement service 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@@ -132,7 +145,7 @@ The suffixes are `#{target_class.acl_target_key}_user_will_lose_permission` andThe service evaluates only the proposed ACL. It does not load the target or compare the proposal with persisted ACL rows. `target_id` only selects edit wording when present; omitting it selects creation wording. Treat “loss” as an inference that the authorized editor already holds the configured permission.-This endpoint evaluates the proposed ACL for confirmation UX; it does not authorize access to the target or replace enforcement in the actual write service. Browser confirmation is not passed as proof to `AccessControlListManager`, so an API client can bypass the prompt. If confirmation must be server-enforced, extend the write contract and re-evaluate there before mutation.+This endpoint evaluates the proposed ACL for confirmation UX; it does not authorize access to the target or replace enforcement in the actual write service. Browser confirmation is not passed as proof to `AccessControlList::Apply`, so an API client can bypass the prompt. If confirmation must be server-enforced, extend the write contract and re-evaluate there before mutation.## Serializing Target ACLs@@ -152,22 +165,27 @@ endUse `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 Grantee Cleanup+When an index needs ACL grantee details for every target, flatten one relation for the whole collection and group the result before serialization. Do not query `AccessControlList` from each serializer instance.-`Group#clear_acls` and `User#clear_acls` enqueue `Jobs::CleanupAclsForDeleted` after a grantee is destroyed. The job removes the deleted group id from `allowed_group_ids` and/or the deleted user id from `allowed_user_ids`, updates `updated_at`, and deletes ACL rows only when both arrays are empty.+```ruby+owners_by_target_id =+ AccessControlList+ .with_permission(targets, Acl::Permissions::OWNER)+ .flattened_list+ .group_by { |entry| entry[:target_id] }-## Migrations+serialize_data(targets, TargetSerializer, owners_by_target_id:)+```++`flattened_list` batch-loads the referenced users and groups. Pass the grouped entries through serializer options so adding targets does not add ACL or grantee queries.-When migrating legacy permission columns into ACLs:+## Deleted Grantee Cleanup-- 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.+`Group#clear_acls` and `User#clear_acls` enqueue `Jobs::CleanupAclsForDeleted` after a grantee is destroyed. The job removes the deleted group id from `allowed_group_ids` and/or the deleted user id from `allowed_user_ids`, updates `updated_at`, and deletes ACL rows only when both arrays are empty.## Current Limitations- `AccessControlList.expand_list_for_bulk_insert`, `flattened_list`, `preload_allowed`, lookup objects, matching scopes, and cleanup jobs now handle both group and user ACL rows.-- `DAccessControl` supports user/group search and user grants. Mandatory ACL injection remains group-first; targets with mandatory user grants need explicit UI support.+- `DAccessControl` supports user/group search and user grants. Persisted owner rows render after mandatory rows without a mandatory badge, with the Owner control disabled unless the actor can manage owners. Class-level mandatory ACL injection remains group-first; targets with other mandatory user grants need explicit UI support.- `flattened_list` skips missing groups, missing users, and unknown target classes defensively. Validate group and user 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.+- Ordinary permission authorization remains at the caller boundary; the replacement service authorizes ownership changes itself. 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.mdindex 487d6365037..e8f70ec1478 100644--- a/.skills/discourse-acl-authoring/references/testing-and-review.md+++ b/.skills/discourse-acl-authoring/references/testing-and-review.md@@ -17,10 +17,12 @@ For `AccessControlList::EvaluateModification`:- Unknown target types fail model lookup.- Requests with a target id use edit wording, while requests without one use creation wording.+- Creation evaluations include the current user's prospective owner grant, including when the submitted ACL is empty.- Mandatory ACL entries are included before evaluating the current user's proposed access.- Direct user and group grants applying to the current user are recognized.- Losing all access fails `user_will_have_permission`.- Losing any configured `loss_warning_permissions` value fails `user_will_not_lose_permission`.+- An owner grant satisfies every configured `loss_warning_permissions` value.- Targets without loss warning permissions can proceed while the current user retains some access.For Guardian methods:@@ -29,18 +31,23 @@ For Guardian methods:- 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`:+For services using `AccessControlList::Apply`:- A missing `ACL_PERMISSIONS` declaration raises `NameError`; inherited declarations are accepted.- Supported permission IDs succeed. Unknown, blank, or missing IDs fail `has_valid_permissions`, including invalid injected mandatory entries, before any ACL rows are destroyed or inserted.- Create/update request specs submit an explicit invalid permission such as `bogus` and assert rejection without partial resource creation or loss of existing ACLs. Test the write endpoints: `/access-control/evaluate.json` previews permission loss and does not enforce the manager's permission vocabulary.- Creation with omitted `acl` persists mandatory ACLs.+- Creation requires an authoritative `initial_owner_user_id`, resolves the user inside the service, and persists it with the reserved `owner` permission.+- System-user ownership is accepted for initial and replacement owner sets, including round trips from existing targets; other non-positive IDs remain invalid and every requested owner must still exist.+- Replacement preserves existing owners when `owner_user_ids` is omitted. A supplied set replaces ownership only when the actor is a currently stored owner or admin, may include only existing users, and must retain at least one owner. The actor need not remain in the requested set. On an ownerless target, only an admin may supply `owner_user_ids`; `initial_owner_user_id` itself may identify any valid user.+- Owners may remove themselves when another owner remains; evaluation still warns when doing so removes their final effective permission.+- Owner user ids are removed from lower direct grants to avoid duplicate grantee rows.- Creation with `acl: []` persists mandatory ACLs or fails closed when no mandatory ACL exists.- Update with explicit `acl: []` replaces existing ACLs with mandatory ACLs.- Submitted ACLs that match the target class's `banned_acl` fail the `has_no_banned_acl` policy.- 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.+- After a successful replacement, the target instance has been reloaded and should not retain a stale `permission_acl` cache.+- Unauthorized actors fail before the service mutates ACL rows.- Invalid group IDs fail at the service/contract boundary when user input can supply IDs.For cleanup behavior:@@ -59,13 +66,7 @@ For lookup objects:- `Acl::Target#group_ids_with_any_permission` replaces the older `multi_permission_group_ids` name.- `Acl::Target#permission_user_ids` and `#user_ids_with_any_permission` return `[]` for missing permissions and defensive array copies for present permissions.- `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.+- User owner grants satisfy all target permission checks and target-id queries; group permission checks remain exact.## Frontend Specs@@ -74,6 +75,9 @@ For `DAccessControl` consumers:- Rendered permissions match target-specific labels/descriptions.- Every option added by `transformPermissionOptions(options)` has an ID in the target's server-side `ACL_PERMISSIONS.values`; the UI-only remove action is not a permission declaration.- Mandatory ACL from `site.access_control.mandatory_acl[targetKey]` appears and is locked.+- Persisted owner rows appear after mandatory rows with the user identity and Owner label, but no Mandatory badge. The control is disabled without `@canManageOwners`; authorized rows offer only Owner and Remove.+- Authorized user rows offer Owner, while group rows never do.+- New targets do not offer Owner for ordinary user rows.- Banned ACL from `site.access_control.banned_acl[targetKey]` removes matching permission options for the matching grantee.- Existing rows with the same group as a mandatory row are not duplicated.- `onChange` writes updated ACL arrays into parent state.@@ -94,9 +98,11 @@ Use `.skills/discourse-writing-js-tests` for QUnit patterns.Ask these questions during code review:-- Is every ACL write routed through `AccessControlListManager`?+- Is every ACL write routed through `AccessControlList::Apply`?+- Does target creation pass an authoritative user owner separately from editable ACL params?+- Are persisted owners protected from normal replacement, and does owner imply all other user permission checks and scopes?- Does the target define or inherit `ACL_PERMISSIONS`, and do frontend permission option IDs match it?-- Does the caller authorize the actor before the manager can replace ACL rows?+- Does the caller authorize the actor before the service 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?- Are banned ACLs enforced in backend writes and filtered from the frontend for matching grantees?@@ -105,6 +111,7 @@ Ask these questions during code review:- Does a FormKit ACL editor use `DAccessControlField` or deliberately document why its validation flow differs?- 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?+- Do ACL-restricted realtime broadcasts include direct user grants and owners as well as group grants? For bulk publishers, are both audience types loaded in batches?- Are group and user 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?@@ -112,12 +119,11 @@ Ask these questions during code review:## Known Sharp Edges-- `AccessControlListManager` currently assumes caller-side authorization.-- Backend storage/lookups and the frontend search picker support user grants; mandatory user ACL display still needs explicit UI support.+- `AccessControlList::Apply` expects caller-side authorization for ordinary permission changes and enforces owner-change authorization itself.+- Backend storage/lookups and the frontend search picker support user grants. Persisted owner rows are handled explicitly, but other mandatory user ACL display still needs explicit UI support.- `DAccessControl` injects mandatory rows for display but does not notify the parent on render.-- `DAccessControl` filters banned permission options for UX, but hidden options are not authorization. The manager policy is the enforcement point.+- `DAccessControl` filters banned permission options for UX, but hidden options are not authorization. The replacement service policy is the enforcement point.- `DAccessControlField` cancellation leaves the proposed ACL in draft state. `preventSubmit` is not a rollback API.- `DAccessControlField` uses `@aclTarget.type` for class lookup and frontend metadata lookup, while site metadata is keyed by `acl_target_key`. A custom key cannot currently satisfy both paths.- Loss confirmation is browser UX, not write-path proof. API clients can bypass it unless the write service has a separate confirmation contract.-- Mandatory ACLs from site settings need extra care in migrations because raw stored settings may omit `mandatory_values`.- `flattened_list` skips stale group IDs, stale user 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/models/access_control_list.rb b/app/models/access_control_list.rbindex e4c84cfab7b..7008eca7853 100644--- a/app/models/access_control_list.rb+++ b/app/models/access_control_list.rb@@ -1,6 +1,9 @@# frozen_string_literal: trueclass AccessControlList < ActiveRecord::Base+ self.ignored_columns += %i[owner]+ # TODO(04-2027): Remove with the owner column.+attr_accessor :allowed_groups_preloaded, :allowed_users_preloaded# NOTE: permission column is freeform, but some common@@ -11,7 +14,7 @@ class AccessControlList < ActiveRecord::Base# - view# - edit# - manage- # - own+ # - owner## For categories for example we may have:#@@ -27,7 +30,7 @@ class AccessControlList < ActiveRecord::Basevalidates :target_id, uniqueness: { scope: %i[target_type permission] }- before_create { self.owner = "core" if owner.blank? }+ before_create { self.source = "core" if source.blank? }def allowed_users@allowed_users ||= User.where(id: allowed_user_ids).to_a@@ -128,9 +131,9 @@ class AccessControlList < ActiveRecord::Base# [{ type: "group", id: 3, permission: "edit" }]## Converting it to include the allowed_group_ids, allowed_user_ids,- # owner, and so on.- def self.bulk_insert_flattened_acl!(flattened_acl, target, owner)- bulk_insert_list = expand_list_for_bulk_insert(flattened_acl, target, owner)+ # source, and so on.+ def self.bulk_insert_flattened_acl!(flattened_acl, target, source)+ bulk_insert_list = expand_list_for_bulk_insert(flattened_acl, target, source)insert_all!(bulk_insert_list)end@@ -142,11 +145,11 @@ class AccessControlList < ActiveRecord::Base# And converts into ACL records that can be inserted into the DB with# .insert_all, ending up in a format like so:#- # [{ permission: "edit", allowed_group_ids: [3], target_type: "Category", target_id: 123, owner: "core" }]+ # [{ permission: "edit", allowed_group_ids: [3], target_type: "Category", target_id: 123, source: "core" }]## The created_at and updated_at dates are automatically added# by AR when .insert_all! is used- def self.expand_list_for_bulk_insert(list, target, owner)+ def self.expand_list_for_bulk_insert(list, target, source)list = dedup_flattened_list(list)permissions_expanded =@@ -171,7 +174,7 @@ class AccessControlList < ActiveRecord::Baseallowed_group_ids: permission[:allowed_group_ids],target_type: target.class.polymorphic_name,target_id: target.id,- owner: owner,+ source: source,}endend@@ -219,7 +222,8 @@ class AccessControlList < ActiveRecord::Basedef build_acl_entry(access_control_list, target_klass, type, id, allowed_object, for_target)mandatory =- target_klass.acl_is_mandatory?({ type:, id:, permission: access_control_list.permission })+ access_control_list.permission != Acl::Permissions::OWNER &&+ target_klass.acl_is_mandatory?({ type:, id:, permission: access_control_list.permission })list_entry = {type:,@@ -363,8 +367,8 @@ end# 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+# source :string(100) not null# target_type :string(255) not null# created_at :datetime not null# updated_at :datetime not nulldiff --git a/app/models/concerns/acl_target.rb b/app/models/concerns/acl_target.rbindex c852b61f3e3..f1a41300229 100644--- a/app/models/concerns/acl_target.rb+++ b/app/models/concerns/acl_target.rb@@ -30,7 +30,10 @@ module AclTargetid:AccessControlList.matching_user(guardian.user)- .where(target_type: polymorphic_name, permission: permission)+ .where(+ target_type: polymorphic_name,+ permission: [permission, Acl::Permissions::OWNER].uniq,+ ).select(:target_id),)end@@ -41,7 +44,10 @@ module AclTargetid:AccessControlList.matching_user(guardian.user)- .where(target_type: polymorphic_name, permission: Array.wrap(permissions))+ .where(+ target_type: polymorphic_name,+ permission: (Array.wrap(permissions) + [Acl::Permissions::OWNER]).uniq,+ ).select(:target_id),)enddiff --git a/app/models/user_history.rb b/app/models/user_history.rbindex deb85169f3e..cb2f3721a70 100644--- a/app/models/user_history.rb+++ b/app/models/user_history.rb@@ -185,6 +185,8 @@ class UserHistory < ActiveRecord::Baseadmin_onboarding_dismissed: 130,removed_avatar: 131,create_group: 132,+ add_access_control_list_owner: 133,+ remove_access_control_list_owner: 134,)end@@ -321,6 +323,8 @@ class UserHistory < ActiveRecord::Baseadmin_onboarding_dismissedremoved_avatarcreate_group+ add_access_control_list_owner+ remove_access_control_list_owner]enddiff --git a/app/services/access_control_list/action/build_replacement.rb b/app/services/access_control_list/action/build_replacement.rbnew file mode 100644index 00000000000..51159630c24--- /dev/null+++ b/app/services/access_control_list/action/build_replacement.rb@@ -0,0 +1,46 @@+# frozen_string_literal: true++class AccessControlList::Action::BuildReplacement < Service::ActionBase+ Result =+ Data.define(+ :flattened_acl,+ :permissions,+ :added_owner_user_ids,+ :removed_owner_user_ids,+ :ordinary_permissions_changed,+ )++ option :acl_entries+ option :initial_owner+ option :owner_user_ids+ option :target+ option :current_acl++ def call+ current_owner_user_ids = current_acl.permission_user_ids(Acl::Permissions::OWNER)+ desired_owner_user_ids = owner_user_ids || current_owner_user_ids+ if current_owner_user_ids.empty?+ desired_owner_user_ids = desired_owner_user_ids + [initial_owner.id]+ end+ desired_owner_user_ids = desired_owner_user_ids.uniq++ owner_acl =+ desired_owner_user_ids.map do |user_id|+ { type: :user, id: user_id, permission: Acl::Permissions::OWNER }+ end+ editable_acl =+ acl_entries.reject { |acl| acl[:type] == :user && desired_owner_user_ids.include?(acl[:id]) }+ flattened_acl = AccessControlList.inject_mandatory_acl(editable_acl + owner_acl, target)+ permissions = Acl::Target.new(flattened_acl).permission_lookup++ Result.new(+ flattened_acl:,+ permissions:,+ added_owner_user_ids: desired_owner_user_ids - current_owner_user_ids,+ removed_owner_user_ids: current_owner_user_ids - desired_owner_user_ids,+ ordinary_permissions_changed:+ current_acl.permission_lookup.except(Acl::Permissions::OWNER) !=+ permissions.except(Acl::Permissions::OWNER),+ )+ end+enddiff --git a/app/services/access_control_list/apply.rb b/app/services/access_control_list/apply.rbnew file mode 100644index 00000000000..2b1f120a3ff--- /dev/null+++ b/app/services/access_control_list/apply.rb@@ -0,0 +1,190 @@+# frozen_string_literal: true++class AccessControlList::Apply+ include Service::Base++ params do+ attribute :acl_target_type, :string+ attribute :acl_target_id, :integer+ attribute :acl_entries, :array, default: -> { [] } do+ attribute :type, :symbol+ attribute :id, :integer+ attribute :permission, :string++ validates :type, inclusion: { in: %i[group user] }+ validates :id, numericality: { only_integer: true, greater_than: 0 }+ validates :permission, presence: true+ end+ attribute :source, :string+ attribute :initial_owner_user_id, :integer+ attribute :owner_user_ids, :array++ before_validation do+ if owner_user_ids+ self.owner_user_ids =+ owner_user_ids.map { |user_id| Integer(user_id, exception: false) }.uniq+ end+ end++ validates :acl_target_type, presence: true+ validates :acl_target_id, numericality: { only_integer: true, greater_than: 0 }+ validates :source, presence: true, length: { maximum: 100 }+ validate :owner_user_ids_are_valid++ private++ def owner_user_ids_are_valid+ return if owner_user_ids.nil?++ all_ids_valid =+ owner_user_ids.all? { |user_id| user_id == Discourse::SYSTEM_USER_ID || user_id&.positive? }+ return if all_ids_valid++ errors.add(:owner_user_ids, :invalid)+ end+ end++ model :acl_target+ policy :has_no_owner_entries+ policy :grantees_exist+ policy :requested_owners_exist+ model :current_acl+ model :initial_owner, optional: true+ policy :has_initial_owner+ policy :can_change_owners+ model :replacement+ policy :has_at_least_one_owner+ policy :has_valid_permissions+ policy :has_no_banned_acl++ transaction do+ step :replace_permissions+ only_if(:ordinary_permissions_changed) { step :log_permission_change }+ only_if(:owners_added) { step :log_owner_additions }+ only_if(:owners_removed) { step :log_owner_removals }+ end++ step :refresh_target_permissions++ private++ def fetch_acl_target(params:)+ target_class =+ Site.access_control_target_classes.find { |klass| klass.name == params.acl_target_type }+ target_class&.find_by(id: params.acl_target_id)+ end++ def fetch_current_acl(acl_target:)+ AccessControlList.where(target: acl_target).target_acl(acl_target)+ end++ def fetch_initial_owner(params:, current_acl:)+ if current_acl.permission_user_ids(Acl::Permissions::OWNER).empty?+ User.find_by(id: params.initial_owner_user_id)+ end+ end++ def has_initial_owner(current_acl:, initial_owner:)+ current_acl.permission_user_ids(Acl::Permissions::OWNER).any? || initial_owner.present?+ end++ def has_no_owner_entries(params:)+ params.acl_entries.none? { |entry| entry.permission == Acl::Permissions::OWNER }+ end++ def requested_owners_exist(params:)+ return true if params.owner_user_ids.nil?++ User.where(id: params.owner_user_ids).count == params.owner_user_ids.length+ end++ def grantees_exist(params:)+ group_ids = params.acl_entries.filter_map { |entry| entry.id if entry.type == :group }.uniq+ user_ids = params.acl_entries.filter_map { |entry| entry.id if entry.type == :user }.uniq++ Group.where(id: group_ids).count == group_ids.length &&+ User.where(id: user_ids).count == user_ids.length+ end++ def fetch_replacement(params:, acl_target:, current_acl:, initial_owner:)+ AccessControlList::Action::BuildReplacement.call(+ acl_entries:+ params.acl_entries.map do |entry|+ { type: entry.type, id: entry.id, permission: entry.permission }+ end,+ initial_owner:,+ owner_user_ids: params.owner_user_ids,+ target: acl_target,+ current_acl:,+ )+ end++ def can_change_owners(params:, guardian:, current_acl:)+ return true if params.owner_user_ids.nil?++ guardian.is_admin? ||+ current_acl.permission_user_ids(Acl::Permissions::OWNER).include?(guardian.user&.id)+ end++ def has_at_least_one_owner(replacement:)+ replacement.permissions.dig(Acl::Permissions::OWNER, :user_ids)&.any?+ end++ def has_valid_permissions(acl_target:, replacement:)+ valid_permissions = acl_target.class.const_get(:ACL_PERMISSIONS).values+ replacement.flattened_acl.all? { |entry| valid_permissions.include?(entry[:permission].to_s) }+ end++ def has_no_banned_acl(acl_target:, replacement:)+ return true if !acl_target.class.has_banned_acl?++ replacement.flattened_acl.none? { |entry| acl_target.class.acl_is_banned?(entry) }+ end++ def replace_permissions(params:, acl_target:, replacement:)+ AccessControlList.where(target: acl_target).destroy_all+ AccessControlList.bulk_insert_flattened_acl!(+ replacement.flattened_acl,+ acl_target,+ params.source,+ )+ end++ def ordinary_permissions_changed(replacement:)+ replacement.ordinary_permissions_changed+ end++ def owners_added(replacement:)+ replacement.added_owner_user_ids.any?+ end++ def owners_removed(replacement:)+ replacement.removed_owner_user_ids.any?+ end++ def log_permission_change(guardian:, acl_target:, current_acl:, replacement:)+ StaffActionLogger.new(guardian.user).log_access_control_list_permission_change(+ acl_target,+ current_acl.permission_lookup.except(Acl::Permissions::OWNER),+ replacement.permissions.except(Acl::Permissions::OWNER),+ )+ end++ def log_owner_additions(guardian:, acl_target:, replacement:)+ logger = StaffActionLogger.new(guardian.user)+ User+ .where(id: replacement.added_owner_user_ids)+ .find_each { |user| logger.log_add_access_control_list_owner(acl_target, user) }+ end++ def log_owner_removals(guardian:, acl_target:, replacement:)+ logger = StaffActionLogger.new(guardian.user)+ User+ .where(id: replacement.removed_owner_user_ids)+ .find_each { |user| logger.log_remove_access_control_list_owner(acl_target, user) }+ end++ def refresh_target_permissions(acl_target:)+ acl_target.reload+ end+enddiff --git a/app/services/access_control_list/evaluate_modification.rb b/app/services/access_control_list/evaluate_modification.rbindex fa17e1ba096..59ab7871674 100644--- a/app/services/access_control_list/evaluate_modification.rb+++ b/app/services/access_control_list/evaluate_modification.rb@@ -27,21 +27,29 @@ class AccessControlList::EvaluateModificationAccessControlList.inject_mandatory_acl(params.new_acl, params.target_type)end- def fetch_acl_user_will_have(guardian:, new_acl_with_mandatory:)- new_acl_with_mandatory.select do |acl|- if acl[:type].to_s == "group"- guardian.user.in_any_groups?([acl[:id]])- else- acl[:id] == guardian.user.id+ def fetch_acl_user_will_have(guardian:, new_acl_with_mandatory:, params:)+ acl_user_will_have =+ new_acl_with_mandatory.select do |acl|+ if acl[:type].to_s == "group"+ guardian.user.in_any_groups?([acl[:id]])+ else+ acl[:id] == guardian.user.id+ endend++ if params.target_id.blank?+ acl_user_will_have << AccessControlList.flat_acl_for(guardian.user, Acl::Permissions::OWNER)end++ acl_user_will_haveenddef user_will_not_lose_permission(target_type_klass:, acl_user_will_have:)return true if !target_type_klass.has_loss_warning_permissions?- (- target_type_klass.loss_warning_permissions - acl_user_will_have.map { |acl| acl[:permission] }- ).empty?+ permissions = acl_user_will_have.map { |acl| acl[:permission].to_s }+ return true if permissions.include?(Acl::Permissions::OWNER)++ (target_type_klass.loss_warning_permissions - permissions).empty?enddef user_will_have_permission(acl_user_will_have:)diff --git a/app/services/access_control_list_manager.rb b/app/services/access_control_list_manager.rbdeleted file mode 100644index f2eaf8d4e3f..00000000000--- a/app/services/access_control_list_manager.rb+++ /dev/null@@ -1,87 +0,0 @@-# 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_valid_permissions- policy :has_no_banned_acl- 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_valid_permissions(params:, flattened_acl_with_mandatory:)- valid_permissions = params.target.class.const_get(:ACL_PERMISSIONS).values- flattened_acl_with_mandatory.all? { |acl| valid_permissions.include?(acl[:permission].to_s) }- end-- def has_no_banned_acl(params:, flattened_acl_with_mandatory:)- return true if !params.target.class.has_banned_acl?- flattened_acl_with_mandatory.none? { |acl| params.target.class.acl_is_banned?(acl) }- 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_for_bulk_insert(- 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 dfdfcb9031c..6c34948176f 100644--- a/app/services/staff_action_logger.rb+++ b/app/services/staff_action_logger.rb@@ -415,6 +415,14 @@ class StaffActionLogger)end+ def log_add_access_control_list_owner(target, user, opts = {})+ log_access_control_list_owner_change(:add_access_control_list_owner, target, user, opts)+ end++ def log_remove_access_control_list_owner(target, user, opts = {})+ log_access_control_list_owner_change(:remove_access_control_list_owner, target, user, opts)+ end+def theme_json(theme)ThemeSerializer.new(theme, root: false, include_theme_field_values: true).to_jsonend@@ -1295,6 +1303,18 @@ class StaffActionLoggerprivate+ def log_access_control_list_owner_change(action, target, user, opts)+ raise Discourse::InvalidParameters.new(:user) if !user.is_a?(User)++ UserHistory.create!(+ params(opts).merge(+ action: UserHistory.actions[action],+ subject: "#{target.class.polymorphic_name} (#{target.id})",+ target_user_id: user.id,+ ),+ )+ end+def json_params(previous_value, new_value)if (previous_value && previous_value.length > UserHistory::MAX_JSON_LENGTH) ||(new_value && new_value.length > UserHistory::MAX_JSON_LENGTH)diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex e0f4d7a4104..a059ec7c1a4 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -76,6 +76,8 @@ en:manage:access_permission_editor: "Editor"access_permission_editor_description: "Can create and edit content for this entity"+ access_permission_owner: "Owner"+ access_permission_owner_description: "Owner has total control over this %{target}, and can add or remove other owners."access_permission_viewer: "Viewer"access_permission_viewer_description: "Can view content for this entity"access_permission_remove: "Remove"@@ -85,6 +87,7 @@ en:mandatory: "Mandatory"disallowed: "Disallowed"required_permission_not_added: "At least one grantee must have %{permission} permission for this %{typeName}"+ owner_required: "At least one user must remain an owner of this %{typeName}"carousel:go_to_slide: "Go to slide %{index}"previous: "Previous slide"@@ -9728,6 +9731,8 @@ en:configure_category_type: "configure category type"unconfigure_category_type: "unconfigure category type"change_access_control_list_permissions: "change access control list permissions"+ add_access_control_list_owner: "add access control list owner"+ remove_access_control_list_owner: "remove access control list owner"admin_onboarding_step_completed: "complete admin onboarding step"admin_onboarding_completed: "complete admin onboarding"admin_onboarding_dismissed: "dismiss admin onboarding"diff --git a/db/migrate/20261021063122_add_source_to_access_control_lists.rb b/db/migrate/20261021063122_add_source_to_access_control_lists.rbnew file mode 100644index 00000000000..c4f30dbf495--- /dev/null+++ b/db/migrate/20261021063122_add_source_to_access_control_lists.rb@@ -0,0 +1,12 @@+# frozen_string_literal: true+class AddSourceToAccessControlLists < ActiveRecord::Migration[8.1]+ def up+ add_column :access_control_lists, :source, :string, limit: 100+ execute "UPDATE access_control_lists SET source = owner"+ change_column_null :access_control_lists, :owner, true+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/db/post_migrate/20261021063131_finalize_access_control_list_source.rb b/db/post_migrate/20261021063131_finalize_access_control_list_source.rbnew file mode 100644index 00000000000..294f6a2f5a2--- /dev/null+++ b/db/post_migrate/20261021063131_finalize_access_control_list_source.rb@@ -0,0 +1,16 @@+# frozen_string_literal: true+class FinalizeAccessControlListSource < ActiveRecord::Migration[8.1]+ def up+ execute <<~SQL+ UPDATE access_control_lists+ SET source = COALESCE(owner, 'core')+ WHERE source IS NULL+ SQL++ change_column_null :access_control_lists, :source, false+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/db/structure.sql b/db/structure.sqlindex a159b317b9c..82316ff3fe3 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -187,12 +187,13 @@ 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,+ owner character varying(100),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+ updated_at timestamp(6) without time zone NOT NULL,+ source character varying(100) NOT NULL);@@ -26160,6 +26161,10 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groupsSET search_path TO "$user", public;INSERT INTO "schema_migrations" (version) VALUES+('20261021063131'),+('20261021063122'),+('20261021060627'),+('20261021060617'),('20261020161054'),('20261020160221'),('20261019232249'),diff --git a/frontend/discourse/app/ui-kit/d-access-control-field.gjs b/frontend/discourse/app/ui-kit/d-access-control-field.gjsindex 8b65cb91e6f..82c9024c4ba 100644--- a/frontend/discourse/app/ui-kit/d-access-control-field.gjs+++ b/frontend/discourse/app/ui-kit/d-access-control-field.gjs@@ -33,6 +33,20 @@ export default class DAccessControlField extends Component {}}+ if (+ this.args.aclTarget.id &&+ !acl.some(+ (entry) => entry.type === "user" && entry.permission === "owner"+ )+ ) {+ addError(name, {+ title: this.args.title,+ message: i18n("access_control.manage.owner_required", {+ typeName: this.args.aclTarget.name,+ }),+ });+ }+let evaluation = {};try {@@ -99,7 +113,9 @@ export default class DAccessControlField extends Component {<DAccessControl@acl={{field.value}}@aclTarget={{@aclTarget}}+ @canManageOwners={{@canManageOwners}}@groups={{this.site.groups}}+ @isNew={{@isNew}}@onChange={{or @onChange field.set}}@transformPermissionOptions={{@transformPermissionOptions}}/>diff --git a/frontend/discourse/app/ui-kit/d-access-control.gjs b/frontend/discourse/app/ui-kit/d-access-control.gjsindex 92d2828015b..0772f3d94cd 100644--- a/frontend/discourse/app/ui-kit/d-access-control.gjs+++ b/frontend/discourse/app/ui-kit/d-access-control.gjs@@ -18,6 +18,7 @@ import DAccessControlGranteeChooser, {} from "./d-access-control-grantee-chooser.gjs";const EDIT_PERMISSION = "edit";+const OWNER_PERMISSION = "owner";const READ_ONLY_PERMISSION = "view";const READ_ONLY_DEFAULT_AUTO_GROUPS = [AUTO_GROUPS.anonymous_users.id,@@ -36,6 +37,18 @@ const REMOVE_ACTION = {),};+function ownerOption(target) {+ return {+ id: OWNER_PERMISSION,+ name: i18n("access_control.manage.access_permission_owner"),+ description: target+ ? i18n("access_control.manage.access_permission_owner_description", {+ target,+ })+ : undefined,+ };+}+export function defaultPermissions() {return [{@@ -151,8 +164,6 @@ export default class DAccessControl extends Component {return resolvedAcl;}- // 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() {const mappedAcl = this.acl.map((entry) => {const hydratedEntry = this.#hydrateDisplayName({ ...entry });@@ -170,7 +181,14 @@ export default class DAccessControl extends Component {name: hydratedEntry.name,avatar_template: hydratedEntry.avatar_template,type: hydratedEntry.type,- mandatory: Boolean(hydratedEntry.mandatory),+ mandatory:+ hydratedEntry.permission !== OWNER_PERMISSION &&+ Boolean(hydratedEntry.mandatory),+ owner: hydratedEntry.permission === OWNER_PERMISSION,+ permission_menu_disabled:+ hydratedEntry.permission === OWNER_PERMISSION+ ? !this.args.canManageOwners+ : Boolean(hydratedEntry.mandatory),};});@@ -179,9 +197,13 @@ export default class DAccessControl extends Component {return a.mandatory ? -1 : 1;}+ if (a.owner !== b.owner) {+ return a.owner ? -1 : 1;+ }+const nameSort = (a.sort_name || "").localeCompare(b.sort_name || "");- if (a.mandatory && b.mandatory) {+ if ((a.mandatory && b.mandatory) || (a.owner && b.owner)) {return nameSort;}@@ -267,9 +289,10 @@ export default class DAccessControl extends Component {* Otherwise, the default permissions are used.*/buildPermissionOptions() {- const permissions =+ const permissions = (this.args.transformPermissionOptions?.(defaultPermissions()) ||- defaultPermissions();+ defaultPermissions()+ ).filter((permission) => permission.id !== OWNER_PERMISSION);return [...permissions.sort((a, b) => a.level - b.level), REMOVE_ACTION];}@@ -365,6 +388,34 @@ export default class DAccessControl extends Component {});}+ @action+ permissionOptionsFor(row) {+ const ownerOptionForTarget = ownerOption(this.args.aclTarget?.name);++ if (row.owner) {+ return this.args.canManageOwners+ ? [ownerOptionForTarget, REMOVE_ACTION]+ : [ownerOptionForTarget];+ }++ const permissionOptions = this.excludeBannedPermissions(+ this.permissionOptions,+ row+ );++ if (row.type === "user" && this.args.canManageOwners && !this.args.isNew) {+ return [+ ...permissionOptions.filter(+ (permission) => permission.id !== REMOVE_ACTION.id+ ),+ ownerOptionForTarget,+ REMOVE_ACTION,+ ];+ }++ return permissionOptions;+ }+#hydrateDisplayName(entry) {if (!isEmpty(entry.display_name)) {return entry;@@ -380,9 +431,6 @@ export default class DAccessControl extends Component {return entry;}- // 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"><DAccessControlGranteeChooser@@ -412,6 +460,7 @@ export default class DAccessControl extends Component {"d-access-control__row"(if (eq row.type "user") "--user" "--group")(if row.mandatory "--mandatory")+ (if row.owner "--owner")}}data-row-id={{row.id}}data-row-type={{row.type}}@@ -444,12 +493,9 @@ export default class DAccessControl extends Component {</span></span><DAccessControlPermissionMenu- @disabled={{row.mandatory}}+ @disabled={{row.permission_menu_disabled}}@onChange={{fn this.onRowPermissionChange row.type row.id}}- @options={{this.excludeBannedPermissions- this.permissionOptions- row- }}+ @options={{this.permissionOptionsFor row}}@value={{row.permission}}/></div>diff --git a/frontend/discourse/tests/integration/components/d-access-control-test.gjs b/frontend/discourse/tests/integration/components/d-access-control-test.gjsindex 99c9e5adc2b..6ebb5f9a734 100644--- a/frontend/discourse/tests/integration/components/d-access-control-test.gjs+++ b/frontend/discourse/tests/integration/components/d-access-control-test.gjs@@ -8,6 +8,7 @@ import { AUTO_GROUPS } from "discourse/lib/constants";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import pretender, { response } from "discourse/tests/helpers/create-pretender";import formKit from "discourse/tests/helpers/form-kit-helper";+import { logIn } from "discourse/tests/helpers/qunit-helpers";import selectKit from "discourse/tests/helpers/select-kit-helper";import DAccessControl from "discourse/ui-kit/d-access-control";import DAccessControlField from "discourse/ui-kit/d-access-control-field";@@ -699,7 +700,281 @@ module("Integration | Component | DAccessControl", function (hooks) {.isDisabled("the mandatory row's permission select is disabled");});- test("sorts rows by mandatory status, type, and name", async function (assert) {+ test("renders an owner after mandatory rows without a mandatory badge when ownership cannot be managed", async function (assert) {+ const state = controlledState([+ {+ type: "group",+ id: 999,+ permission: "view",+ display_name: "Alpha Group",+ mandatory: true,+ },+ {+ type: "user",+ id: 7,+ permission: "owner",+ username: "martin",+ name: "Martin Brennan",+ display_name: "martin",+ avatar_template: "/letter_avatar_proxy/v4/letter/m/{size}.png",+ },+ ]);++ await render(+ <template>+ <DAccessControl+ @acl={{state.acl}}+ @groups={{GROUPS}}+ @onChange={{state.onChange}}+ />+ </template>+ );++ const ownerRow =+ '.d-access-control__row[data-row-type="user"][data-row-id="7"]';+ const rows = findAll(".d-access-control__row");++ assert+ .dom(rows[0])+ .hasAttribute("data-row-id", "999", "renders the mandatory row first");+ assert+ .dom(rows[1])+ .hasAttribute(+ "data-row-id",+ "7",+ "renders the owner after mandatory rows"+ );+ assert.dom(ownerRow).hasClass("--owner", "identifies the row as the owner");+ assert+ .dom(ownerRow)+ .doesNotHaveClass(+ "--mandatory",+ "does not identify the owner as mandatory"+ );+ assert+ .dom(`${ownerRow} .d-access-control__item-name`)+ .includesText("martin", "renders the owner's identity");+ assert.dom(`${ownerRow} .avatar`).exists("renders the owner's avatar");+ assert+ .dom(`${ownerRow} .d-access-control__tooltip`)+ .doesNotExist("does not show a mandatory badge for the owner");+ assert+ .dom(`${ownerRow} .d-access-control__permission`)+ .hasText(+ i18n("access_control.manage.access_permission_owner"),+ "labels the permission as Owner"+ )+ .isDisabled("prevents changing or removing the owner");+ });++ test("offers only Owner and Remove for an owner manager", async function (assert) {+ const state = controlledState([+ {+ type: "user",+ id: 7,+ permission: "owner",+ username: "martin",+ display_name: "martin",+ },+ ]);+ const ownerRow =+ '.d-access-control__row[data-row-type="user"][data-row-id="7"]';++ await render(+ <template>+ <DAccessControl+ @acl={{state.acl}}+ @aclTarget={{aclTarget}}+ @canManageOwners={{true}}+ @groups={{GROUPS}}+ @onChange={{state.onChange}}+ />+ </template>+ );++ assert+ .dom(`${ownerRow} .d-access-control__permission`)+ .isEnabled("allows ownership management");++ await expandPermissionMenu(ownerRow);++ assert+ .dom(permissionOptionSelector("owner"))+ .exists("keeps the current Owner option");+ assert.dom(permissionOptionDescription("owner")).hasText(+ i18n("access_control.manage.access_permission_owner_description", {+ target: aclTarget.name,+ }),+ "describes the owner's control over the target"+ );+ assert+ .dom(permissionOptionSelector("remove"))+ .exists("offers the Remove action");+ assert+ .dom(permissionOptionSelector("view"))+ .doesNotExist("does not allow downgrading the owner to Viewer");+ assert+ .dom(permissionOptionSelector("edit"))+ .doesNotExist("does not allow downgrading the owner to Editor");+ });++ test("offers ownership only for user rows when ownership can be managed", async function (assert) {+ const state = controlledState([+ {+ type: "group",+ id: 999,+ permission: "view",+ display_name: "Some Group",+ },+ {+ type: "user",+ id: 7,+ permission: "edit",+ username: "martin",+ display_name: "martin",+ },+ ]);+ const groupRow =+ '.d-access-control__row[data-row-type="group"][data-row-id="999"]';+ const userRow =+ '.d-access-control__row[data-row-type="user"][data-row-id="7"]';++ await render(+ <template>+ <DAccessControl+ @acl={{state.acl}}+ @canManageOwners={{true}}+ @groups={{GROUPS}}+ @onChange={{state.onChange}}+ />+ </template>+ );++ await expandPermissionMenu(userRow);++ assert+ .dom(permissionOptionSelector("owner"))+ .exists("offers Owner for a user");++ await expandPermissionMenu(userRow);+ await expandPermissionMenu(groupRow);++ assert+ .dom(permissionOptionSelector("owner"))+ .doesNotExist("does not offer Owner for a group");+ });++ test("does not offer ownership for user rows on a new target", async function (assert) {+ const state = controlledState([+ {+ type: "user",+ id: 7,+ permission: "edit",+ username: "martin",+ display_name: "martin",+ },+ ]);+ const userRow =+ '.d-access-control__row[data-row-type="user"][data-row-id="7"]';++ await render(+ <template>+ <DAccessControl+ @acl={{state.acl}}+ @canManageOwners={{true}}+ @groups={{GROUPS}}+ @isNew={{true}}+ @onChange={{state.onChange}}+ />+ </template>+ );++ await expandPermissionMenu(userRow);++ assert+ .dom(permissionOptionSelector("owner"))+ .doesNotExist("does not offer Owner during target creation");+ });++ test("allows an owner manager to remove their own owner row", async function (assert) {+ this.currentUser = logIn(this.owner);+ const currentUserId = this.currentUser.id;+ const coOwnerId = currentUserId + 1;+ const state = controlledState([+ {+ type: "user",+ id: currentUserId,+ permission: "owner",+ username: this.currentUser.username,+ display_name: this.currentUser.username,+ },+ {+ type: "user",+ id: coOwnerId,+ permission: "owner",+ username: "co-owner",+ display_name: "co-owner",+ },+ ]);+ const currentOwnerRow = `.d-access-control__row[data-row-type="user"][data-row-id="${currentUserId}"]`;++ await render(+ <template>+ <DAccessControl+ @acl={{state.acl}}+ @canManageOwners={{true}}+ @groups={{GROUPS}}+ @onChange={{state.onChange}}+ />+ </template>+ );++ await selectPermission("remove", currentOwnerRow);++ assert.deepEqual(+ state.onChangeCalls[0].map((entry) => entry.id),+ [coOwnerId],+ "removes the current user while retaining the co-owner"+ );+ });++ test("does not offer owner as a permission for ordinary rows", async function (assert) {+ const state = controlledState([+ {+ type: "group",+ id: 999,+ permission: "view",+ display_name: "Some Group",+ },+ ]);+ const transformPermissionOptions = (permissions) => [+ ...permissions,+ {+ id: "owner",+ level: 3,+ name: "Owner",+ },+ ];++ await render(+ <template>+ <DAccessControl+ @acl={{state.acl}}+ @groups={{GROUPS}}+ @onChange={{state.onChange}}+ @transformPermissionOptions={{transformPermissionOptions}}+ />+ </template>+ );++ await expandPermissionMenu();++ assert+ .dom(permissionOptionSelector("owner"))+ .doesNotExist("keeps the reserved owner permission out of the menu");+ });++ test("sorts rows by mandatory and owner status, then type and name", async function (assert) {const state = controlledState([{type: "user",@@ -733,6 +1008,12 @@ module("Integration | Component | DAccessControl", function (hooks) {permission: "view",display_name: "Apple Group",},+ {+ type: "user",+ id: 3,+ permission: "owner",+ display_name: "Owner User",+ },]);await render(@@ -747,12 +1028,19 @@ module("Integration | Component | DAccessControl", function (hooks) {assert.deepEqual(rowNames(),- ["Alpha Group", "Zoe User", "Apple Group", "Beta Group", "Aaron User"],- "sorts mandatory rows by name, then groups by name, then users by name"+ [+ "Alpha Group",+ "Zoe User",+ "Owner User",+ "Apple Group",+ "Beta Group",+ "Aaron User",+ ],+ "sorts mandatory rows by name, then owners, groups, and users");assert.deepEqual(findAll(".d-access-control__row").map((row) => row.dataset.rowType),- ["group", "user", "group", "group", "user"],+ ["group", "user", "user", "group", "group", "user"],"keeps regular groups before regular users");});@@ -842,8 +1130,19 @@ module("Integration | Component | DAccessControlField", function (hooks) {setupRenderingTest(hooks);test("binds a named field and updates FormKit without an onChange callback", async function (assert) {+ this.currentUser = logIn(this.owner);this.site.groups = GROUPS;- this.data = { permissions: [] };+ this.data = {+ permissions: [+ {+ type: "user",+ id: this.currentUser.id,+ permission: "owner",+ username: this.currentUser.username,+ display_name: this.currentUser.username,+ },+ ],+ };this.onSubmit = sinon.spy();pretender.post("/access-control/evaluate.json", (request) => {const payload = JSON.parse(request.requestBody);@@ -853,7 +1152,7 @@ module("Integration | Component | DAccessControlField", function (hooks) {"evaluates the target class");assert.strictEqual(- payload.new_acl[0].id,+ payload.new_acl.find((entry) => entry.type === "group").id,42,"evaluates the named field value");@@ -881,7 +1180,7 @@ module("Integration | Component | DAccessControlField", function (hooks) {const data = this.onSubmit.firstCall.args[0];assert.strictEqual(- data.permissions[0].permission,+ data.permissions.find((entry) => entry.type === "group").permission,"edit","submits the updated permissions");@@ -892,6 +1191,7 @@ module("Integration | Component | DAccessControlField", function (hooks) {});test("reports confirmed access loss and allows submission", async function (assert) {+ this.currentUser = logIn(this.owner);const dialog = getOwner(this).lookup("service:dialog");sinon.stub(dialog, "confirm").resolves(true);@@ -905,7 +1205,17 @@ module("Integration | Component | DAccessControlField", function (hooks) {}));- this.data = { acl: [] };+ this.data = {+ acl: [+ {+ type: "user",+ id: this.currentUser.id,+ permission: "owner",+ username: this.currentUser.username,+ display_name: this.currentUser.username,+ },+ ],+ };this.onChange = sinon.spy();this.onSubmit = sinon.spy();this.onAccessLossConfirmed = sinon.spy();@@ -934,4 +1244,51 @@ module("Integration | Component | DAccessControlField", function (hooks) {"the confirmed warning permissions are reported");});++ test("prevents an existing target from submitting without an owner", async function (assert) {+ this.data = {+ acl: [+ {+ type: "user",+ id: 7,+ permission: "owner",+ username: "martin",+ display_name: "martin",+ },+ ],+ };+ this.onSubmit = sinon.spy();+ pretender.post("/access-control/evaluate.json", () => response({}));++ await render(+ <template>+ <Form @data={{this.data}} @onSubmit={{this.onSubmit}} as |form|>+ <DAccessControlField+ @aclTarget={{aclTarget}}+ @canManageOwners={{true}}+ @form={{form}}+ @title="Access"+ />+ <form.Submit />+ </Form>+ </template>+ );++ await selectPermission(+ "remove",+ '.d-access-control__row[data-row-type="user"][data-row-id="7"]'+ );+ await formKit().submit();++ assert+ .form()+ .field("acl")+ .hasError(+ i18n("access_control.manage.owner_required", {+ typeName: aclTarget.name,+ }),+ "explains that the final owner cannot be removed"+ );+ assert.false(this.onSubmit.called, "does not submit the ownerless ACL");+ });});diff --git a/lib/acl/permissions.rb b/lib/acl/permissions.rbindex 0960ef9f958..00a202488af 100644--- a/lib/acl/permissions.rb+++ b/lib/acl/permissions.rb@@ -2,10 +2,12 @@module Aclclass Permissions+ OWNER = "owner"+attr_reader :valuesdef initialize(*permissions)- @values = permissions.map { |permission| permission.to_s.freeze }.uniq.freeze+ @values = (permissions.map(&:to_s) + [OWNER]).map(&:freeze).uniq.freeze@values.each do |permission|if !permission.match?(/\A[a-z][a-z0-9_]*\z/) || respond_to?(permission, true)diff --git a/lib/acl/target.rb b/lib/acl/target.rbindex 1a81b319d0f..217ef243ba0 100644--- a/lib/acl/target.rb+++ b/lib/acl/target.rb@@ -51,16 +51,21 @@ module Acldef user_has_permission?(user_or_id, permission)user_permissions = @user_lookup[user_or_id.is_a?(Numeric) ? user_or_id : user_or_id&.id]- (user_permissions || []).include?(permission)+ (user_permissions || []).intersect?([permission, Acl::Permissions::OWNER])enddef user_has_any_permission?(user_or_id, permissions)user_permissions = @user_lookup[user_or_id.is_a?(Numeric) ? user_or_id : user_or_id&.id]- (user_permissions || []).any? { |permission| permissions.include?(permission) }+ (user_permissions || []).include?(Acl::Permissions::OWNER) ||+ (user_permissions || []).any? { |permission| permissions.include?(permission) }enddef permission_user_ids(permission)- ((@permission_lookup[permission] || {}).dig(:user_ids) || []).dup+ permission_user_ids = (@permission_lookup[permission] || {}).dig(:user_ids) || []+ return permission_user_ids.dup if permission == Acl::Permissions::OWNER++ owner_user_ids = (@permission_lookup[Acl::Permissions::OWNER] || {}).dig(:user_ids) || []+ (permission_user_ids + owner_user_ids).uniqenddef user_ids_with_any_permission(permissions)diff --git a/lib/acl/user.rb b/lib/acl/user.rbindex 706cbf0cbe8..39760fe88c9 100644--- a/lib/acl/user.rb+++ b/lib/acl/user.rb@@ -22,16 +22,23 @@ module Aclenddef has_target_permission?(target, permission)- @target_lookup[target_key(target)]&.include?(permission)+ target_permissions = @target_lookup[target_key(target)] || []+ target_permissions.intersect?([permission, Acl::Permissions::OWNER])enddef has_any_target_permission?(target, permissions)target_permissions = @target_lookup[target_key(target)]- (target_permissions || []).any? { |permission| permissions.include?(permission) }+ (target_permissions || []).include?(Acl::Permissions::OWNER) ||+ (target_permissions || []).any? { |permission| permissions.include?(permission) }enddef target_ids_with_permission(target_class, permission)- ((@permission_lookup[permission] || {}).dig(target_class.polymorphic_name) || []).dup+ target_ids = (@permission_lookup[permission] || {}).dig(target_class.polymorphic_name) || []+ return target_ids.dup if permission == Acl::Permissions::OWNER++ owner_target_ids =+ (@permission_lookup[Acl::Permissions::OWNER] || {}).dig(target_class.polymorphic_name) || []+ (target_ids + owner_target_ids).uniqenddef target_ids_with_any_permissions(target_class, permissions)diff --git a/lib/guardian.rb b/lib/guardian.rbindex 89c70b88c11..84e97a21944 100644--- a/lib/guardian.rb+++ b/lib/guardian.rb@@ -192,6 +192,14 @@ class Guardian@user.permission_acl.has_any_target_permission?(target, permissions)end+ def is_acl_owner?(target)+ has_acl_permission?(target, Acl::Permissions::OWNER)+ end++ def can_manage_acl_owner?(target)+ authenticated? && (is_admin? || is_acl_owner?(target))+ end+def target_ids_with_acl_permission(target_klass, permission)@user.permission_acl.target_ids_with_permission(target_klass, permission)enddiff --git a/plugins/boards/app/controllers/boards/api/boards_controller.rb b/plugins/boards/app/controllers/boards/api/boards_controller.rbindex 5f1803264b6..e3101755d6d 100644--- a/plugins/boards/app/controllers/boards/api/boards_controller.rb+++ b/plugins/boards/app/controllers/boards/api/boards_controller.rb@@ -24,7 +24,7 @@ module Boardsboards =Boards::Board- .includes(:columns, :created_by)+ .includes(:columns).with_any_acl_permissions(guardian, allowed_permissions).order(:name).to_a@@ -34,16 +34,7 @@ module Boards.pluck(:slug).to_settag_name_map = build_tag_name_map(*boards)- render json: {- boards:- serialize_data(- boards,- Boards::BoardSerializer,- root: false,- tag_name_map:,- used_slugs:,- ),- }+ render json: { boards: serialize_boards(boards, tag_name_map:, used_slugs:) }enddef available@@ -140,7 +131,9 @@ module Boardsdef createraw = board_mutation_params.to_h- Boards::CreateBoard.call(guardian:, params: raw, raw_board_params: raw) do |result|+ Boards::CreateBoard.call(+ service_params.deep_merge(params: raw, raw_board_params: raw),+ ) do |result|on_success { |board:| render json: { board: serialize_board(board) }, status: :created }on_failed_policy(:can_manage) { raise Discourse::InvalidAccess }on_failed_contract do |contract|@@ -155,9 +148,10 @@ module Boardsraw = board_mutation_params.to_h.except("columns")Boards::UpdateBoard.call(- guardian:,- params: raw.merge("id" => params[:id], "client_id" => params[:client_id]),- raw_board_params: raw,+ service_params.deep_merge(+ params: raw.merge("id" => params[:id], "client_id" => params[:client_id]),+ raw_board_params: raw,+ ),) doon_success do |board:, cards_removed_count:|response = {@@ -364,7 +358,21 @@ module Boards)end- def serialize_boards(boards, tag_name_map:)+ def serialize_boards(boards, tag_name_map:, used_slugs:)+ owners_by_board_id =+ AccessControlList+ .with_permission(boards, Acl::Permissions::OWNER)+ .flattened_list+ .group_by { |entry| entry[:target_id] }++ serialize_data(+ boards,+ Boards::BoardSerializer,+ root: false,+ tag_name_map:,+ used_slugs:,+ owners_by_board_id:,+ )enddef preload_all_assignments(cards, visible_topic_ids)diff --git a/plugins/boards/app/controllers/boards/base_controller.rb b/plugins/boards/app/controllers/boards/base_controller.rbindex 296c5025632..37fb7c8dbb5 100644--- a/plugins/boards/app/controllers/boards/base_controller.rb+++ b/plugins/boards/app/controllers/boards/base_controller.rb@@ -73,6 +73,7 @@ module Boards:card_style,:show_topic_thumbnail,acl: %i[id type permission],+ owner_user_ids: [],category_ids: [],tag_names: [],columns: %i[diff --git a/plugins/boards/app/serializers/boards/board_serializer.rb b/plugins/boards/app/serializers/boards/board_serializer.rbindex a8522b3c3f7..d76b8bd8ec4 100644--- a/plugins/boards/app/serializers/boards/board_serializer.rb+++ b/plugins/boards/app/serializers/boards/board_serializer.rb@@ -20,7 +20,8 @@ module Boards:can_unarchive,:can_write,:can_manage,- :created_by,+ :can_manage_acl_owner,+ :owners,:columns,:acl@@ -61,10 +62,26 @@ module Boardsscope.can_manage_board?(object)end- def created_by- return nil if object.created_by.blank?+ def can_manage_acl_owner+ scope.can_manage_acl_owner?(object)+ end- { username: object.created_by.username, avatar_template: object.created_by.avatar_template }+ def owners+ owner_entries =+ if @options.key?(:owners_by_board_id)+ @options[:owners_by_board_id].fetch(object.id, [])+ else+ AccessControlList.with_permission(object, Acl::Permissions::OWNER).flattened_list+ end++ owner_entries.map do |owner|+ {+ id: owner[:id],+ username: owner[:username],+ name: owner[:display_name],+ avatar_template: owner[:avatar_template],+ }+ endenddef columnsdiff --git a/plugins/boards/app/services/boards/create_board.rb b/plugins/boards/app/services/boards/create_board.rbindex fb252aa98af..6f541351832 100644--- a/plugins/boards/app/services/boards/create_board.rb+++ b/plugins/boards/app/services/boards/create_board.rb@@ -30,7 +30,7 @@ module Boardsif raw.key?("tag_names")raw["tag_ids"] = VisibleTagResolver.resolve_names!(raw.delete("tag_names"), guardian:)end- board = Board.new(raw.except("columns", "acl"))+ board = Board.new(raw.except("columns", "acl", "owner_user_ids"))board.created_by_id = guardian.user.idboard.updated_by_id = guardian.user.idboard.save!@@ -51,14 +51,15 @@ module Boardsraw = context[:raw_board_params] || {}flattened_acl = raw["acl"] || []- # TODO (martin) We need to add the current user as Owner here- # when we have the user functionality ready for ACLs- AccessControlListManager.call(+ AccessControlList::Apply.call(guardian:,params: {- target: board,- flattened_acl: flattened_acl,- owner: Boards::PLUGIN_NAME,+ acl_target_type: board.class.name,+ acl_target_id: board.id,+ acl_entries: flattened_acl,+ source: Boards::PLUGIN_NAME,+ initial_owner_user_id: guardian.user.id,+ owner_user_ids: raw["owner_user_ids"],},) do |result|on_failure dodiff --git a/plugins/boards/app/services/boards/publisher.rb b/plugins/boards/app/services/boards/publisher.rbindex d9085e18136..100aa16b2d2 100644--- a/plugins/boards/app/services/boards/publisher.rb+++ b/plugins/boards/app/services/boards/publisher.rb@@ -80,11 +80,13 @@ module Boardsendgroup_ids = board.permission_acl.group_ids_with_any_permission(%w[view edit manage])+ user_ids = board.permission_acl.user_ids_with_any_permission(%w[view edit manage])opts = {}# Anonymous viewers belong to no group, so a board readable by anonymous# users must broadcast to everyone rather than being group-restricted.- if group_ids.present? && !group_ids.include?(Group::AUTO_GROUPS[:anonymous_users])- opts[:group_ids] = group_ids+ if !group_ids.include?(Group::AUTO_GROUPS[:anonymous_users])+ opts[:group_ids] = group_ids if group_ids.present?+ opts[:user_ids] = user_ids if user_ids.present?endMessageBus.publish("#{CHANNEL_PREFIX}/#{board.id}", data, opts)diff --git a/plugins/boards/app/services/boards/topic_sync.rb b/plugins/boards/app/services/boards/topic_sync.rbindex 7d5061b0dea..6e121452613 100644--- a/plugins/boards/app/services/boards/topic_sync.rb+++ b/plugins/boards/app/services/boards/topic_sync.rb@@ -87,7 +87,7 @@ module Boardsplan:,existing_cards: snapshot[:existing_cards],max_positions: snapshot[:max_positions],- board_groups: snapshot[:board_groups],+ board_audiences: snapshot[:board_audiences],)endend@@ -101,14 +101,19 @@ module BoardsCOALESCE(ARRAY_AGG(DISTINCT acl_group_id) FILTER (WHERE acl_group_id IS NOT NULL),'{}'::bigint[]- ) AS allowed_group_ids+ ) AS allowed_group_ids,+ COALESCE(+ ARRAY_AGG(DISTINCT acl_user_id) FILTER (WHERE acl_user_id IS NOT NULL),+ '{}'::bigint[]+ ) AS allowed_user_idsFROM discourse_kanban_cards cJOIN discourse_kanban_boards b ON b.id = c.board_idLEFT JOIN access_control_lists aclON acl.target_id = b.idAND acl.target_type = 'Boards::Board'- AND acl.permission IN ('view', 'edit', 'manage')+ AND acl.permission IN ('view', 'edit', 'manage', 'owner')LEFT JOIN LATERAL UNNEST(acl.allowed_group_ids) AS acl_groups(acl_group_id) ON TRUE+ LEFT JOIN LATERAL UNNEST(acl.allowed_user_ids) AS acl_users(acl_user_id) ON TRUEWHERE c.topic_id = :topic_id AND NOT b.archivedGROUP BY c.id, c.board_idSQL@@ -116,14 +121,17 @@ module Boardsreturn if rows.empty?deleted_by_board = {}- board_groups = {}+ board_audiences = {}rows.each do |row|(deleted_by_board[row.board_id] ||= []) << row.card_id- board_groups[row.board_id] ||= row.allowed_group_ids || []+ board_audiences[row.board_id] ||= {+ group_ids: row.allowed_group_ids || [],+ user_ids: row.allowed_user_ids || [],+ }endCard.where(id: rows.map(&:card_id)).delete_all- publish_sync_changes(board_groups:, deleted_by_board:, created_cards: [])+ publish_sync_changes(board_audiences:, deleted_by_board:, created_cards: [])enddef self.fetch_sync_snapshot(topic)@@ -155,13 +163,18 @@ module BoardsCOALESCE(ARRAY_AGG(DISTINCT acl_group_id) FILTER (WHERE acl_group_id IS NOT NULL),'{}'::bigint[]- ) AS allowed_group_ids+ ) AS allowed_group_ids,+ COALESCE(+ ARRAY_AGG(DISTINCT acl_user_id) FILTER (WHERE acl_user_id IS NOT NULL),+ '{}'::bigint[]+ ) AS allowed_user_idsFROM discourse_kanban_boards bLEFT JOIN access_control_lists aclON acl.target_id = b.idAND acl.target_type = 'Boards::Board'- AND acl.permission IN ('view', 'edit', 'manage')+ AND acl.permission IN ('view', 'edit', 'manage', 'owner')LEFT JOIN LATERAL UNNEST(acl.allowed_group_ids) AS acl_groups(acl_group_id) ON TRUE+ LEFT JOIN LATERAL UNNEST(acl.allowed_user_ids) AS acl_users(acl_user_id) ON TRUEWHERE NOT b.archived AND b.id IN (SELECT board_id FROM matchingUNION ALL@@ -171,7 +184,7 @@ module Boards)SELECT 'existing'::text AS source, ec.card_id, ec.board_id, ec.column_id,NULL::bigint AS column_tag_id, NULL::bigint AS max_pos,- NULL::bigint[] AS allowed_group_ids+ NULL::bigint[] AS allowed_group_ids, NULL::bigint[] AS allowed_user_idsFROM (SELECT c.id AS card_id, c.board_id, c.column_idFROM discourse_kanban_cards c@@ -183,24 +196,24 @@ module BoardsUNION ALLSELECT 'matching'::text, NULL, m.board_id, m.column_id,m.column_tag_id, NULL,- NULL+ NULL, NULLFROM matching mUNION ALLSELECT 'max_pos'::text, NULL, NULL, mp.column_id,NULL, mp.max_pos,- NULL+ NULL, NULLFROM max_positions mpUNION ALLSELECT 'board'::text, NULL, bi.board_id, NULL,NULL, NULL,- bi.allowed_group_ids+ bi.allowed_group_ids, bi.allowed_user_idsFROM board_info biSQLexisting_cards = []matching_placements = []max_positions = {}- board_groups = {}+ board_audiences = {}DB.query(@@ -222,11 +235,14 @@ module Boardswhen "max_pos"max_positions[row.column_id] = row.max_poswhen "board"- board_groups[row.board_id] = row.allowed_group_ids || []+ board_audiences[row.board_id] = {+ group_ids: row.allowed_group_ids || [],+ user_ids: row.allowed_user_ids || [],+ }endend- { existing_cards:, matching_placements:, max_positions:, board_groups: }+ { existing_cards:, matching_placements:, max_positions:, board_audiences: }endprivate_class_method :fetch_sync_snapshot@@ -281,7 +297,7 @@ module Boardsendprivate_class_method :compute_sync_plan- def self.execute_sync_changes(topic:, plan:, existing_cards:, max_positions:, board_groups:)+ def self.execute_sync_changes(topic:, plan:, existing_cards:, max_positions:, board_audiences:)# Delete — derive board mapping from existing_cards snapshot (no extra query)deleted_by_board = {}if plan[:remove_card_ids].present?@@ -328,7 +344,7 @@ module Boardsend# Publish- publish_sync_changes(board_groups:, deleted_by_board:, created_cards:)+ publish_sync_changes(board_audiences:, deleted_by_board:, created_cards:)endprivate_class_method :execute_sync_changes@@ -355,21 +371,27 @@ module Boardsendprivate_class_method :trim_excess_cards- def self.publish_sync_changes(board_groups:, deleted_by_board:, created_cards:)- archived_ids = Board.where(id: board_groups.keys, archived: true).pluck(:id)- board_groups = board_groups.except(*archived_ids)+ def self.publish_sync_changes(board_audiences:, deleted_by_board:, created_cards:)+ archived_ids = Board.where(id: board_audiences.keys, archived: true).pluck(:id)+ board_audiences = board_audiences.except(*archived_ids)board_ids = (deleted_by_board.keys + created_cards.map(&:board_id)).uniq- board_ids.each { |board_id| publish_to_board(board_groups, board_id, type: "board_updated") }+ board_ids.each do |board_id|+ publish_to_board(board_audiences, board_id, type: "board_updated")+ endendprivate_class_method :publish_sync_changes- def self.publish_to_board(board_groups, board_id, data)- group_ids = board_groups[board_id]- return if group_ids.nil?+ def self.publish_to_board(board_audiences, board_id, data)+ audience = board_audiences[board_id]+ return if audience.nil?++ group_ids = audience[:group_ids]+ user_ids = audience[:user_ids]opts = {}- if group_ids.present? && !group_ids.include?(Group::AUTO_GROUPS[:anonymous_users])- opts[:group_ids] = group_ids+ if !group_ids.include?(Group::AUTO_GROUPS[:anonymous_users])+ opts[:group_ids] = group_ids if group_ids.present?+ opts[:user_ids] = user_ids if user_ids.present?endMessageBus.publish("#{Publisher::CHANNEL_PREFIX}/#{board_id}",diff --git a/plugins/boards/app/services/boards/update_board.rb b/plugins/boards/app/services/boards/update_board.rbindex 387d853281a..49f9f8a2979 100644--- a/plugins/boards/app/services/boards/update_board.rb+++ b/plugins/boards/app/services/boards/update_board.rb@@ -35,20 +35,31 @@ module Boardsdef update_acl(board:, guardian:)raw = context[:raw_board_params] || {}- return if !raw.key?("acl")- flattened_acl = raw["acl"]-- AccessControlListManager.call(+ return if !raw.key?("acl") && !raw.key?("owner_user_ids")+ flattened_acl =+ raw["acl"] ||+ AccessControlList+ .where(target: board)+ .flattened_list+ .reject { |entry| entry[:permission] == Acl::Permissions::OWNER }++ AccessControlList::Apply.call(guardian:,params: {- target: board,- flattened_acl: flattened_acl,- owner: Boards::PLUGIN_NAME,+ acl_target_type: board.class.name,+ acl_target_id: board.id,+ acl_entries: flattened_acl,+ source: Boards::PLUGIN_NAME,+ initial_owner_user_id: board.created_by_id,+ owner_user_ids: raw["owner_user_ids"],},) do |result|- on_success do |previous_permissions:, new_permissions:|+ on_success do |current_acl:, replacement:|context[:histories] ||= {}- context[:histories][:permissions_changed] = { previous_permissions:, new_permissions: }+ context[:histories][:permissions_changed] = {+ previous_permissions: current_acl.permission_lookup,+ new_permissions: replacement.permissions,+ }endon_failure do@@ -66,7 +77,7 @@ module Boardsif raw.key?("tag_names")raw["tag_ids"] = VisibleTagResolver.resolve_names!(raw.delete("tag_names"), guardian:)end- board.assign_attributes(raw.except("columns", "acl"))+ board.assign_attributes(raw.except("columns", "acl", "owner_user_ids"))board.updated_by_id = guardian.user.idif board.name_changed?diff --git a/plugins/boards/assets/javascripts/discourse/components/boards-access-control-field.gjs b/plugins/boards/assets/javascripts/discourse/components/boards-access-control-field.gjsindex ead777ee78a..253ed067468 100644--- a/plugins/boards/assets/javascripts/discourse/components/boards-access-control-field.gjs+++ b/plugins/boards/assets/javascripts/discourse/components/boards-access-control-field.gjs@@ -16,8 +16,10 @@ export default class BoardsAccessControlField extends Component {<template><DAccessControlField@aclTarget={{this.aclTarget}}+ @canManageOwners={{@canManageOwners}}@description={{@description}}@form={{@form}}+ @isNew={{@isNew}}@name={{@name}}@onAccessLossConfirmed={{@onAccessLossConfirmed}}@onChange={{@onChange}}diff --git a/plugins/boards/assets/javascripts/discourse/components/boards-page.gjs b/plugins/boards/assets/javascripts/discourse/components/boards-page.gjsindex 4ed670e5056..551ccf19d16 100644--- a/plugins/boards/assets/javascripts/discourse/components/boards-page.gjs+++ b/plugins/boards/assets/javascripts/discourse/components/boards-page.gjs@@ -161,13 +161,23 @@ export default class BoardsPage extends Component {</div><div class="discourse-boards-board-card__footer">- <DUserLink- class="discourse-boards-board-card__creator discourse-boards-badge"- @user={{board.created_by}}+ <div+ class="discourse-boards-board-card__owners discourse-boards-badge">- {{i18n "boards.board.created_by"}}- {{dAvatar board.created_by imageSize="micro"}}- </DUserLink>+ <span>+ {{i18n "boards.board.owners" count=board.owners.length}}+ </span>+ <span class="discourse-boards-board-card__owner-avatars">+ {{#each board.owners as |owner|}}+ <DUserLink+ class="discourse-boards-board-card__owner"+ @user={{owner}}+ >+ {{dAvatar owner imageSize="micro"}}+ </DUserLink>+ {{/each}}+ </span>+ </div><span class="discourse-boards-badge">{{i18ndiff --git a/plugins/boards/assets/javascripts/discourse/components/modal/boards-board-settings.gjs b/plugins/boards/assets/javascripts/discourse/components/modal/boards-board-settings.gjsindex 70cb6e6ad68..9e7622ad08c 100644--- a/plugins/boards/assets/javascripts/discourse/components/modal/boards-board-settings.gjs+++ b/plugins/boards/assets/javascripts/discourse/components/modal/boards-board-settings.gjs@@ -218,7 +218,20 @@ export default class BoardsBoardSettings extends Component {async _performSave(data) {try {- await this.args.model.onSave(data);+ const aclEntries = data.acl || [];+ const ownerUserIds = aclEntries+ .filter(+ (entry) => entry.type === "user" && entry.permission === "owner"+ )+ .map((entry) => entry.id);+ const acl = aclEntries.filter((entry) => entry.permission !== "owner");+ const boardData = { ...data, acl };++ if (!this.isNew && this.args.model.board.can_manage_acl_owner) {+ boardData.owner_user_ids = ownerUserIds;+ }++ await this.args.model.onSave(boardData);this.args.closeModal({ reloadAfterSave: this.reloadAfterSave });} catch (error) {popupAjaxError(error);@@ -265,8 +278,13 @@ export default class BoardsBoardSettings extends Component {<form.Section><BoardsAccessControlField@boardId={{@model.board.id}}+ @canManageOwners={{or+ this.isNew+ @model.board.can_manage_acl_owner+ }}@description={{i18n "boards.manage.board_access_description"}}@form={{form}}+ @isNew={{this.isNew}}@onAccessLossConfirmed={{this.accessLossConfirmed}}@onChange={{this.aclChanged}}@title={{i18n "boards.manage.board_access"}}diff --git a/plugins/boards/assets/javascripts/discourse/lib/fabricators.js b/plugins/boards/assets/javascripts/discourse/lib/fabricators.jsindex bf1e6daaf47..42cf45e1aa3 100644--- a/plugins/boards/assets/javascripts/discourse/lib/fabricators.js+++ b/plugins/boards/assets/javascripts/discourse/lib/fabricators.js@@ -52,6 +52,7 @@ export default class BoardsFabricators {columns: args.columns || [],can_write: args.can_write ?? true,can_manage: args.can_manage ?? true,+ owners: args.owners || [this.coreFabricators.user()],});}diff --git a/plugins/boards/assets/javascripts/discourse/models/board.js b/plugins/boards/assets/javascripts/discourse/models/board.jsindex 3068521eab6..78480f78dc8 100644--- a/plugins/boards/assets/javascripts/discourse/models/board.js+++ b/plugins/boards/assets/javascripts/discourse/models/board.js@@ -34,6 +34,7 @@ export default class Board {@tracked archived;@tracked can_archive;@tracked can_manage;+ @tracked can_manage_acl_owner;@tracked can_unarchive;@tracked can_write;@tracked card_style;@@ -42,6 +43,7 @@ export default class Board {@tracked id;@tracked name;@tracked old_slug_used;+ @tracked owners;@tracked require_confirmation;@tracked show_tags;@tracked show_topic_thumbnail;diff --git a/plugins/boards/assets/stylesheets/boards-manage.scss b/plugins/boards/assets/stylesheets/boards-manage.scssindex f3638359b06..54fceaf186a 100644--- a/plugins/boards/assets/stylesheets/boards-manage.scss+++ b/plugins/boards/assets/stylesheets/boards-manage.scss@@ -247,6 +247,21 @@padding-top: 0.5em;border-top: 1px solid var(--content-border-color);}++ &__owner-avatars {+ display: flex;+ padding-inline-start: 0.2em;+ }++ &__owner {+ display: flex;+ border-radius: 50%;+ outline: 1px solid var(--secondary);++ + .discourse-boards-board-card__owner {+ margin-inline-start: -0.2em;+ }+ }}.onebox .discourse-boards-board-card {diff --git a/plugins/boards/config/locales/client.en.yml b/plugins/boards/config/locales/client.en.ymlindex 0a5a9612bf1..135abcda858 100644--- a/plugins/boards/config/locales/client.en.yml+++ b/plugins/boards/config/locales/client.en.yml@@ -127,7 +127,9 @@ en:constraint_fix_tags: "Add a board tag"constraint_fix_confirm: "Move and update"constraint_tooltip: "Only topics with these categories and tags are allowed on this board."- created_by: "Created by"+ owners:+ one: "Owner"+ other: "Owners"show_older_cards: "Show %{count} older cards"errors:category_unavailable: "The destination category is no longer available. Update the board or column settings before creating a topic."diff --git a/plugins/boards/db/migrate/20261021060617_backfill_board_owner_acls.rb b/plugins/boards/db/migrate/20261021060617_backfill_board_owner_acls.rbnew file mode 100644index 00000000000..142bb1e54da--- /dev/null+++ b/plugins/boards/db/migrate/20261021060617_backfill_board_owner_acls.rb@@ -0,0 +1,48 @@+# frozen_string_literal: true+class BackfillBoardOwnerAcls < ActiveRecord::Migration[8.1]+ def up+ return unless Migration::Helpers.existing_site?++ insert_missing_owner_acls+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end++ private++ def insert_missing_owner_acls+ execute <<~SQL+ INSERT INTO access_control_lists (+ target_type,+ target_id,+ owner,+ permission,+ allowed_user_ids,+ allowed_group_ids,+ created_at,+ updated_at+ )+ SELECT+ 'Boards::Board',+ boards.id,+ 'boards',+ 'owner',+ ARRAY[boards.created_by_id]::bigint[],+ ARRAY[]::bigint[],+ CURRENT_TIMESTAMP,+ CURRENT_TIMESTAMP+ FROM discourse_kanban_boards AS boards+ INNER JOIN users ON users.id = boards.created_by_id+ WHERE NOT EXISTS (+ SELECT 1+ FROM access_control_lists AS owner_acl+ WHERE owner_acl.target_type = 'Boards::Board'+ AND owner_acl.target_id = boards.id+ AND owner_acl.permission = 'owner'+ )+ ON CONFLICT DO NOTHING+ SQL+ end+enddiff --git a/plugins/boards/db/post_migrate/20261021060627_finalize_board_owner_acls.rb b/plugins/boards/db/post_migrate/20261021060627_finalize_board_owner_acls.rbnew file mode 100644index 00000000000..7bf6d8021c6--- /dev/null+++ b/plugins/boards/db/post_migrate/20261021060627_finalize_board_owner_acls.rb@@ -0,0 +1,83 @@+# frozen_string_literal: true+class FinalizeBoardOwnerAcls < ActiveRecord::Migration[8.1]+ def up+ return unless Migration::Helpers.existing_site?++ insert_missing_owner_acls+ remove_redundant_owner_grants+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end++ private++ def insert_missing_owner_acls+ execute <<~SQL+ INSERT INTO access_control_lists (+ target_type,+ target_id,+ owner,+ permission,+ allowed_user_ids,+ allowed_group_ids,+ created_at,+ updated_at+ )+ SELECT+ 'Boards::Board',+ boards.id,+ 'boards',+ 'owner',+ ARRAY[boards.created_by_id]::bigint[],+ ARRAY[]::bigint[],+ CURRENT_TIMESTAMP,+ CURRENT_TIMESTAMP+ FROM discourse_kanban_boards AS boards+ INNER JOIN users ON users.id = boards.created_by_id+ WHERE NOT EXISTS (+ SELECT 1+ FROM access_control_lists AS owner_acl+ WHERE owner_acl.target_type = 'Boards::Board'+ AND owner_acl.target_id = boards.id+ AND owner_acl.permission = 'owner'+ )+ ON CONFLICT DO NOTHING+ SQL+ end++ def remove_redundant_owner_grants+ execute <<~SQL+ DELETE FROM access_control_lists AS permission_acl+ USING access_control_lists AS owner_acl+ WHERE permission_acl.target_type = 'Boards::Board'+ AND owner_acl.target_type = permission_acl.target_type+ AND owner_acl.target_id = permission_acl.target_id+ AND owner_acl.permission = 'owner'+ AND permission_acl.permission <> 'owner'+ AND permission_acl.allowed_user_ids && owner_acl.allowed_user_ids+ AND permission_acl.allowed_user_ids <@ owner_acl.allowed_user_ids+ AND cardinality(permission_acl.allowed_group_ids) = 0+ SQL++ execute <<~SQL+ UPDATE access_control_lists AS permission_acl+ SET+ allowed_user_ids = ARRAY(+ SELECT granted_user_id+ FROM unnest(permission_acl.allowed_user_ids) AS granted_users(granted_user_id)+ WHERE NOT (granted_user_id = ANY(owner_acl.allowed_user_ids))+ ORDER BY granted_user_id+ ),+ updated_at = CURRENT_TIMESTAMP+ FROM access_control_lists AS owner_acl+ WHERE permission_acl.target_type = 'Boards::Board'+ AND owner_acl.target_type = permission_acl.target_type+ AND owner_acl.target_id = permission_acl.target_id+ AND owner_acl.permission = 'owner'+ AND permission_acl.permission <> 'owner'+ AND permission_acl.allowed_user_ids && owner_acl.allowed_user_ids+ SQL+ end+enddiff --git a/plugins/boards/lib/boards/guardian_extensions.rb b/plugins/boards/lib/boards/guardian_extensions.rbindex 79bd338feac..c8f14f6440d 100644--- a/plugins/boards/lib/boards/guardian_extensions.rb+++ b/plugins/boards/lib/boards/guardian_extensions.rb@@ -11,11 +11,13 @@ module Boardsenddef can_destroy_board?(board)- !board.archived? && can_manage_boards? && has_acl_permission?(board, "manage")+ !board.archived? &&+ (is_acl_owner?(board) || (can_manage_boards? && has_acl_permission?(board, "manage")))enddef can_manage_board?(board)- !board.archived? && can_manage_boards? && has_acl_permission?(board, "manage")+ !board.archived? &&+ (is_acl_owner?(board) || (can_manage_boards? && has_acl_permission?(board, "manage")))enddef can_read_board?(board)diff --git a/plugins/boards/lib/discourse_workflows/nodes/create_board/v1.rb b/plugins/boards/lib/discourse_workflows/nodes/create_board/v1.rbindex dccd6e10c66..8a2d371a6b1 100644--- a/plugins/boards/lib/discourse_workflows/nodes/create_board/v1.rb+++ b/plugins/boards/lib/discourse_workflows/nodes/create_board/v1.rb@@ -35,7 +35,8 @@ if defined?(DiscourseWorkflows)acl_target_type: "Boards::Board",acl_target_key: Boards::Board.acl_target_key,acl_target_name: "boards.manage.board",- permissions: Boards::Board::ACL_PERMISSIONS.values,+ permissions:+ Boards::Board::ACL_PERMISSIONS.values - [Boards::Board::ACL_PERMISSIONS.owner],},},slug: {diff --git a/plugins/boards/spec/db/migrate/20260901020329_migrate_discourse_kanban_to_boards_spec.rb b/plugins/boards/spec/db/migrate/20260901020329_migrate_discourse_kanban_to_boards_spec.rbindex 8b31caa682f..3484634abb2 100644--- a/plugins/boards/spec/db/migrate/20260901020329_migrate_discourse_kanban_to_boards_spec.rb+++ b/plugins/boards/spec/db/migrate/20260901020329_migrate_discourse_kanban_to_boards_spec.rb@@ -16,6 +16,10 @@ RSpec.describe MigrateDiscourseKanbanToBoards dobefore do@original_verbose = ActiveRecord::Migration.verboseActiveRecord::Migration.verbose = false+ connection = ActiveRecord::Base.connection+ if connection.column_exists?(:access_control_lists, :source)+ connection.remove_column(:access_control_lists, :source)+ endendafter do@@ -36,13 +40,26 @@ RSpec.describe MigrateDiscourseKanbanToBoards doenddef insert_acl(target_type:, permission:, owner:)- AccessControlList.create!(+ DB.query_single(+ <<~SQL,+ INSERT INTO access_control_lists (+ target_id,+ target_type,+ permission,+ owner,+ allowed_group_ids,+ created_at,+ updated_at+ )+ VALUES (:target_id, :target_type, :permission, :owner, ARRAY[:id]::bigint[], NOW(), NOW())+ RETURNING id+ SQLtarget_id: board.id,target_type:,permission:,owner:,- allowed_group_ids: [group.id],- )+ id: group.id,+ ).firstendit "copies legacy settings on existing sites without removing or overwriting values" do@@ -96,12 +113,13 @@ RSpec.describe MigrateDiscourseKanbanToBoards do2.times { migrate }expect(- AccessControlList.where(target_id: board.id).pluck(- :target_type,- :owner,- :permission,- :allowed_group_ids,- ),+ DB+ .query(<<~SQL, target_id: board.id)+ SELECT target_type, owner, permission, allowed_group_ids+ FROM access_control_lists+ WHERE target_id = :target_id+ SQL+ .map { |acl| [acl.target_type, acl.owner, acl.permission, acl.allowed_group_ids] },).to contain_exactly(["DiscourseKanban::Board", "discourse-kanban", "view", [group.id]],["DiscourseKanban::Board", "discourse-kanban", "edit", [group.id]],@@ -119,30 +137,44 @@ RSpec.describe MigrateDiscourseKanbanToBoards do2.times { migrate }expect(- AccessControlList.where(- target_id: board.id,- target_type: "Boards::Board",- permission: "view",- ).pluck(:owner, :allowed_group_ids),+ DB.query(<<~SQL, target_id: board.id).map { |acl| [acl.owner, acl.allowed_group_ids] },+ SELECT owner, allowed_group_ids+ FROM access_control_lists+ WHERE target_id = :target_id+ AND target_type = 'Boards::Board'+ AND permission = 'view'+ SQL).to eq([["boards", [group.id]]])endit "does not overwrite an existing Boards ACL when copying a legacy row" do- legacy =+ legacy_id =insert_acl(target_type: "DiscourseKanban::Board",permission: "view",owner: "discourse-kanban",)- existing = insert_acl(target_type: "Boards::Board", permission: "view", owner: "core")+ existing_id = insert_acl(target_type: "Boards::Board", permission: "view", owner: "core")migrate- expect(legacy.reload).to have_attributes(- target_type: "DiscourseKanban::Board",- owner: "discourse-kanban",- )- expect(existing.reload).to have_attributes(target_type: "Boards::Board", owner: "core")- expect(AccessControlList.where(target_id: board.id, permission: "view").count).to eq(2)+ expect(+ DB.query_single(+ "SELECT target_type, owner FROM access_control_lists WHERE id = :id",+ id: legacy_id,+ ),+ ).to eq(%w[DiscourseKanban::Board discourse-kanban])+ expect(+ DB.query_single(+ "SELECT target_type, owner FROM access_control_lists WHERE id = :id",+ id: existing_id,+ ),+ ).to eq(%w[Boards::Board core])+ expect(+ DB.query_single(+ "SELECT COUNT(*) FROM access_control_lists WHERE target_id = :target_id AND permission = 'view'",+ target_id: board.id,+ ).first,+ ).to eq(2)endenddiff --git a/plugins/boards/spec/db/migrate/20261021060617_backfill_board_owner_acls_spec.rb b/plugins/boards/spec/db/migrate/20261021060617_backfill_board_owner_acls_spec.rbnew file mode 100644index 00000000000..71c47280270--- /dev/null+++ b/plugins/boards/spec/db/migrate/20261021060617_backfill_board_owner_acls_spec.rb@@ -0,0 +1,111 @@+# frozen_string_literal: true++require Rails.root.join("plugins/boards/db/migrate/20261021060617_backfill_board_owner_acls.rb")++RSpec.describe BackfillBoardOwnerAcls do+ subject(:migrate) { described_class.new.up }++ fab!(:creator, :user)+ fab!(:existing_owner, :user)+ fab!(:board) do+ Boards::Board.create!(+ name: "Owner migration board",+ slug: "owner-migration",+ created_by: creator,+ )+ end++ before do+ @original_verbose = ActiveRecord::Migration.verbose+ ActiveRecord::Migration.verbose = false+ connection = ActiveRecord::Base.connection+ if connection.column_exists?(:access_control_lists, :source)+ connection.remove_column(:access_control_lists, :source)+ end+ DB.exec("UPDATE schema_migration_details SET created_at = NOW() - INTERVAL '2 hours'")+ Discourse.clear_site_creation_date_cache+ end++ after do+ ActiveRecord::Migration.verbose = @original_verbose+ Discourse.clear_site_creation_date_cache+ end++ it "creates an owner ACL for the board creator idempotently" do+ DB.exec("DROP INDEX idx_on_target_type_target_id_permission_f472902150")++ 2.times { migrate }++ expect(DB.query_single(<<~SQL, target_id: board.id)).to eq(["boards", [creator.id], []])+ SELECT owner, allowed_user_ids, allowed_group_ids+ FROM access_control_lists+ WHERE target_type = 'Boards::Board'+ AND target_id = :target_id+ AND permission = 'owner'+ SQL+ end++ def insert_acl(permission:, user_ids:)+ DB.query_single(<<~SQL, target_id: board.id, permission:, user_id: user_ids.first)+ INSERT INTO access_control_lists (+ target_type,+ target_id,+ owner,+ permission,+ allowed_user_ids,+ created_at,+ updated_at+ )+ VALUES (+ 'Boards::Board',+ :target_id,+ 'boards',+ :permission,+ ARRAY[:user_id]::bigint[],+ NOW(),+ NOW()+ )+ RETURNING id+ SQL+ end++ it "preserves established ownership and the creator's legacy grant" do+ insert_acl(permission: "owner", user_ids: [existing_owner.id])+ manager_acl_id = insert_acl(permission: "manage", user_ids: [creator.id]).first+ DB.exec("DROP INDEX idx_on_target_type_target_id_permission_f472902150")++ 2.times { migrate }++ owner_acl = DB.query(<<~SQL, target_id: board.id).first+ SELECT owner, allowed_user_ids, allowed_group_ids+ FROM access_control_lists+ WHERE target_type = 'Boards::Board'+ AND target_id = :target_id+ AND permission = 'owner'+ SQL+ expect(owner_acl.owner).to eq("boards")+ expect(owner_acl.allowed_user_ids).to eq([existing_owner.id])+ expect(owner_acl.allowed_group_ids).to eq([])+ expect(+ DB.query_single(+ "SELECT allowed_user_ids FROM access_control_lists WHERE id = :id",+ id: manager_acl_id,+ ).first,+ ).to eq([creator.id])+ end++ it "does not backfill owner ACLs on a fresh install" do+ DB.exec("UPDATE schema_migration_details SET created_at = NOW()")+ Discourse.clear_site_creation_date_cache++ migrate++ expect(DB.query_single(<<~SQL, target_id: board.id).first).to eq(0)+ SELECT COUNT(*)+ FROM access_control_lists+ WHERE target_type = 'Boards::Board'+ AND target_id = :target_id+ AND permission = 'owner'+ SQL+ end+enddiff --git a/plugins/boards/spec/db/post_migrate/20261021060627_finalize_board_owner_acls_spec.rb b/plugins/boards/spec/db/post_migrate/20261021060627_finalize_board_owner_acls_spec.rbnew file mode 100644index 00000000000..d95e26c6d0a--- /dev/null+++ b/plugins/boards/spec/db/post_migrate/20261021060627_finalize_board_owner_acls_spec.rb@@ -0,0 +1,117 @@+# frozen_string_literal: true++require Rails.root.join(+ "plugins/boards/db/post_migrate/20261021060627_finalize_board_owner_acls.rb",+ )++RSpec.describe FinalizeBoardOwnerAcls do+ subject(:migrate) { described_class.new.up }++ fab!(:creator, :user)+ fab!(:existing_owner, :user)+ fab!(:member, :user)+ fab!(:group)+ fab!(:board) do+ Boards::Board.create!(+ name: "Owner migration board",+ slug: "owner-migration",+ created_by: creator,+ )+ end++ before do+ @original_verbose = ActiveRecord::Migration.verbose+ ActiveRecord::Migration.verbose = false+ connection = ActiveRecord::Base.connection+ unless connection.column_exists?(:access_control_lists, :source)+ connection.add_column(:access_control_lists, :source, :string, limit: 100)+ end+ connection.change_column_null(:access_control_lists, :source, true)+ connection.change_column_null(:access_control_lists, :owner, true)+ DB.exec("UPDATE schema_migration_details SET created_at = NOW() - INTERVAL '2 hours'")+ Discourse.clear_site_creation_date_cache+ end++ after do+ ActiveRecord::Migration.verbose = @original_verbose+ Discourse.clear_site_creation_date_cache+ end++ it "preserves established ownership and removes grants redundant with current owners" do+ AccessControlList.create!(+ target: board,+ source: "boards",+ permission: "owner",+ allowed_user_ids: [existing_owner.id],+ )+ AccessControlList.create!(+ target: board,+ source: "boards",+ permission: "manage",+ allowed_user_ids: [creator.id, existing_owner.id],+ )+ edit_acl =+ AccessControlList.create!(+ target: board,+ source: "boards",+ permission: "edit",+ allowed_user_ids: [creator.id, existing_owner.id, member.id],+ )+ view_acl =+ AccessControlList.create!(+ target: board,+ source: "boards",+ permission: "view",+ allowed_user_ids: [creator.id],+ allowed_group_ids: [group.id],+ )++ 2.times { migrate }++ owner_acl = AccessControlList.find_by!(target: board, permission: "owner")+ expect(owner_acl.allowed_user_ids).to eq([existing_owner.id])+ expect(AccessControlList.find_by!(target: board, permission: "manage").allowed_user_ids).to eq(+ [creator.id],+ )+ expect(edit_acl.reload.allowed_user_ids).to contain_exactly(creator.id, member.id)+ expect(view_acl.reload).to have_attributes(+ allowed_user_ids: [creator.id],+ allowed_group_ids: [group.id],+ )+ end++ it "catches boards created during rollout before cleaning up the creator's direct grants" do+ manager_acl =+ AccessControlList.create!(+ target: board,+ source: "boards",+ permission: "manage",+ allowed_user_ids: [creator.id, member.id],+ )+ DB.exec("DROP INDEX idx_on_target_type_target_id_permission_f472902150")++ migrate++ expect(AccessControlList.find_by!(target: board, permission: "owner").allowed_user_ids).to eq(+ [creator.id],+ )+ expect(manager_acl.reload.allowed_user_ids).to eq([member.id])+ end++ it "does not backfill or clean up ACLs on a fresh install" do+ manager_acl =+ AccessControlList.create!(+ target: board,+ source: "boards",+ permission: "manage",+ allowed_user_ids: [creator.id],+ )+ DB.exec("UPDATE schema_migration_details SET created_at = NOW()")+ Discourse.clear_site_creation_date_cache++ migrate++ expect(AccessControlList.where(target: board, permission: "owner")).to be_empty+ expect(manager_acl.reload.allowed_user_ids).to eq([creator.id])+ end+enddiff --git a/plugins/boards/spec/fabricators/boards_board_fabricator.rb b/plugins/boards/spec/fabricators/boards_board_fabricator.rbindex 34c46e05ed1..4fa0a87a8e2 100644--- a/plugins/boards/spec/fabricators/boards_board_fabricator.rb+++ b/plugins/boards/spec/fabricators/boards_board_fabricator.rb@@ -16,8 +16,10 @@ Fabricator(:boards_board, class_name: "Boards::Board") do.wrap(evaluator[:additional_manage_groups]).map { |group| AccessControlList.flat_acl_for(group, "manage") }+ owner_acl = AccessControlList.flat_acl_for(board.created_by, Acl::Permissions::OWNER)+AccessControlList.bulk_insert_flattened_acl!(- AccessControlList.inject_mandatory_acl(additional_manage_groups, board),+ AccessControlList.inject_mandatory_acl(additional_manage_groups + [owner_acl], board),board,Boards::PLUGIN_NAME,)diff --git a/plugins/boards/spec/lib/discourse_workflows/nodes/create_board/v1_spec.rb b/plugins/boards/spec/lib/discourse_workflows/nodes/create_board/v1_spec.rbindex b61297430cb..5a5f4654f8d 100644--- a/plugins/boards/spec/lib/discourse_workflows/nodes/create_board/v1_spec.rb+++ b/plugins/boards/spec/lib/discourse_workflows/nodes/create_board/v1_spec.rb@@ -107,6 +107,9 @@ RSpec.describe DiscourseWorkflows::Nodes::CreateBoard::V1 doboard = Boards::Board.find(output.fetch("board_id"))expect(board).to have_attributes(slug: "project-board", created_by: Discourse.system_user)+ expect(board.permission_acl.permission_user_ids(Acl::Permissions::OWNER)).to eq(+ [Discourse::SYSTEM_USER_ID],+ )expect(output).to match_node_output_schema(described_class)enddiff --git a/plugins/boards/spec/lib/guardian_extensions_spec.rb b/plugins/boards/spec/lib/guardian_extensions_spec.rbindex 643bf7b2391..7f8d41f7214 100644--- a/plugins/boards/spec/lib/guardian_extensions_spec.rb+++ b/plugins/boards/spec/lib/guardian_extensions_spec.rb@@ -131,6 +131,52 @@ RSpec.describe Boards::GuardianExtensions doendend+ describe "owner permissions" do+ fab!(:board) { Fabricate(:boards_board, created_by: creator, slug: "owned-board") }++ before { SiteSetting.boards_manage_board_allowed_groups = read_group.id.to_s }++ it "grants every permission appropriate to the board state outside the global management groups" do+ expect(+ [+ creator.guardian.can_read_board?(board),+ creator.guardian.can_write_board?(board),+ creator.guardian.can_manage_board?(board),+ creator.guardian.can_destroy_board?(board),+ creator.guardian.can_archive_board?(board),+ creator.guardian.can_unarchive_board?(board),+ ],+ ).to eq([true, true, true, true, true, false])++ board.update!(archived: true)++ expect(+ [+ creator.guardian.can_read_board?(board),+ creator.guardian.can_write_board?(board),+ creator.guardian.can_manage_board?(board),+ creator.guardian.can_destroy_board?(board),+ creator.guardian.can_archive_board?(board),+ creator.guardian.can_unarchive_board?(board),+ ],+ ).to eq([true, false, false, false, false, true])+ end++ it "keeps ordinary Manage grants behind the global management group gate" do+ AccessControlList.find_by!(target: board, permission: "manage").update!(+ allowed_group_ids: [write_group.id],+ )++ expect(writer.guardian.can_manage_board?(board)).to eq(false)+ expect(writer.guardian.can_destroy_board?(board)).to eq(false)++ SiteSetting.boards_manage_board_allowed_groups = write_group.id.to_s++ expect(writer.guardian.can_manage_board?(board)).to eq(true)+ expect(writer.guardian.can_destroy_board?(board)).to eq(true)+ end+ end+describe "archived board permissions" dofab!(:board) { Fabricate(:boards_board, slug: "archived-board", archived: true) }diff --git a/plugins/boards/spec/requests/boards/boards_controller_spec.rb b/plugins/boards/spec/requests/boards/boards_controller_spec.rbindex cf707c2467f..79f5e9c77d9 100644--- a/plugins/boards/spec/requests/boards/boards_controller_spec.rb+++ b/plugins/boards/spec/requests/boards/boards_controller_spec.rb@@ -91,6 +91,25 @@ RSpec.describe Boards::Api::BoardsController doslugs = response.parsed_body["boards"].map { |b| b["slug"] }expect(slugs).to contain_exactly("editable")end++ it "returns owners for every board with one batched ACL lookup" do+ co_owner = Fabricate(:user)+ first_board = Fabricate(:boards_board, name: "First", created_by: admin)+ second_board = Fabricate(:boards_board, name: "Second", created_by: co_owner)+ AccessControlList.find_by!(target: first_board, permission: Acl::Permissions::OWNER).update!(+ allowed_user_ids: [admin.id, co_owner.id],+ )++ sign_in(admin)+ queries = track_sql_queries { get "/boards/api/boards.json" }++ boards = response.parsed_body["boards"].index_by { |board| board["id"] }+ expect(boards[first_board.id]["owners"].pluck("id")).to contain_exactly(admin.id, co_owner.id)+ expect(boards[second_board.id]["owners"].pluck("id")).to contain_exactly(co_owner.id)++ owner_acl_queries = queries.grep(/FROM "access_control_lists".*"target_id" IN .*"permission"/)+ expect(owner_acl_queries.size).to eq(1)+ endenddescribe "GET /boards/api/boards/available" do@@ -394,7 +413,7 @@ RSpec.describe Boards::Api::BoardsController doexpect(response.parsed_body["board"]["can_manage"]).to eq(false)end- it "includes the creator's username and avatar_template" do+ it "includes the owners' usernames and avatar templates" doboard =Fabricate(:boards_board, name: "Creator Test", slug: "creator-test", created_by: admin)board.columns.create!(title: "Col", position: 0)@@ -403,10 +422,9 @@ RSpec.describe Boards::Api::BoardsController doget "/boards/api/boards/#{board.id}.json"expect(response.status).to eq(200)- created_by = response.parsed_body["board"]["created_by"]- expect(created_by).to be_present- expect(created_by["username"]).to eq(admin.username)- expect(created_by["avatar_template"]).to eq(admin.avatar_template)+ owners = response.parsed_body["board"]["owners"]+ expect(owners.sole["username"]).to eq(admin.username)+ expect(owners.sole["avatar_template"]).to eq(admin.avatar_template)endit "includes topic details for detailed cards" do@@ -608,7 +626,29 @@ RSpec.describe Boards::Api::BoardsController do["view", [read_group.id]],["edit", [write_group.id]],["manage", [manage_group.id, Group::AUTO_GROUPS[:admins]]],+ ["owner", []],)+ expect(+ AccessControlList.find_by!(target: board, permission: "owner").allowed_user_ids,+ ).to contain_exactly(manager.id)+ end++ it "rejects initial co-owner ids from a non-admin" do+ sign_in(manager)++ expect do+ post "/boards/api/boards.json",+ params: {+ board: {+ name: "Co-owned board",+ slug: "co-owned-board",+ owner_user_ids: [outsider.id],+ },+ }+ end.not_to change { Boards::Board.count }++ expect(response.status).to eq(422)+ expect(response.parsed_body["failed"]).to eq("FAILED")endit "rejects an invalid permission name without creating a board, columns, or ACLs" do@@ -640,6 +680,26 @@ RSpec.describe Boards::Api::BoardsController doexpect(response.parsed_body["failed"]).to eq("FAILED")end+ it "rejects an ACL payload that assigns ownership to another user" do+ sign_in(manager)++ expect do+ post "/boards/api/boards.json",+ params: {+ board: {+ name: "Spoofed owner",+ slug: "spoofed-owner",+ acl: [{ type: "user", id: outsider.id, permission: "owner" }],+ },+ }+ end.not_to change {+ [Boards::Board.count, AccessControlList.count, Boards::BoardHistory.count]+ }++ expect(response.status).to eq(422)+ expect(response.parsed_body["failed"]).to eq("FAILED")+ end+it "creates a board for users in the manage group" dosign_in(manager)@@ -708,7 +768,11 @@ RSpec.describe Boards::Api::BoardsController do["view", [read_group.id]],["edit", [write_group.id]],["manage", [manage_group.id, Group::AUTO_GROUPS[:admins]]],+ ["owner", []],)+ expect(+ AccessControlList.find_by!(target: acl_board, permission: "owner").allowed_user_ids,+ ).to contain_exactly(admin.id)endit "rejects an invalid permission name and preserves the board and its existing ACLs" do@@ -737,6 +801,67 @@ RSpec.describe Boards::Api::BoardsController do)end+ it "rejects an ACL payload that replaces the existing owner" do+ sign_in(manager)+ previous_acls = AccessControlList.where(target: acl_board).order(:id).map(&:attributes)++ expect do+ put "/boards/api/boards/#{acl_board.id}.json",+ params: {+ board: {+ acl: [+ { type: "group", id: manage_group.id, permission: "manage" },+ { type: "user", id: outsider.id, permission: "owner" },+ ],+ },+ }+ end.not_to change { Boards::BoardHistory.count }++ expect(response.status).to eq(422)+ expect(response.parsed_body["failed"]).to eq("FAILED")+ expect(AccessControlList.where(target: acl_board).order(:id).map(&:attributes)).to eq(+ previous_acls,+ )+ expect(acl_board.reload.created_by_id).to eq(admin.id)+ end++ it "allows an owner to remove themselves when another owner remains" do+ board = Fabricate(:boards_board, created_by: manager)+ AccessControlList.find_by!(target: board, permission: "owner").update!(+ allowed_user_ids: [manager.id, outsider.id],+ )+ sign_in(manager)++ put "/boards/api/boards/#{board.id}.json",+ params: {+ board: {+ owner_user_ids: [outsider.id],+ },+ }++ expect(response.status).to eq(200)+ expect(AccessControlList.find_by!(target: board, permission: "owner").allowed_user_ids).to eq(+ [outsider.id],+ )+ end++ it "rejects owner changes from a board manager who is not an owner" do+ sign_in(manager)+ previous_acls = AccessControlList.where(target: acl_board).order(:id).map(&:attributes)++ put "/boards/api/boards/#{acl_board.id}.json",+ params: {+ board: {+ owner_user_ids: [admin.id, outsider.id],+ },+ }++ expect(response.status).to eq(422)+ expect(AccessControlList.where(target: acl_board).order(:id).map(&:attributes)).to eq(+ previous_acls,+ )+ end+it "updates board attributes for users in the manage group" doboard =Fabricate(diff --git a/plugins/boards/spec/serializers/boards/board_serializer_spec.rb b/plugins/boards/spec/serializers/boards/board_serializer_spec.rbindex 2eadf7b9a91..7710e59a47e 100644--- a/plugins/boards/spec/serializers/boards/board_serializer_spec.rb+++ b/plugins/boards/spec/serializers/boards/board_serializer_spec.rb@@ -86,19 +86,43 @@ RSpec.describe Boards::BoardSerializer dowriter_payload =described_class.new(writable_board, root: false, scope: Guardian.new(writer)).as_json- expect(manager_payload).to include(can_manage: true)+ expect(manager_payload).to include(can_manage: true, can_manage_acl_owner: false)expect(writer_payload).to include(can_write: true, can_manage: false)end- it "serializes the creator username and avatar template" do+ it "allows owners and admins to manage owners" do+ board = Fabricate(:boards_board, created_by: writer)++ owner_payload = described_class.new(board, root: false, scope: writer.guardian).as_json+ admin_payload = described_class.new(board, root: false, scope: admin.guardian).as_json++ expect(owner_payload).to include(can_manage_acl_owner: true)+ expect(admin_payload).to include(can_manage_acl_owner: true)+ end++ it "serializes the board owners" do+ co_owner = Fabricate(:user)board = Fabricate(:boards_board, created_by: admin)+ AccessControlList.find_by!(target: board, permission: Acl::Permissions::OWNER).update!(+ allowed_user_ids: [admin.id, co_owner.id],+ )payload =described_class.new(board, root: false, scope: Guardian.new(admin), tag_name_map: {}).as_json- expect(payload[:created_by]).to eq(- username: admin.username,- avatar_template: admin.avatar_template,+ expect(payload[:owners]).to contain_exactly(+ {+ id: admin.id,+ username: admin.username,+ name: admin.display_name,+ avatar_template: admin.avatar_template,+ },+ {+ id: co_owner.id,+ username: co_owner.username,+ name: co_owner.display_name,+ avatar_template: co_owner.avatar_template,+ },)enddiff --git a/plugins/boards/spec/services/boards/create_board_spec.rb b/plugins/boards/spec/services/boards/create_board_spec.rbindex bd9cd0c553d..582e9fd1064 100644--- a/plugins/boards/spec/services/boards/create_board_spec.rb+++ b/plugins/boards/spec/services/boards/create_board_spec.rb@@ -52,6 +52,29 @@ RSpec.describe Boards::CreateBoard doexpect(manage_acl.allowed_group_ids).to contain_exactly(Group::AUTO_GROUPS[:admins])end+ it "makes the creator the board owner" do+ board = result[:board]++ owner_acl = AccessControlList.find_by!(target: board, permission: "owner")+ expect(owner_acl.allowed_user_ids).to contain_exactly(manager.id)+ expect(owner_acl.allowed_group_ids).to be_empty+ end++ context "with co-owners" do+ let(:raw) do+ {+ "name" => "Co-owned board",+ "slug" => "co-owned-board",+ "owner_user_ids" => [outsider.id],+ }+ end++ it "rejects the initial owner set from a non-admin" do+ expect { result }.not_to change { Boards::Board.count }+ expect(result).to fail_a_step(:create_acl)+ end+ end+it "creates mandatory ACLs when ACL params are empty" doraw["acl"] = []diff --git a/plugins/boards/spec/services/boards/publisher_spec.rb b/plugins/boards/spec/services/boards/publisher_spec.rbindex 690215dfafa..4ea375919e6 100644--- a/plugins/boards/spec/services/boards/publisher_spec.rb+++ b/plugins/boards/spec/services/boards/publisher_spec.rb@@ -4,6 +4,7 @@ RSpec.describe Boards::Publisher dofab!(:admin)fab!(:write_group, :group)fab!(:read_group, :group)+ fab!(:direct_user, :user)before { enable_current_plugin }@@ -11,10 +12,11 @@ RSpec.describe Boards::Publisher doboard =Boards::Board.create!(name: "Test Board", slug: "test-publisher", created_by_id: admin.id)Fabricate(- :access_control_list_with_groups,+ :access_control_list_with_users_and_groups,target: board,permission: "edit",groups: [write_group],+ users: [direct_user],)Fabricate(:access_control_list_with_groups,@@ -22,6 +24,7 @@ RSpec.describe Boards::Publisher dopermission: "view",groups: [read_group],)+ Fabricate(:access_control_list_with_users, target: board, permission: "owner", users: [admin])boardendfab!(:column) { board.columns.create!(title: "To Do", position: 0) }@@ -41,7 +44,7 @@ RSpec.describe Boards::Publisher dolet(:test_client_id) { "abc123" }describe ".publish_card_created!" do- it "publishes a card_created message with group_ids and client_id" do+ it "publishes a card_created message to group, direct user, and owner audiences" domessages =MessageBus.track_publish(channel) dodescribed_class.publish_card_created!(board, card_data, client_id: test_client_id)@@ -53,6 +56,7 @@ RSpec.describe Boards::Publisher doexpect(msg.data[:client_id]).to eq(test_client_id)expect(msg.data[:card]).to eq(card_data)expect(msg.group_ids).to contain_exactly(write_group.id, read_group.id)+ expect(msg.user_ids).to contain_exactly(direct_user.id, admin.id)endend@@ -241,14 +245,23 @@ RSpec.describe Boards::Publisher docontext "with a public board" dofab!(:public_board) do- Boards::Board.create!(- name: "Public Board",- slug: "test-publisher-public",- created_by_id: admin.id,+ board =+ Boards::Board.create!(+ name: "Public Board",+ slug: "test-publisher-public",+ created_by_id: admin.id,+ )+ Fabricate(+ :access_control_list_with_groups,+ target: board,+ permission: "view",+ groups: [Group.find(Group::AUTO_GROUPS[:anonymous_users])],)+ Fabricate(:access_control_list_with_users, target: board, permission: "owner", users: [admin])+ boardend- it "publishes without group_ids restriction" do+ it "publishes without audience restrictions when anonymous users can read" domessages =MessageBus.track_publish("/boards/#{public_board.id}") dodescribed_class.publish_board_updated!(public_board, client_id: test_client_id)@@ -256,6 +269,7 @@ RSpec.describe Boards::Publisher doexpect(messages.size).to eq(1)expect(messages.first.group_ids).to be_nil+ expect(messages.first.user_ids).to be_nilendenddiff --git a/plugins/boards/spec/services/boards/topic_sync_spec.rb b/plugins/boards/spec/services/boards/topic_sync_spec.rbindex ca8fc9a3769..72a35aa7af2 100644--- a/plugins/boards/spec/services/boards/topic_sync_spec.rb+++ b/plugins/boards/spec/services/boards/topic_sync_spec.rb@@ -8,6 +8,7 @@ RSpec.describe Boards::TopicSync dofab!(:topic) { Fabricate(:topic, category: category) }fab!(:read_group, :group)fab!(:write_group, :group)+ fab!(:co_owner, :user)before { enable_current_plugin }@@ -56,7 +57,7 @@ RSpec.describe Boards::TopicSync doexpect(card.column_changed_at).to be_presentend- it "publishes board updates for created topic cards to board ACL groups" do+ it "publishes board updates for created topic cards to board ACL groups and owners" dotagged_topic = Fabricate(:topic, tags: [tag_a])board =Boards::Board.create!(@@ -78,6 +79,12 @@ RSpec.describe Boards::TopicSync dopermission: "edit",groups: [write_group],)+ Fabricate(+ :access_control_list_with_users,+ target: board,+ permission: Acl::Permissions::OWNER,+ users: [co_owner],+ )messages =MessageBus.track_publish("/boards/#{board.id}") { described_class.sync_topic(tagged_topic) }@@ -85,6 +92,7 @@ RSpec.describe Boards::TopicSync doexpect(messages.size).to eq(1)expect(messages.first.data).to eq(type: "board_updated", client_id: nil)expect(messages.first.group_ids).to contain_exactly(read_group.id, write_group.id)+ expect(messages.first.user_ids).to contain_exactly(co_owner.id)endit "publishes board updates for created topic cards without group restrictions for anonymous board ACLs" do@@ -103,6 +111,12 @@ RSpec.describe Boards::TopicSync dopermission: "view",allowed_group_ids: [Group::AUTO_GROUPS[:anonymous_users]],)+ Fabricate(+ :access_control_list_with_users,+ target: board,+ permission: Acl::Permissions::OWNER,+ users: [co_owner],+ )messages =MessageBus.track_publish("/boards/#{board.id}") { described_class.sync_topic(tagged_topic) }@@ -110,6 +124,7 @@ RSpec.describe Boards::TopicSync doexpect(messages.size).to eq(1)expect(messages.first.data).to eq(type: "board_updated", client_id: nil)expect(messages.first.group_ids).to be_nil+ expect(messages.first.user_ids).to be_nilendit "does not match topics when board has no constraints" do@@ -299,7 +314,7 @@ RSpec.describe Boards::TopicSync doexpect { described_class.remove_topic(topic.id) }.to change { Boards::Card.count }.by(-1)end- it "publishes topic card removals to board ACL groups" do+ it "publishes topic card removals to board ACL groups and owners" doboard =Boards::Board.create!(name: "ACL Remove Board",@@ -320,6 +335,12 @@ RSpec.describe Boards::TopicSync dopermission: "view",groups: [read_group],)+ Fabricate(+ :access_control_list_with_users,+ target: board,+ permission: Acl::Permissions::OWNER,+ users: [co_owner],+ )messages =MessageBus.track_publish("/boards/#{board.id}") { described_class.remove_topic(topic.id) }@@ -327,6 +348,7 @@ RSpec.describe Boards::TopicSync doexpect(messages.size).to eq(1)expect(messages.first.data).to eq(type: "board_updated", client_id: nil)expect(messages.first.group_ids).to contain_exactly(read_group.id)+ expect(messages.first.user_ids).to contain_exactly(co_owner.id)enddescribe "multi-column card semantics" dodiff --git a/plugins/boards/spec/services/boards/update_board_spec.rb b/plugins/boards/spec/services/boards/update_board_spec.rbindex 0e0750d10af..66051d231e6 100644--- a/plugins/boards/spec/services/boards/update_board_spec.rb+++ b/plugins/boards/spec/services/boards/update_board_spec.rb@@ -20,6 +20,7 @@ RSpec.describe Boards::UpdateBoard dopermission: "manage",groups: [manage_group],)+ Fabricate(:access_control_list_with_users, target: board, permission: "owner", users: [admin])boardendfab!(:column) { board.columns.create!(title: "Col", position: 0) }@@ -84,6 +85,70 @@ RSpec.describe Boards::UpdateBoard domanage_acl = AccessControlList.find_by!(target: board, permission: "manage")expect(manage_acl.allowed_group_ids).to contain_exactly(Group::AUTO_GROUPS[:admins])+ owner_acl = AccessControlList.find_by!(target: board, permission: "owner")+ expect(owner_acl.allowed_user_ids).to contain_exactly(admin.id)+ end++ context "when an owner adds a co-owner without submitting ACL params" do+ let(:raw) { { "owner_user_ids" => [admin.id, outsider.id] } }+ let(:dependencies) { { guardian: admin.guardian } }++ it "updates owners while preserving ordinary ACLs" do+ expect(result).to run_successfully+ expect(+ AccessControlList.find_by!(target: board, permission: "owner").allowed_user_ids,+ ).to(contain_exactly(admin.id, outsider.id))+ expect(+ AccessControlList.find_by!(target: board, permission: "manage").allowed_group_ids,+ ).to(contain_exactly(manage_group.id, Group::AUTO_GROUPS[:admins]))+ end+ end++ context "when the board is owned by the system user" do+ fab!(:system_owned_board) do+ board =+ Boards::Board.create!(+ name: "System owned",+ slug: "system-owned",+ created_by_id: Discourse::SYSTEM_USER_ID,+ )+ Fabricate(+ :access_control_list_with_users,+ target: board,+ permission: Acl::Permissions::OWNER,+ users: [Discourse.system_user],+ )+ Fabricate(+ :access_control_list_with_groups,+ target: board,+ permission: "manage",+ groups: [manage_group],+ )+ board+ end++ let(:raw) do+ { "name" => "Updated system board", "owner_user_ids" => [Discourse::SYSTEM_USER_ID] }+ end+ let(:params) { raw.merge("id" => system_owned_board.id) }+ let(:dependencies) { { guardian: admin.guardian } }++ it "updates unrelated settings while preserving the system owner" do+ expect(result).to run_successfully+ expect(system_owned_board.reload.name).to eq("Updated system board")+ expect(+ AccessControlList.find_by!(+ target: system_owned_board,+ permission: Acl::Permissions::OWNER,+ ).allowed_user_ids,+ ).to eq([Discourse::SYSTEM_USER_ID])+ end+ end++ context "when a non-owner manager changes owners" do+ let(:raw) { { "owner_user_ids" => [admin.id, outsider.id] } }++ it { is_expected.to fail_a_step(:update_acl) }endit "does not delete topic cards on unconstrained boards" do@@ -181,12 +246,20 @@ RSpec.describe Boards::UpdateBoard do"group_ids" => [manage_group.id],"user_ids" => [],},+ "owner" => {+ "group_ids" => [],+ "user_ids" => [admin.id],+ },},"new_permissions" => {"manage" => {"group_ids" => [new_group.id, Group::AUTO_GROUPS[:admins]],"user_ids" => [],},+ "owner" => {+ "group_ids" => [],+ "user_ids" => [admin.id],+ },},},)diff --git a/plugins/boards/spec/system/manage_boards_spec.rb b/plugins/boards/spec/system/manage_boards_spec.rbindex b71b91103b9..96019c32027 100644--- a/plugins/boards/spec/system/manage_boards_spec.rb+++ b/plugins/boards/spec/system/manage_boards_spec.rb@@ -23,19 +23,13 @@ describe "Manage Boards Boards" docontext "when user is in the manage group" dobefore { sign_in(manager) }- it "warns the user when they create a board they will not be able to manage" do+ it "does not warn about access loss because the creator becomes the owner" doboards_page.visit_pageboards_page.click_new_boardboards_page.fill_modal_board_name("Self-lockout Board")access_control.remove_permission_row(type: "group", id: manage_group.id)boards_page.save_board_modal- expect(access_control).to have_loss_warning(- I18n.t("access_control_list.errors.Boards::Board_user_will_lose_permission_on_create"),- )-- access_control.confirm_loss_warning-expect(boards_page.board_settings_modal).to be_closedexpect(PageObjects::Components::BoardsBoard.new).to have_name("Self-lockout Board")enddiff --git a/plugins/boards/test/javascripts/components/boards-board-settings-test.gjs b/plugins/boards/test/javascripts/components/boards-board-settings-test.gjsindex 4d522217767..2255ef06a69 100644--- a/plugins/boards/test/javascripts/components/boards-board-settings-test.gjs+++ b/plugins/boards/test/javascripts/components/boards-board-settings-test.gjs@@ -1,5 +1,5 @@import { getOwner } from "@ember/owner";-import { fillIn, render } from "@ember/test-helpers";+import { click, fillIn, render } from "@ember/test-helpers";import { module, test } from "qunit";import sinon from "sinon";import { setupRenderingTest } from "discourse/tests/helpers/component-test";@@ -44,6 +44,13 @@ module(const group = this.site.groups[0];const board = this.fabricators.board();board.acl = [+ {+ type: "user",+ id: this.currentUser.id,+ permission: "owner",+ username: this.currentUser.username,+ display_name: this.currentUser.username,+ },{type: "group",id: group.id,@@ -86,6 +93,189 @@ module();});+ test("uses the board ownership capability for existing owner controls", async function (assert) {+ const board = this.fabricators.board();+ board.acl = [+ {+ type: "user",+ id: 7,+ permission: "owner",+ username: "martin",+ display_name: "martin",+ },+ ];+ board.can_manage_acl_owner = false;+ this.model = { ...this.model, board, isNew: false };++ await render(+ <template>+ <BoardsBoardSettings @inline={{true}} @model={{this.model}} />+ </template>+ );++ const ownerPermission =+ '.d-access-control__row[data-row-type="user"][data-row-id="7"] .d-access-control__permission';+ assert+ .dom(ownerPermission)+ .isDisabled("keeps owner controls disabled without the capability");++ board.can_manage_acl_owner = true;++ await render(+ <template>+ <BoardsBoardSettings @inline={{true}} @model={{this.model}} />+ </template>+ );++ assert+ .dom(ownerPermission)+ .isEnabled("enables owner controls with the capability");+ });++ test("does not offer additional owners while creating a board", async function (assert) {+ const board = this.fabricators.board();+ board.acl = [+ {+ type: "user",+ id: 7,+ permission: "edit",+ username: "martin",+ display_name: "martin",+ },+ ];+ this.model = { ...this.model, board };++ await render(+ <template>+ <BoardsBoardSettings @inline={{true}} @model={{this.model}} />+ </template>+ );++ await click(+ '.d-access-control__row[data-row-type="user"][data-row-id="7"] .d-access-control__permission'+ );++ assert+ .dom('.d-access-control__permission-option[data-permission-id="owner"]')+ .doesNotExist("does not offer Owner during board creation");+ });++ test("splits owner users from ordinary ACL entries when saving", async function (assert) {+ const group = this.site.groups[0];+ const board = this.fabricators.board();+ board.acl = [+ {+ type: "user",+ id: 7,+ permission: "owner",+ username: "martin",+ display_name: "martin",+ },+ {+ type: "group",+ id: group.id,+ permission: "manage",+ display_name: group.name,+ },+ {+ type: "user",+ id: 8,+ permission: "owner",+ username: "sam",+ display_name: "sam",+ },+ ];+ board.can_manage_acl_owner = true;+ this.model = { ...this.model, board, isNew: false };+ pretender.post("/access-control/evaluate.json", () => response({}));++ await render(+ <template>+ <BoardsBoardSettings+ @closeModal={{this.closeModal}}+ @inline={{true}}+ @model={{this.model}}+ />+ </template>+ );++ await formKit().submit();++ const savedBoard = this.model.onSave.firstCall.args[0];+ assert.deepEqual(+ savedBoard.owner_user_ids,+ [7, 8],+ "sends owner IDs through the dedicated ownership argument"+ );+ assert.deepEqual(+ savedBoard.acl,+ [+ {+ type: "group",+ id: group.id,+ permission: "manage",+ display_name: group.name,+ },+ ],+ "keeps only ordinary permissions in the ACL argument"+ );+ });++ test("does not submit an owner replacement when creating a board", async function (assert) {+ pretender.post("/access-control/evaluate.json", () => response({}));++ await render(+ <template>+ <BoardsBoardSettings+ @closeModal={{this.closeModal}}+ @inline={{true}}+ @model={{this.model}}+ />+ </template>+ );++ await fillIn(".discourse-boards-editable-title__input", "New board");+ await formKit().submit();++ assert.false(+ Object.hasOwn(this.model.onSave.firstCall.args[0], "owner_user_ids"),+ "leaves initial ownership to the create service"+ );+ });++ test("does not submit owners without the ownership capability", async function (assert) {+ const board = this.fabricators.board();+ board.acl = [+ {+ type: "user",+ id: 7,+ permission: "owner",+ username: "martin",+ display_name: "martin",+ },+ ];+ board.can_manage_acl_owner = false;+ this.model = { ...this.model, board, isNew: false };+ pretender.post("/access-control/evaluate.json", () => response({}));++ await render(+ <template>+ <BoardsBoardSettings+ @closeModal={{this.closeModal}}+ @inline={{true}}+ @model={{this.model}}+ />+ </template>+ );++ await formKit().submit();++ assert.false(+ Object.hasOwn(this.model.onSave.firstCall.args[0], "owner_user_ids"),+ "does not request an ownership change"+ );+ });+test("default ACL is created using manage board allowed groups and logged in users", async function (assert) {await render(<template>diff --git a/plugins/boards/test/javascripts/components/boards-category-loading-test.gjs b/plugins/boards/test/javascripts/components/boards-category-loading-test.gjsindex 3fb655e5bd0..f5be06f9735 100644--- a/plugins/boards/test/javascripts/components/boards-category-loading-test.gjs+++ b/plugins/boards/test/javascripts/components/boards-category-loading-test.gjs@@ -46,6 +46,15 @@ module("Integration | Component | Boards category loading", function (hooks) {this.owner.lookup("service:modal").containerElement = getRootElement();this.fabricators = new BoardsFabricators(this.owner);this.board = this.fabricators.board();+ this.board.acl = [+ {+ type: "user",+ id: this.currentUser.id,+ permission: "owner",+ username: this.currentUser.username,+ display_name: this.currentUser.username,+ },+ ];this.board.category_ids = [CATEGORY_ID];this.board.tag_names = [];this.column = this.fabricators.column();diff --git a/plugins/boards/test/javascripts/components/boards-page-test.gjs b/plugins/boards/test/javascripts/components/boards-page-test.gjsindex 8b55e4d445c..67c2c64ae9a 100644--- a/plugins/boards/test/javascripts/components/boards-page-test.gjs+++ b/plugins/boards/test/javascripts/components/boards-page-test.gjs@@ -62,4 +62,54 @@ module("Integration | Component | BoardsPage", function (hooks) {.dom(".discourse-boards-board-card__name").hasText("Past work", "the archived board is reachable");});++ test("shows board owners as pluralized avatar groups", async function (assert) {+ this.boards = [+ new BoardsFabricators(getOwner(this)).board({+ id: 1,+ name: "Personal board",+ owners: [+ {+ username: "alice",+ avatar_template:+ "/letter_avatar_proxy/v4/letter/a/13edae/{size}.png",+ },+ ],+ }),+ new BoardsFabricators(getOwner(this)).board({+ id: 2,+ name: "Shared board",+ owners: [+ {+ username: "alice",+ avatar_template:+ "/letter_avatar_proxy/v4/letter/a/13edae/{size}.png",+ },+ {+ username: "bob",+ avatar_template:+ "/letter_avatar_proxy/v4/letter/b/3be4f8/{size}.png",+ },+ ],+ }),+ ];++ await render(<template><BoardsPage @boards={{this.boards}} /></template>);++ assert+ .dom(+ ".discourse-boards-board-card:nth-child(1) .discourse-boards-board-card__owners"+ )+ .includesText("Owner", "one owner uses the singular label");+ assert+ .dom(+ ".discourse-boards-board-card:nth-child(2) .discourse-boards-board-card__owners"+ )+ .includesText("Owners", "multiple owners use the plural label");+ assert+ .dom(".discourse-boards-board-card__owner")+ .exists({ count: 3 }, "each owner has a profile link");+ assert.dom(".discourse-boards-board-card__owner[href='/u/alice']").exists();+ assert.dom(".discourse-boards-board-card__owner[href='/u/bob']").exists();+ });});diff --git a/spec/db/migrate/20261021063122_add_source_to_access_control_lists_spec.rb b/spec/db/migrate/20261021063122_add_source_to_access_control_lists_spec.rbnew file mode 100644index 00000000000..766f09de9f8--- /dev/null+++ b/spec/db/migrate/20261021063122_add_source_to_access_control_lists_spec.rb@@ -0,0 +1,49 @@+# frozen_string_literal: true++require Rails.root.join("db/migrate/20261021063122_add_source_to_access_control_lists.rb")++RSpec.describe AddSourceToAccessControlLists do+ around { |example| ActiveRecord::Migration.suppress_messages { example.run } }++ it "adds and backfills source while allowing legacy owner values to be omitted" do+ connection = ActiveRecord::Base.connection+ if connection.column_exists?(:access_control_lists, :source)+ connection.remove_column(:access_control_lists, :source)+ end+ connection.change_column_null(:access_control_lists, :owner, false)++ acl_id = DB.query_single(<<~SQL).first+ INSERT INTO access_control_lists (+ target_type,+ target_id,+ owner,+ permission,+ created_at,+ updated_at+ )+ VALUES ('Category', 1, 'test-plugin', 'view', NOW(), NOW())+ RETURNING id+ SQL++ described_class.new.up++ expect(+ DB.query_single("SELECT owner, source FROM access_control_lists WHERE id = :acl_id", acl_id:),+ ).to eq(%w[test-plugin test-plugin])+ owner_column =+ connection.columns(:access_control_lists).find { |column| column.name == "owner" }+ expect(owner_column.null).to eq(true)++ expect { DB.exec(<<~SQL) }.not_to raise_error+ INSERT INTO access_control_lists (+ target_type,+ target_id,+ source,+ permission,+ created_at,+ updated_at+ )+ VALUES ('Category', 2, 'core', 'view', NOW(), NOW())+ SQL+ end+enddiff --git a/spec/db/post_migrate/20261021063131_finalize_access_control_list_source_spec.rb b/spec/db/post_migrate/20261021063131_finalize_access_control_list_source_spec.rbnew file mode 100644index 00000000000..c398bd18007--- /dev/null+++ b/spec/db/post_migrate/20261021063131_finalize_access_control_list_source_spec.rb@@ -0,0 +1,67 @@+# frozen_string_literal: true++require Rails.root.join("db/post_migrate/20261021063131_finalize_access_control_list_source.rb")++RSpec.describe FinalizeAccessControlListSource do+ around { |example| ActiveRecord::Migration.suppress_messages { example.run } }++ it "finalizes source values without overwriting existing source values" do+ connection = ActiveRecord::Base.connection+ unless connection.column_exists?(:access_control_lists, :source)+ connection.add_column(:access_control_lists, :source, :string, limit: 100)+ end+ connection.change_column_null(:access_control_lists, :source, true)+ connection.change_column_null(:access_control_lists, :owner, true)++ legacy_acl_id = DB.query_single(<<~SQL).first+ INSERT INTO access_control_lists (+ target_type,+ target_id,+ owner,+ permission,+ created_at,+ updated_at+ )+ VALUES ('Category', 1, 'test-plugin', 'view', NOW(), NOW())+ RETURNING id+ SQL+ default_acl_id = DB.query_single(<<~SQL).first+ INSERT INTO access_control_lists (+ target_type,+ target_id,+ permission,+ created_at,+ updated_at+ )+ VALUES ('Category', 2, 'view', NOW(), NOW())+ RETURNING id+ SQL+ existing_source_acl_id = DB.query_single(<<~SQL).first+ INSERT INTO access_control_lists (+ target_type,+ target_id,+ owner,+ source,+ permission,+ created_at,+ updated_at+ )+ VALUES ('Category', 3, 'legacy-plugin', 'new-plugin', 'view', NOW(), NOW())+ RETURNING id+ SQL++ described_class.new.up++ expect(DB.query_single(<<~SQL, legacy_acl_id:, default_acl_id:, existing_source_acl_id:)).to eq(+ SELECT source+ FROM access_control_lists+ WHERE id IN (:legacy_acl_id, :default_acl_id, :existing_source_acl_id)+ ORDER BY id+ SQL+ %w[test-plugin core new-plugin],+ )+ source_column =+ connection.columns(:access_control_lists).find { |column| column.name == "source" }+ expect(source_column.null).to eq(false)+ end+enddiff --git a/spec/fabricators/access_control_list_fabricator.rb b/spec/fabricators/access_control_list_fabricator.rbindex f6ab5c12cf0..540c2d92181 100644--- a/spec/fabricators/access_control_list_fabricator.rb+++ b/spec/fabricators/access_control_list_fabricator.rb@@ -3,7 +3,7 @@Fabricator(:access_control_list) dotarget { Fabricate(:category) }permission { "view" }- owner { "core" }+ source { "core" }allowed_user_ids { [] }allowed_group_ids { [] }enddiff --git a/spec/lib/acl/permissions_spec.rb b/spec/lib/acl/permissions_spec.rbindex 641ecef86ed..af4ef8bdbf8 100644--- a/spec/lib/acl/permissions_spec.rb+++ b/spec/lib/acl/permissions_spec.rb@@ -5,7 +5,7 @@ RSpec.describe Acl::Permissions dodescribe "#values" doit "returns the permission IDs as frozen strings in a frozen array" do- expect(permissions.values).to eq(%w[view edit manage])+ expect(permissions.values).to eq(%w[view edit manage owner])expect(permissions.values).to be_frozenexpect(permissions.values).to all(be_frozen)end@@ -13,8 +13,12 @@ RSpec.describe Acl::Permissions dodescribe "named readers" doit "returns each permission ID as a frozen string" do- expect([permissions.view, permissions.edit, permissions.manage]).to eq(%w[view edit manage])- expect([permissions.view, permissions.edit, permissions.manage]).to all(be_frozen)+ expect([permissions.view, permissions.edit, permissions.manage, permissions.owner]).to eq(+ %w[view edit manage owner],+ )+ expect([permissions.view, permissions.edit, permissions.manage, permissions.owner]).to all(+ be_frozen,+ )endit "raises for an undeclared permission" dodiff --git a/spec/lib/acl/target_spec.rb b/spec/lib/acl/target_spec.rbindex 410a504be1b..a04cea9248b 100644--- a/spec/lib/acl/target_spec.rb+++ b/spec/lib/acl/target_spec.rb@@ -5,6 +5,7 @@ RSpec.describe Acl::Target dofab!(:group)fab!(:user)+ fab!(:owner, :user)let(:flattened_acl_list) do[@@ -13,6 +14,7 @@ RSpec.describe Acl::Target do{ type: "group", id: 22, permission: "view", target_type: "Category", target_id: 5 },{ type: :user, id: user.id, permission: "manage", target_type: "Category", target_id: 5 },{ type: "user", id: 99, permission: "view", target_type: "Category", target_id: 5 },+ { type: :user, id: owner.id, permission: "owner", target_type: "Category", target_id: 5 },]end@@ -106,6 +108,11 @@ RSpec.describe Acl::Target doit "does not grant user permissions from non-user entries" doexpect(target_acl.user_has_permission?(group.id, "edit")).to eq(false)end++ it "grants every permission to an owner" do+ expect(target_acl.user_has_permission?(owner, "view")).to eq(true)+ expect(target_acl.user_has_permission?(owner, "manage")).to eq(true)+ endenddescribe "#user_has_any_permission?" do@@ -120,23 +127,31 @@ RSpec.describe Acl::Target doit "returns false for a user not present in the list" doexpect(target_acl.user_has_any_permission?(123_456, %w[view manage])).to eq(false)end++ it "grants any requested permission to an owner" do+ expect(target_acl.user_has_any_permission?(owner, %w[edit manage])).to eq(true)+ endenddescribe "#permission_user_ids" doit "returns all user ids holding the permission" do- expect(target_acl.permission_user_ids("view")).to contain_exactly(99)+ expect(target_acl.permission_user_ids("view")).to contain_exactly(99, owner.id)endit "returns only the matching users for a more restrictive permission" do- expect(target_acl.permission_user_ids("manage")).to contain_exactly(user.id)+ expect(target_acl.permission_user_ids("manage")).to contain_exactly(user.id, owner.id)end- it "returns an empty array when only non-user entries hold the permission" do- expect(target_acl.permission_user_ids("edit")).to eq([])+ it "includes owners when only non-user entries hold the permission" do+ expect(target_acl.permission_user_ids("edit")).to contain_exactly(owner.id)end- it "returns an empty array for a permission that is not present" do- expect(target_acl.permission_user_ids("own")).to eq([])+ it "includes owners for a permission that is not present" do+ expect(target_acl.permission_user_ids("own")).to contain_exactly(owner.id)+ end++ it "returns only explicit owners for the owner permission" do+ expect(target_acl.permission_user_ids("owner")).to contain_exactly(owner.id)endend@@ -145,11 +160,12 @@ RSpec.describe Acl::Target doexpect(target_acl.user_ids_with_any_permission(%w[view manage])).to contain_exactly(user.id,99,+ owner.id,)endit "ignores permissions that are not present" do- expect(target_acl.user_ids_with_any_permission(%w[view own])).to contain_exactly(99)+ expect(target_acl.user_ids_with_any_permission(%w[view own])).to contain_exactly(99, owner.id)endendenddiff --git a/spec/lib/acl/user_spec.rb b/spec/lib/acl/user_spec.rbindex ba7e3ea3b25..859c0b60933 100644--- a/spec/lib/acl/user_spec.rb+++ b/spec/lib/acl/user_spec.rb@@ -7,12 +7,14 @@ RSpec.describe Acl::User dofab!(:topic)fab!(:other_topic, :topic)+ fab!(:absent_topic, :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 },+ { type: :user, id: 12, permission: "owner", target_type: "Topic", target_id: other_topic.id },]end@@ -35,7 +37,12 @@ RSpec.describe Acl::User doendit "returns nil for a target absent from the list" do- expect(user_acl.has_target_permission?(other_topic, "view")).to be_nil+ expect(user_acl.has_target_permission?(absent_topic, "view")).to eq(false)+ end++ it "grants every permission for an owned target" do+ expect(user_acl.has_target_permission?(other_topic, "view")).to eq(true)+ expect(user_acl.has_target_permission?(other_topic, "manage")).to eq(true)endend@@ -49,7 +56,11 @@ RSpec.describe Acl::User doendit "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)+ expect(user_acl.has_any_target_permission?(absent_topic, %w[view edit])).to eq(false)+ end++ it "grants any requested permission for an owned target" do+ expect(user_acl.has_any_target_permission?(other_topic, %w[edit manage])).to eq(true)endend@@ -59,7 +70,10 @@ RSpec.describe Acl::User doendit "scopes the ids to the requested target class" do- expect(user_acl.target_ids_with_permission(Topic, "view")).to contain_exactly(topic.id)+ expect(user_acl.target_ids_with_permission(Topic, "view")).to contain_exactly(+ topic.id,+ other_topic.id,+ )endit "returns an empty array when no target of that class holds the permission" do@@ -67,7 +81,11 @@ RSpec.describe Acl::User doendit "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([])+ expect(user_acl.target_ids_with_permission(Topic, "edit")).to contain_exactly(other_topic.id)+ end++ it "returns only owned targets for the owner permission" do+ expect(user_acl.target_ids_with_permission(Topic, "owner")).to contain_exactly(other_topic.id)endit "returns a defensive copy" do@@ -87,6 +105,7 @@ RSpec.describe Acl::User doit "scopes the combined ids to the requested target class" doexpect(user_acl.target_ids_with_any_permissions(Topic, %w[view edit])).to contain_exactly(topic.id,+ other_topic.id,)enddiff --git a/spec/lib/guardian_spec.rb b/spec/lib/guardian_spec.rbindex bc0bb6fa0ec..ccf74f1922c 100644--- a/spec/lib/guardian_spec.rb+++ b/spec/lib/guardian_spec.rb@@ -78,6 +78,7 @@ RSpec.describe Guardian dofab!(:acl_group) { Fabricate(:group).tap { |group| group.add(acl_user) } }fab!(:member_category, :category)fab!(:anon_category, :category)+ fab!(:owned_category, :category)fab!(:member_acl) doFabricate(:access_control_list_with_groups,@@ -94,6 +95,14 @@ RSpec.describe Guardian doallowed_group_ids: [Group::AUTO_GROUPS[:anonymous_users]],)end+ fab!(:owner_acl) do+ Fabricate(+ :access_control_list_with_users,+ target: owned_category,+ permission: "owner",+ users: [acl_user],+ )+ endbefore doCategory.stubs(:has_mandatory_acl?).returns(false)@@ -143,6 +152,25 @@ RSpec.describe Guardian doexpect(Guardian.new.has_any_acl_permission?(member_category, %w[edit view])).to eq(false)endend++ describe "#is_acl_owner?" do+ it "is true only for a directly owned target" do+ expect(acl_user.guardian.is_acl_owner?(owned_category)).to eq(true)+ expect(acl_user.guardian.is_acl_owner?(member_category)).to eq(false)+ end+ end++ describe "#can_manage_acl_owner?" do+ it "allows target owners and admins to manage ownership" do+ expect(acl_user.guardian.can_manage_acl_owner?(owned_category)).to eq(true)+ expect(Fabricate(:admin).guardian.can_manage_acl_owner?(member_category)).to eq(true)+ end++ it "rejects other users and anonymous guardians" do+ expect(acl_user.guardian.can_manage_acl_owner?(member_category)).to eq(false)+ expect(Guardian.new.can_manage_acl_owner?(owned_category)).to eq(false)+ end+ endenddescribe "can_enable_safe_mode" dodiff --git a/spec/models/access_control_list_spec.rb b/spec/models/access_control_list_spec.rbindex 768cb7b0e1c..fbdf9fd5fe8 100644--- a/spec/models/access_control_list_spec.rb+++ b/spec/models/access_control_list_spec.rb@@ -7,6 +7,12 @@ RSpec.describe AccessControlList dofab!(:user) { Fabricate(:user, name: "User One") }fab!(:other_user) { Fabricate(:user, name: "User Two") }+ it "defaults the source to core" do+ access_control_list = Fabricate(:access_control_list, source: nil, target:, permission: "view")++ expect(access_control_list.source).to eq("core")+ end+describe ".expand_list_for_bulk_insert" doit "collapses multiple groups sharing a permission into one record" dolist = [@@ -24,7 +30,7 @@ RSpec.describe AccessControlList doallowed_user_ids: [],target_type: "Category",target_id: target.id,- owner: "core",+ source: "core",)end@@ -42,13 +48,13 @@ RSpec.describe AccessControlList do)end- it "accepts a symbol type and a custom owner" do+ it "accepts a symbol type and a custom source" dolist = [{ type: :group, id: group.id, permission: "view" }]result = described_class.expand_list_for_bulk_insert(list, target, "chat")expect(result.first[:allowed_group_ids]).to contain_exactly(group.id)- expect(result.first[:owner]).to eq("chat")+ expect(result.first[:source]).to eq("chat")endit "collapses users and groups sharing a permission into one record" do@@ -67,7 +73,7 @@ RSpec.describe AccessControlList doallowed_user_ids: contain_exactly(user.id, other_user.id),target_type: "Category",target_id: target.id,- owner: "core",+ source: "core",},)end@@ -229,6 +235,24 @@ RSpec.describe AccessControlList do)end+ it "does not mark owner entries as mandatory" do+ Fabricate(:access_control_list_with_users, target: target, permission: "owner", users: [user])+ target+ .class+ .stubs(:acl_is_mandatory?)+ .with({ type: :user, id: user.id, permission: "owner" })+ .returns(true)++ owner_entry = described_class.where(target: target, permission: "owner").flattened_list.first++ expect(owner_entry).to include(+ type: :user,+ id: user.id,+ permission: "owner",+ mandatory: false,+ )+ end+it "returns an empty array when there are no acls" doexpect(described_class.where(target: Fabricate(:category)).flattened_list).to eq([])enddiff --git a/spec/models/concerns/acl_target_spec.rb b/spec/models/concerns/acl_target_spec.rbindex 79a91b2424f..733e54492d3 100644--- a/spec/models/concerns/acl_target_spec.rb+++ b/spec/models/concerns/acl_target_spec.rb@@ -68,4 +68,38 @@ RSpec.describe AclTarget do)endend++ describe "permission scopes" do+ fab!(:acl_user, :user)+ fab!(:owned_post, :post)+ fab!(:viewable_post, :post)+ fab!(:other_post, :post)++ before do+ Fabricate(+ :access_control_list_with_users,+ target: owned_post.becomes(target_class),+ permission: "owner",+ users: [acl_user],+ )+ Fabricate(+ :access_control_list_with_users,+ target: viewable_post.becomes(target_class),+ permission: "view",+ users: [acl_user],+ )+ end++ it "includes owned targets in a single-permission scope" do+ expect(target_class.with_acl_permission(acl_user.guardian, "view").pluck(:id)).to(+ contain_exactly(owned_post.id, viewable_post.id),+ )+ end++ it "includes owned targets in a multi-permission scope" do+ expect(+ target_class.with_any_acl_permissions(acl_user.guardian, %w[view edit]).pluck(:id),+ ).to contain_exactly(owned_post.id, viewable_post.id)+ end+ endenddiff --git a/spec/models/user_history_spec.rb b/spec/models/user_history_spec.rbindex 3467fe1cf2f..672e6e3c702 100644--- a/spec/models/user_history_spec.rb+++ b/spec/models/user_history_spec.rb@@ -12,6 +12,16 @@ RSpec.describe UserHistory doit "'change_site_text' should be at 29th position" doexpect(actions[:change_site_text]).to eq(29)end++ it "keeps ACL owner actions at their assigned positions" do+ expect(+ actions.values_at(:add_access_control_list_owner, :remove_access_control_list_owner),+ ).to eq([133, 134])+ expect(described_class.staff_actions).to include(+ :add_access_control_list_owner,+ :remove_access_control_list_owner,+ )+ endendenddiff --git a/spec/requests/access_control_lists_controller_spec.rb b/spec/requests/access_control_lists_controller_spec.rbindex 246bd14073c..3bba766b995 100644--- a/spec/requests/access_control_lists_controller_spec.rb+++ b/spec/requests/access_control_lists_controller_spec.rb@@ -85,7 +85,7 @@ RSpec.describe AccessControlListsController do)end- it "returns creation-specific wording when a new target would lose a warning permission" do+ it "allows creation with an ACL that omits a loss warning permission" dopost "/access-control/evaluate.json",params: {target_type: "EvaluateModificationRequestTestTarget",@@ -93,16 +93,8 @@ RSpec.describe AccessControlListsController do},as: :json- expect(response.status).to eq(422)- expect(response.parsed_body).to eq(- {- "errors" => ["You will not have permission if you create this target. Continue?"],- "extras" => {- "current_user_will_lose_permission" => true,- "loss_warning_permissions" => ["manage"],- },- },- )+ expect(response.status).to eq(200)+ expect(response.parsed_body).to include("current_user_will_lose_permissions" => false)endit "retains edit wording when an existing target would lose a warning permission" do@@ -120,27 +112,63 @@ RSpec.describe AccessControlListsController do)end- it "returns generic creation wording when a new target would grant no access" do+ it "warns an existing owner who removes their final permission" do+ target = Fabricate(:post).becomes(EvaluateModificationRequestTestTarget)+ Fabricate(+ :access_control_list_with_users,+ target:,+ permission: Acl::Permissions::OWNER,+ users: [current_user],+ )EvaluateModificationRequestTestTarget.stubs(:loss_warning_permissions).returns([])post "/access-control/evaluate.json",params: {+ target_id: target.id,target_type: "EvaluateModificationRequestTestTarget",new_acl: [],},as: :jsonexpect(response.status).to eq(422)- expect(response.parsed_body).to eq(- {- "errors" => [- I18n.t("access_control_list.errors.user_will_not_have_permission_on_create"),- ],- "extras" => {- "current_user_will_lose_permission" => true,- },- },+ expect(response.parsed_body["errors"]).to contain_exactly(+ I18n.t("access_control_list.errors.user_will_not_have_permission"),+ )+ end++ it "allows an existing owner to retain a direct loss warning permission" do+ target = Fabricate(:post).becomes(EvaluateModificationRequestTestTarget)+ Fabricate(+ :access_control_list_with_users,+ target:,+ permission: Acl::Permissions::OWNER,+ users: [current_user],)++ post "/access-control/evaluate.json",+ params: {+ target_id: target.id,+ target_type: "EvaluateModificationRequestTestTarget",+ new_acl: [{ type: "user", id: current_user.id, permission: "manage" }],+ },+ as: :json++ expect(response.status).to eq(200)+ expect(response.parsed_body).to include("current_user_will_lose_permissions" => false)+ end++ it "allows creation with an empty ACL" do+ EvaluateModificationRequestTestTarget.stubs(:loss_warning_permissions).returns([])++ post "/access-control/evaluate.json",+ params: {+ target_type: "EvaluateModificationRequestTestTarget",+ new_acl: [],+ },+ as: :json++ expect(response.status).to eq(200)+ expect(response.parsed_body).to include("current_user_will_lose_permissions" => false)endendenddiff --git a/spec/services/access_control_list/action/build_replacement_spec.rb b/spec/services/access_control_list/action/build_replacement_spec.rbnew file mode 100644index 00000000000..6f7e6f3fa7b--- /dev/null+++ b/spec/services/access_control_list/action/build_replacement_spec.rb@@ -0,0 +1,151 @@+# frozen_string_literal: true++RSpec.describe AccessControlList::Action::BuildReplacement do+ subject(:replacement) do+ described_class.call(acl_entries:, initial_owner:, owner_user_ids:, target:, current_acl:)+ end++ class BuildReplacementAclTargetSpecTarget < Category+ include AclTarget++ self.table_name = "categories"++ def self.name+ "BuildReplacementAclTargetSpecTarget"+ end++ ACL_PERMISSIONS = Acl::Permissions.new(:view, :edit, :manage)+ end++ fab!(:initial_owner, :user)+ fab!(:current_owner, :user)+ fab!(:co_owner, :user)+ fab!(:group)+ fab!(:target) { Fabricate(:category).becomes(BuildReplacementAclTargetSpecTarget) }++ let(:acl_entries) { [{ type: :group, id: group.id, permission: "view" }] }+ let(:owner_user_ids) { nil }+ let(:current_acl) { AccessControlList.where(target:).target_acl(target) }++ context "when the target has no current owner" do+ it "adds the initial owner and reports the resulting changes" do+ expect(replacement.flattened_acl).to contain_exactly(+ { type: :group, id: group.id, permission: "view" },+ { type: :user, id: initial_owner.id, permission: Acl::Permissions::OWNER },+ )+ expect(replacement.added_owner_user_ids).to eq([initial_owner.id])+ expect(replacement.removed_owner_user_ids).to be_empty+ expect(replacement.ordinary_permissions_changed).to be(true)+ end+ end++ context "when requested owners are provided for an ownerless target" do+ let(:owner_user_ids) { [co_owner.id, co_owner.id] }++ it "deduplicates the request and retains the initial owner" do+ expect(replacement.permissions.dig(Acl::Permissions::OWNER, :user_ids)).to contain_exactly(+ co_owner.id,+ initial_owner.id,+ )+ expect(replacement.added_owner_user_ids).to contain_exactly(co_owner.id, initial_owner.id)+ end+ end++ context "when the current owners are not replaced" do+ fab!(:owner_acl) do+ Fabricate(+ :access_control_list_with_users,+ target:,+ permission: Acl::Permissions::OWNER,+ users: [current_owner],+ )+ end++ it "preserves the current owners" do+ expect(replacement.permissions.dig(Acl::Permissions::OWNER, :user_ids)).to eq(+ [current_owner.id],+ )+ expect(replacement.added_owner_user_ids).to be_empty+ expect(replacement.removed_owner_user_ids).to be_empty+ end+ end++ context "when the current owner set is replaced" do+ fab!(:owner_acl) do+ Fabricate(+ :access_control_list_with_users,+ target:,+ permission: Acl::Permissions::OWNER,+ users: [current_owner],+ )+ end++ let(:owner_user_ids) { [co_owner.id] }++ it "reports owners added and removed" do+ expect(replacement.added_owner_user_ids).to eq([co_owner.id])+ expect(replacement.removed_owner_user_ids).to eq([current_owner.id])+ end+ end++ context "when an owner also has a lower direct permission" do+ fab!(:owner_acl) do+ Fabricate(+ :access_control_list_with_users,+ target:,+ permission: Acl::Permissions::OWNER,+ users: [current_owner],+ )+ end++ let(:acl_entries) do+ [+ { type: :user, id: current_owner.id, permission: "manage" },+ { type: :group, id: group.id, permission: "manage" },+ ]+ end++ it "removes the redundant user permission and preserves the group permission" do+ expect(replacement.flattened_acl).to contain_exactly(+ { type: :group, id: group.id, permission: "manage" },+ { type: :user, id: current_owner.id, permission: Acl::Permissions::OWNER },+ )+ end+ end++ context "when the target declares a missing mandatory permission" do+ before do+ BuildReplacementAclTargetSpecTarget.stubs(:mandatory_acl).returns(+ [{ type: :group, id: Group::AUTO_GROUPS[:admins], permission: "manage" }],+ )+ end++ it "injects the mandatory entry" do+ expect(replacement.flattened_acl).to include(+ type: :group,+ id: Group::AUTO_GROUPS[:admins],+ permission: "manage",+ )+ end+ end++ context "when only ownership changes" do+ fab!(:owner_acl) do+ Fabricate(+ :access_control_list_with_users,+ target:,+ permission: Acl::Permissions::OWNER,+ users: [current_owner],+ )+ end+ fab!(:view_acl) do+ Fabricate(:access_control_list_with_groups, target:, permission: "view", groups: [group])+ end++ let(:owner_user_ids) { [current_owner.id, co_owner.id] }++ it "does not report an ordinary permission change" do+ expect(replacement.ordinary_permissions_changed).to be(false)+ end+ end+enddiff --git a/spec/services/access_control_list/apply_spec.rb b/spec/services/access_control_list/apply_spec.rbnew file mode 100644index 00000000000..e26dcc1f6ee--- /dev/null+++ b/spec/services/access_control_list/apply_spec.rb@@ -0,0 +1,262 @@+# frozen_string_literal: true++RSpec.describe AccessControlList::Apply do+ class ApplyAclTargetSpecTarget < Category+ include AclTarget++ self.table_name = "categories"++ def self.name+ "ApplyAclTargetSpecTarget"+ end++ ACL_PERMISSIONS = Acl::Permissions.new(:view, :edit, :manage)+ end++ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:acl_target_type) }+ it { is_expected.to allow_value(1).for(:acl_target_id) }+ it { is_expected.not_to allow_value(0).for(:acl_target_id) }+ it { is_expected.to validate_presence_of(:source) }+ it { is_expected.to validate_length_of(:source).is_at_most(100) }+ it { is_expected.to allow_value([Discourse::SYSTEM_USER_ID]).for(:owner_user_ids) }+ it { is_expected.not_to allow_value([0]).for(:owner_user_ids) }+ it { is_expected.not_to allow_value([-2]).for(:owner_user_ids) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:admin)+ fab!(:target_owner, :user)+ fab!(:co_owner, :user)+ fab!(:other_user, :user)+ fab!(:group)+ fab!(:other_group, :group)+ fab!(:target) { Fabricate(:category).becomes(ApplyAclTargetSpecTarget) }++ let(:params) do+ {+ acl_target_type: target.class.name,+ acl_target_id: target.id,+ acl_entries:,+ source: "test_source",+ initial_owner_user_id: target_owner.id,+ owner_user_ids:,+ }+ end+ let(:dependencies) { { guardian: admin.guardian } }+ let(:acl_entries) do+ [+ { type: :group, id: group.id, permission: "view" },+ { type: :group, id: other_group.id, permission: "edit" },+ ]+ end+ let(:owner_user_ids) { nil }++ context "when the contract is invalid" do+ let(:params) { super().merge(acl_target_id: 0) }++ it { is_expected.to fail_a_contract }+ end++ context "when the ACL target is not found" do+ let(:params) { super().merge(acl_target_id: 999_999) }++ it { is_expected.to fail_to_find_a_model(:acl_target) }+ end++ context "when an owner is submitted as an ordinary ACL entry" do+ let(:acl_entries) do+ [{ type: :user, id: target_owner.id, permission: Acl::Permissions::OWNER }]+ end++ it { is_expected.to fail_a_policy(:has_no_owner_entries) }+ end++ context "when an ordinary ACL grantee does not exist" do+ let(:acl_entries) { [{ type: :user, id: 999_999, permission: "view" }] }++ it { is_expected.to fail_a_policy(:grantees_exist) }+ end++ context "when a requested owner does not exist" do+ let(:owner_user_ids) { [co_owner.id, 999_999] }++ it { is_expected.to fail_a_policy(:requested_owners_exist) }+ end++ context "when the system user is the current and requested owner" do+ fab!(:owner_acl) do+ Fabricate(+ :access_control_list_with_users,+ target:,+ permission: Acl::Permissions::OWNER,+ users: [Discourse.system_user],+ )+ end++ let(:acl_entries) { [] }+ let(:owner_user_ids) { [Discourse::SYSTEM_USER_ID] }++ it "preserves the system user as the owner" do+ expect(result).to run_successfully+ expect(+ AccessControlList.find_by!(target:, permission: Acl::Permissions::OWNER).allowed_user_ids,+ ).to eq([Discourse::SYSTEM_USER_ID])+ end+ end++ context "without an initial owner for an ownerless target" do+ let(:params) { super().merge(initial_owner_user_id: 999_999) }++ it { is_expected.to fail_a_policy(:has_initial_owner) }+ end++ context "when a non-owner requests an ownership change" do+ fab!(:owner_acl) do+ Fabricate(+ :access_control_list_with_users,+ target:,+ permission: Acl::Permissions::OWNER,+ users: [target_owner],+ )+ end++ let(:dependencies) { { guardian: other_user.guardian } }+ let(:owner_user_ids) { [target_owner.id, co_owner.id] }++ it { is_expected.to fail_a_policy(:can_change_owners) }+ end++ context "when an owner removes the final owner" do+ fab!(:owner_acl) do+ Fabricate(+ :access_control_list_with_users,+ target:,+ permission: Acl::Permissions::OWNER,+ users: [target_owner],+ )+ end++ let(:dependencies) { { guardian: target_owner.guardian } }+ let(:owner_user_ids) { [] }++ it { is_expected.to fail_a_policy(:has_at_least_one_owner) }+ end++ context "when an unknown permission is requested" do+ let(:acl_entries) { [{ type: :group, id: group.id, permission: "unknown" }] }++ it { is_expected.to fail_a_policy(:has_valid_permissions) }+ end++ context "when a banned ACL entry is requested" do+ let(:acl_entries) { [{ type: :group, id: group.id, permission: "edit" }] }++ before do+ ApplyAclTargetSpecTarget.stubs(:banned_acl).returns(+ [{ type: :group, id: group.id, permission: "edit" }],+ )+ end++ it { is_expected.to fail_a_policy(:has_no_banned_acl) }+ end++ context "when applying an initial ACL" do+ it { is_expected.to run_successfully }++ it "persists the owner and ordinary permissions with the source" do+ expect { result }.to change { AccessControlList.where(target:).count }.from(0).to(3)++ expect(AccessControlList.where(target:).pluck(:source).uniq).to eq(["test_source"])+ expect(AccessControlList.find_by!(target:, permission: "view").allowed_group_ids).to eq(+ [group.id],+ )+ expect(AccessControlList.find_by!(target:, permission: "edit").allowed_group_ids).to eq(+ [other_group.id],+ )+ expect(+ AccessControlList.find_by!(target:, permission: Acl::Permissions::OWNER).allowed_user_ids,+ ).to eq([target_owner.id])+ end++ it "logs the ordinary permission and owner changes" do+ expect { result }.to change {+ UserHistory.where(+ action: UserHistory.actions[:change_access_control_list_permissions],+ ).count+ }.by(1).and change {+ UserHistory.where(action: UserHistory.actions[:add_access_control_list_owner]).count+ }.by(1)+ end+ end++ context "when an admin specifies owners for an ownerless target" do+ let(:acl_entries) { [] }+ let(:owner_user_ids) { [co_owner.id] }++ it "retains the initial owner and adds every requested owner" do+ expect(result).to run_successfully+ expect(+ AccessControlList.find_by!(target:, permission: Acl::Permissions::OWNER).allowed_user_ids,+ ).to contain_exactly(target_owner.id, co_owner.id)+ end+ end++ context "when existing owners are omitted from the request" do+ fab!(:owner_acl) do+ Fabricate(+ :access_control_list_with_users,+ target:,+ permission: Acl::Permissions::OWNER,+ users: [target_owner],+ )+ end++ it "preserves the current owners" do+ expect(result).to run_successfully+ expect(+ AccessControlList.find_by!(target:, permission: Acl::Permissions::OWNER).allowed_user_ids,+ ).to eq([target_owner.id])+ end+ end++ context "when a current owner replaces the owner set" do+ fab!(:owner_acl) do+ Fabricate(+ :access_control_list_with_users,+ target:,+ permission: Acl::Permissions::OWNER,+ users: [target_owner, co_owner],+ )+ end++ let(:dependencies) { { guardian: target_owner.guardian } }+ let(:acl_entries) { [] }+ let(:owner_user_ids) { [co_owner.id] }++ it "allows self-removal while another owner remains" do+ expect(result).to run_successfully+ expect(+ AccessControlList.find_by!(target:, permission: Acl::Permissions::OWNER).allowed_user_ids,+ ).to eq([co_owner.id])+ end++ it "logs the ownership removal without an ordinary permission change" do+ expect { result }.to change {+ UserHistory.where(action: UserHistory.actions[:remove_access_control_list_owner]).count+ }.by(1).and not_change {+ UserHistory.where(+ action: UserHistory.actions[:change_access_control_list_permissions],+ ).count+ }++ expect(UserHistory.last).to have_attributes(+ subject: "Category (#{target.id})",+ target_user_id: target_owner.id,+ )+ end+ end+ end+enddiff --git a/spec/services/access_control_list/evaluate_modification_spec.rb b/spec/services/access_control_list/evaluate_modification_spec.rbindex 7a160f65c5a..37a5f4c2b48 100644--- a/spec/services/access_control_list/evaluate_modification_spec.rb+++ b/spec/services/access_control_list/evaluate_modification_spec.rb@@ -11,13 +11,14 @@ RSpec.describe AccessControlList::EvaluateModification dofab!(:current_user, :user)- let(:params) { { new_acl:, target_type: } }+ let(:params) { { new_acl:, target_id:, target_type: } }let(:dependencies) { { guardian: } }let(:guardian) { current_user.guardian }let(:new_acl) do[{ type: "group", id: Group::AUTO_GROUPS[:logged_in_users], permission: "view" }]end- let(:target) { Fabricate(:post) }+ let(:target) { Fabricate(:post).becomes(EvaluateModificationTestTargetClass) }+ let(:target_id) { target.id }let(:target_type) { "EvaluateModificationTestTargetClass" }class EvaluateModificationTestTargetClass < ActiveRecord::Base@@ -42,12 +43,55 @@ RSpec.describe AccessControlList::EvaluateModification doit { is_expected.to fail_to_find_a_model(:target_type_klass) }end- context "when the new ACL is empty" do+ context "when an existing owner removes ownership without retaining another grant" dolet(:new_acl) { [] }+ before do+ Fabricate(+ :access_control_list_with_users,+ target:,+ permission: Acl::Permissions::OWNER,+ users: [current_user],+ )+ end+it { is_expected.to fail_a_policy(:user_will_have_permission) }end+ context "when an existing owner retains a direct loss warning permission" do+ let(:new_acl) { [{ type: "user", id: current_user.id, permission: "manage" }] }++ before do+ Fabricate(+ :access_control_list_with_users,+ target:,+ permission: Acl::Permissions::OWNER,+ users: [current_user],+ )+ EvaluateModificationTestTargetClass.stubs(:loss_warning_permissions).returns(["manage"])+ end++ it { is_expected.to run_successfully }+ end++ context "when creating a target with an empty ACL" do+ let(:new_acl) { [] }+ let(:target_id) { nil }++ it { is_expected.to run_successfully }+ end++ context "when creating a target with a loss warning permission" do+ let(:new_acl) { [] }+ let(:target_id) { nil }++ before do+ EvaluateModificationTestTargetClass.stubs(:loss_warning_permissions).returns(["manage"])+ end++ it { is_expected.to run_successfully }+ end+context "when the new ACL is empty but the target has mandatory ACL entries that cover the current user" dolet(:new_acl) { [] }@@ -89,6 +133,18 @@ RSpec.describe AccessControlList::EvaluateModification doit { is_expected.to fail_a_policy(:user_will_not_lose_permission) }end++ context "when the current user is a proposed owner" do+ let(:new_acl) do+ [{ type: "user", id: current_user.id, permission: Acl::Permissions::OWNER }]+ end++ before do+ EvaluateModificationTestTargetClass.stubs(:loss_warning_permissions).returns(["manage"])+ end++ it { is_expected.to run_successfully }+ endendendenddiff --git a/spec/services/access_control_list_manager_spec.rb b/spec/services/access_control_list_manager_spec.rbdeleted file mode 100644index 323b940b6b0..00000000000--- a/spec/services/access_control_list_manager_spec.rb+++ /dev/null@@ -1,286 +0,0 @@-# frozen_string_literal: true--RSpec.describe AccessControlListManager do- class AclTargetSpecTarget < Category- include AclTarget-- self.table_name = "categories"-- def self.name- "AclTargetSpecTarget"- end-- ACL_PERMISSIONS = Acl::Permissions.new(:view, :edit, :manage)- end-- class InheritedAclTargetSpecTarget < AclTargetSpecTarget- end-- class UndeclaredAclTargetSpecTarget < Category- include AclTarget- end-- 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!(:group)- fab!(:other_group, :group)- fab!(:target) do- cat = AclTargetSpecTarget.new(name: "Test Category", user: admin)- cat.skip_publish = true- cat.save!- cat- end-- let(:params) { { target:, flattened_acl:, owner: } }- let(:dependencies) { { guardian: } }- let(:guardian) { admin.guardian }- let(:owner) { "test_owner" }-- let(:flattened_acl) do- [- { type: "group", id: group.id, permission: "view" },- { type: "group", id: other_group.id, permission: "edit" },- ]- 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 the target has no permission declaration" do- fab!(:target) { Fabricate(:category).becomes(UndeclaredAclTargetSpecTarget) }-- it "raises a configuration error without creating ACLs" do- expect { result }.to raise_error(NameError, /ACL_PERMISSIONS/)- expect(AccessControlList.where(target:)).to be_empty- end- end-- context "when the target inherits its permission declaration" do- fab!(:target) { Fabricate(:category).becomes(InheritedAclTargetSpecTarget) }-- it "accepts and persists inherited permissions" do- expect(result).to run_successfully- expect(AccessControlList.where(target:).pluck(:permission)).to contain_exactly(- "view",- "edit",- )- end- end-- context "when an unknown permission is provided" do- let(:flattened_acl) { [{ type: "group", id: group.id, permission: "Jester" }] }-- it "rejects the ACL without creating permissions or logging a change" do- expect { result }.not_to change { AccessControlList.where(target:).count }- expect(result).to fail_a_policy(:has_valid_permissions)- expect(- UserHistory.where(action: UserHistory.actions[:change_access_control_list_permissions]),- ).to be_empty- end- end-- context "when valid and invalid permissions are mixed" do- fab!(:existing_acl) do- Fabricate(:access_control_list_with_groups, target:, permission: "manage", groups: [group])- end-- let(:flattened_acl) do- [- { type: "group", id: group.id, permission: "view" },- { type: "group", id: other_group.id, permission: "Jester" },- ]- end-- it "preserves all existing ACL data" do- expect { result }.not_to change { AccessControlList.where(target:).map(&:attributes) }- expect(result).to fail_a_policy(:has_valid_permissions)- end- end-- context "when a permission is blank" do- let(:flattened_acl) { [{ type: "group", id: group.id, permission: "" }] }-- it { is_expected.to fail_a_policy(:has_valid_permissions) }- end-- context "when a permission is missing" do- let(:flattened_acl) { [{ type: "group", id: group.id }] }-- it { is_expected.to fail_a_policy(:has_valid_permissions) }- end-- context "when a mandatory permission is invalid" do- before do- AclTargetSpecTarget.stubs(:mandatory_acl).returns(- [{ type: :group, id: Group::AUTO_GROUPS[:admins], permission: "Jester" }],- )- end-- it "rejects the injected permission without creating ACLs" do- expect { result }.not_to change { AccessControlList.where(target:).count }- expect(result).to fail_a_policy(:has_valid_permissions)- end- 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: target).count }.from(0).to(2)-- view_acl = AccessControlList.find_by(target: target, permission: "view")- edit_acl = AccessControlList.find_by(target: target, 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: target).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 (#{target.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: target,- permission: "manage",- groups: [group],- )- end-- it "replaces the previous access control lists" do- existing_id = existing_acl.id- result-- expect(AccessControlList.where(target: target).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 (#{target.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- it "does not modify the flattened ACL" do- result-- expect(AccessControlList.where(target: target).pluck(:permission)).to contain_exactly(- "edit",- "view",- )- end- end-- context "when the target has mandatory ACLs" do- before do- AclTargetSpecTarget.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: target).pluck(:permission)).to contain_exactly(- "view",- "edit",- "manage",- )-- manage_acl = AccessControlList.find_by(target: target, 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: target, permission: "manage").count).to eq(1)- end- end- end- end-- describe "banned 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[:anonymous_users], permission: "edit" },- ]- end-- context "when the target does not have banned ACLs" do- it "does not modify the flattened ACL" do- result-- expect(AccessControlList.where(target: target).pluck(:permission)).to contain_exactly(- "edit",- "view",- )- end- end-- context "when the target has banned ACLs" do- before do- AclTargetSpecTarget.stubs(:banned_acl).returns(- [{ type: :group, id: Group::AUTO_GROUPS[:anonymous_users], permission: "edit" }],- )- end-- it { is_expected.to fail_a_policy(:has_no_banned_acl) }- end- end- end-enddiff --git a/spec/services/staff_action_logger_spec.rb b/spec/services/staff_action_logger_spec.rbindex 3a29f33320d..7d3f6fdc6e2 100644--- a/spec/services/staff_action_logger_spec.rb+++ b/spec/services/staff_action_logger_spec.rb@@ -15,6 +15,38 @@ RSpec.describe StaffActionLogger doendend+ describe "ACL owner changes" do+ fab!(:target, :category)+ fab!(:target_user, :user)++ it "logs owner additions and removals as distinct actions" do+ added = logger.log_add_access_control_list_owner(target, target_user)+ removed = logger.log_remove_access_control_list_owner(target, target_user)++ expect([added, removed]).to contain_exactly(+ have_attributes(+ action: UserHistory.actions[:add_access_control_list_owner],+ subject: "Category (#{target.id})",+ target_user_id: target_user.id,+ ),+ have_attributes(+ action: UserHistory.actions[:remove_access_control_list_owner],+ subject: "Category (#{target.id})",+ target_user_id: target_user.id,+ ),+ )+ end++ it "rejects an invalid target user" do+ expect { logger.log_add_access_control_list_owner(target, nil) }.to raise_error(+ Discourse::InvalidParameters,+ )+ expect { logger.log_remove_access_control_list_owner(target, target.id) }.to raise_error(+ Discourse::InvalidParameters,+ )+ end+ end+describe "log_user_deletion" dosubject(:log_user_deletion) { described_class.new(admin).log_user_deletion(deleted_user) }