Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Evaluate ACL before save to prevent user from removing themselves from ACL (#42044)

Martin Brennana0de88db7b97
diff --git a/.skills/discourse-acl-authoring/SKILL.md b/.skills/discourse-acl-authoring/SKILL.md
index 3163a055f82..4ef16403f2b 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, Site access_control metadata, plugin ACL target registration, or the DAccessControl UI component.
+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.
---
# Discourse ACL Authoring
@@ -12,7 +12,7 @@ Use this skill before adding or reviewing ACL-backed resource permissions in Dis
1. Identify the target resource and desired permission vocabulary. Prefer simple strings such as `view`, `edit`, and `manage`, but confirm the target's domain semantics.
2. Read [references/backend-model.md](references/backend-model.md) when touching `AccessControlList`, `AclTarget`, `Acl::Target`, `Acl::User`, `Guardian`, `User#permission_acl`, or target visibility queries.
3. Read [references/manager-and-plugin-integration.md](references/manager-and-plugin-integration.md) when writing ACLs, creating target models, registering plugin target classes, serializing ACLs, or integrating services/controllers.
-4. Read [references/frontend-d-access-control.md](references/frontend-d-access-control.md) when using or customizing `DAccessControl`.
+4. Read [references/frontend-d-access-control.md](references/frontend-d-access-control.md) when using or customizing `DAccessControl`, `DAccessControlField`, or FormKit ACL validation.
5. Read [references/testing-and-review.md](references/testing-and-review.md) when adding specs or reviewing an ACL feature.
6. Also load `.skills/discourse-service-authoring` for `Service::Base` changes, `.skills/discourse-writing-rspec-tests` for RSpec, and `.skills/discourse-writing-js-tests` for QUnit.
@@ -24,6 +24,9 @@ Use this skill before adding or reviewing ACL-backed resource permissions in Dis
- 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.
+- 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.
- Do not claim user ACL support is complete. Backend support is partially wired for `allowed_user_ids` in expansion, flattening, preloading, lookup helpers, matching scopes, and cleanup jobs, but `DAccessControl` remains group-first and does not yet provide complete user ACL editing.
## Local Anchors
@@ -34,8 +37,9 @@ Use this skill before adding or reviewing ACL-backed resource permissions in Dis
- Guardian helpers: `lib/guardian.rb`
- User ACL cache: `app/models/user.rb`
- Write manager: `app/services/access_control_list_manager.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 component: `frontend/discourse/app/ui-kit/d-access-control.gjs`
-- Core specs: `spec/models/access_control_list_spec.rb`, `spec/models/concerns/acl_target_spec.rb`, `spec/lib/acl/target_spec.rb`, `spec/jobs/regular/cleanup_acls_for_deleted_spec.rb`, `spec/services/access_control_list_manager_spec.rb`, `spec/serializers/site_serializer_spec.rb`, `frontend/discourse/tests/integration/components/d-access-control-test.gjs`
+- 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`
- Plugin consumer example: `plugins/discourse-kanban` or the external `discourse-kanban` checkout when present.
diff --git a/.skills/discourse-acl-authoring/references/backend-model.md b/.skills/discourse-acl-authoring/references/backend-model.md
index ed4055bc6a1..78d3b4cc1de 100644
--- a/.skills/discourse-acl-authoring/references/backend-model.md
+++ b/.skills/discourse-acl-authoring/references/backend-model.md
@@ -148,6 +148,8 @@ The concern provides:
- `.acl_is_mandatory?(acl)`
- `.has_banned_acl?`
- `.acl_is_banned?(acl)`
+- `.has_loss_warning_permissions?`
+- `.acl_triggers_loss_warning?(acl)`
- `mandatory_acl_as_expanded_list(owner)`
`AclTarget.acl_matches?(acl_a, acl_b)` is the shared comparator for mandatory and banned ACL matching. It normalizes `type` to symbols and compares `permission` as strings.
@@ -185,6 +187,25 @@ Banned entries are consumed by both backend writes and frontend rendering:
Keep mandatory and banned ACL metadata group-based unless the target flow has explicit user ACL UI and review coverage. Backend lookups can understand user ACL rows, but shared frontend editing is not complete.
+## Loss Warning Permissions
+
+Define `self.loss_warning_permissions` when the current actor should confirm losing particular permissions from the proposed ACL:
+
+```ruby
+def self.loss_warning_permissions
+ %w[manage]
+end
+```
+
+This 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.
+
+The concern provides:
+
+- `.has_loss_warning_permissions?` to detect non-empty configuration.
+- `.acl_triggers_loss_warning?(acl)` to test whether one flattened ACL entry has a configured permission.
+
+Use a noun phrase because the method returns permission strings; do not reintroduce action-like names such as `warn_of_loss`.
+
## Stale References
`flattened_list` is defensive around stale data:
diff --git a/.skills/discourse-acl-authoring/references/frontend-d-access-control.md b/.skills/discourse-acl-authoring/references/frontend-d-access-control.md
index d3f13124e40..3252d53863a 100644
--- a/.skills/discourse-acl-authoring/references/frontend-d-access-control.md
+++ b/.skills/discourse-acl-authoring/references/frontend-d-access-control.md
@@ -16,7 +16,7 @@ Basic usage:
<DAccessControl
@groups={{this.site.groups}}
@acl={{field.value}}
- @aclTarget="DiscourseKanban::Board"
+ @aclTarget={{this.aclTarget}}
@onChange={{this.aclChanged}}
@transformPermissionOptions={{this.transformPermissionOptions}}
/>
@@ -27,10 +27,22 @@ Arguments:
- `@groups`: group records available for selection. Each group should have `id`, `name`, `full_name`, and `automatic`.
- `@acl`: flattened ACL entries from the backend or form state. 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 key used to load mandatory ACL entries from `site.access_control.mandatory_acl` and banned entries from `site.access_control.banned_acl`.
+- `@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.
- `@transformPermissionOptions`: optional callback to customize default permission labels/descriptions or add target-specific permissions.
-`@aclTarget` must match `target_class.acl_target_key`; by default this is the Ruby class name such as `"DiscourseKanban::Board"`.
+Example target descriptor:
+
+```js
+get aclTarget() {
+ return {
+ type: "Plugin::Target",
+ id: this.args.model.target?.id,
+ name: i18n("plugin.target.name"),
+ };
+}
+```
+
+`@aclTarget.type` must be the Ruby class name resolved through `Site.access_control_target_classes`. It is also used to index mandatory and banned site metadata, which is keyed by `target_class.acl_target_key`. Keep the default `acl_target_key` when using this component: a custom key cannot currently satisfy both class lookup during evaluation and frontend metadata lookup.
## Controlled Component Behavior
@@ -100,31 +112,51 @@ The component is still group-first for preloaded data and mandatory ACL injectio
## FormKit Integration
-When used inside a FormKit custom field:
+Prefer `DAccessControlField` instead of assembling a custom FormKit field directly:
```gjs
-<form.Field
- @name="acl"
+import DAccessControlField from "discourse/ui-kit/d-access-control-field";
+
+<DAccessControlField
+ @form={{form}}
@title={{i18n "plugin.target.access"}}
@description={{i18n "plugin.target.access_description"}}
- @format="max"
- @type="custom"
- @validate={{this.validateAccess}}
- as |field|
->
- <field.Control>
- <DAccessControl
- @groups={{this.site.groups}}
- @acl={{field.value}}
- @aclTarget="Plugin::Target"
- @onChange={{this.aclChanged}}
- @transformPermissionOptions={{this.transformPermissionOptions}}
- />
- </field.Control>
-</form.Field>
+ @aclTarget={{this.aclTarget}}
+ @onChange={{this.aclChanged}}
+ @onAccessLossConfirmed={{this.accessLossConfirmed}}
+ @mustHavePermissions={{array "manage"}}
+ @transformPermissionOptions={{this.transformPermissionOptions}}
+/>
+```
+
+The wrapper owns a FormKit custom field named `acl` and supplies `site.groups` to `DAccessControl`. Its arguments are:
+
+- `@form`: the contextual FormKit object.
+- `@title` and `@description`: field metadata.
+- `@aclTarget`: `{ type, id, name }`, passed through to `DAccessControl` and the evaluation request.
+- `@onChange`: writes the controlled ACL value back to the parent form.
+- `@onAccessLossConfirmed`: optional callback invoked after the current user confirms a warning that they will lose access. It receives `{ permissions }`, where `permissions` contains the target's configured `loss_warning_permissions` and is empty when the user will lose all access without a configured warning permission. Consumers can use this to defer route refreshes or reloads until their save succeeds.
+- `@transformPermissionOptions`: passed through to `DAccessControl`.
+- `@mustHavePermissions`: optional permission strings. At least one ACL entry must have one of them or the field adds a visible validation error.
+
+Use `@mustHavePermissions` only for the separate invariant that at least one grantee must retain an allowed permission. It does not specifically protect the current actor. Omit it if removing the final `manage` grant is allowed after confirmation.
+
+The parent still owns controlled state:
+
+```js
+@action
+aclChanged(acl) {
+ this.formApi.set("acl", acl);
+}
```
-Validate the form state client-side for user experience, but rely on server-side validation and `AccessControlListManager` for actual enforcement.
+On submission, the field posts the proposed ACL to `/access-control/evaluate.json`. If the current user would lose access or a configured `loss_warning_permissions` permission, it displays the server-provided confirmation message. Confirming allows submission. Cancelling calls FormKit's `preventSubmit()`; this skips commit and `@onSubmit` without showing an extra validation error.
+
+Keep post-save lifecycle behavior in the consumer. For example, a modal can set a flag from `@onAccessLossConfirmed`, save through its FormKit `@onSubmit`, and pass the flag to its caller through `closeModal(data)`. The promise returned by `modal.show()` resolves with that data after the modal closes, at which point the caller can refresh or reload. Reset a previously set flag when `@onChange` receives another ACL draft, and never reload when confirmation is cancelled or the save fails.
+
+`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.
## Testing
@@ -139,3 +171,5 @@ Consumer tests should cover:
- `@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 assertions
+
+For `DAccessControlField` consumers, also cover required permissions, confirmation and cancellation of loss warnings, no visible error on cancellation, and the final save payload after confirmation.
diff --git a/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md b/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md
index fb8a67ae16d..df6f71c7790 100644
--- a/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md
+++ b/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md
@@ -99,6 +99,38 @@ The key is `target_class.acl_target_key`, which defaults to the class name. If a
`mandatory_acl` and `banned_acl` are both always present in the serialized `access_control` payload. Each map only includes target classes that define non-empty metadata for that ACL type.
+## Evaluating Permission Loss Before Save
+
+`POST /access-control/evaluate.json` calls `AccessControlList::EvaluateModification` with:
+
+```json
+{
+ "target_type": "Plugin::Target",
+ "target_id": 123,
+ "new_acl": []
+}
+```
+
+The service resolves `target_type` from `Site.access_control_target_classes`, injects the target class's mandatory ACL entries, and calculates which proposed entries apply to the current user through direct user grants or group membership. Evaluation fails when either:
+
+- the current user would have no permission after the change; or
+- the current user would lose any permission declared by `loss_warning_permissions`.
+
+The first case uses `access_control_list.errors.user_will_not_have_permission`. For configured loss warnings, define a target-specific server translation:
+
+```yaml
+en:
+ access_control_list:
+ errors:
+ "Plugin::Target_user_will_lose_permission": "You will no longer be able to manage this target. Continue?"
+```
+
+The suffix is `#{target_class.acl_target_key}_user_will_lose_permission`. Keep this translation in the plugin when the ACL target is plugin-owned.
+
+The service evaluates only the proposed ACL. It does not load the target or compare the proposal with persisted ACL rows, and `target_id` is not currently used by the service. 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.
+
## Serializing Target ACLs
Use `AccessControlList.where(target: target).flattened_list` when returning ACLs to a client that edits them.
diff --git a/.skills/discourse-acl-authoring/references/testing-and-review.md b/.skills/discourse-acl-authoring/references/testing-and-review.md
index e638b4d1188..c3f0542ad6e 100644
--- a/.skills/discourse-acl-authoring/references/testing-and-review.md
+++ b/.skills/discourse-acl-authoring/references/testing-and-review.md
@@ -8,9 +8,19 @@ For target models:
- Include `AclTarget`.
- Cover `mandatory_acl` if the target defines one.
+- Cover `loss_warning_permissions` when the target requires confirmation before the current actor loses a permission.
- Cover domain helper methods such as `anonymous_can_read?` or `can_write?` that wrap `permission_acl`.
- Cover `.with_acl_permission` and `.with_any_acl_permissions` when index/list actions depend on the shared scopes.
+For `AccessControlList::EvaluateModification`:
+
+- Unknown target types fail model lookup.
+- 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`.
+- Targets without loss warning permissions can proceed while the current user retains some access.
+
For Guardian methods:
- Cover anonymous, logged-in, direct group membership, writer-implies-reader, and manager cases as applicable.
@@ -63,6 +73,15 @@ For `DAccessControl` consumers:
- `onChange` writes updated ACL arrays into parent state.
- The final save payload includes the intended ACL array.
+For `DAccessControlField` consumers:
+
+- `@mustHavePermissions` adds a visible field error when no ACL entry has an allowed permission.
+- Omitting `@mustHavePermissions` permits removal of the final manager when that is the intended confirmed flow.
+- A loss-warning response displays the target-specific server message for confirmation.
+- Confirming proceeds and does not prompt again for the same ACL fingerprint.
+- Cancelling prevents commit and `@onSubmit` without adding a visible error.
+- A later submission attempt is evaluated again when the ACL differs or the previous attempt was cancelled.
+
Use `.skills/discourse-writing-js-tests` for QUnit patterns.
## Review Checklist
@@ -74,7 +93,9 @@ Ask these questions during code review:
- 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?
-- Does the UI `@aclTarget` string match the target's `acl_target_key`?
+- Does `@aclTarget.type` contain the registered Ruby class name, and does the target retain the default matching `acl_target_key`?
+- If the target defines `loss_warning_permissions`, does it provide the matching `access_control_list.errors.<acl_target_key>_user_will_lose_permission` server translation?
+- 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?
- Are group and user IDs validated before persistence when they come from params?
@@ -89,5 +110,8 @@ Ask these questions during code review:
- `DAccessControl` remains group-first and does not provide complete user ACL editing yet.
- `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.
+- `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/controllers/access_control_lists_controller.rb b/app/controllers/access_control_lists_controller.rb
index 2c2d2bf6290..65fefdc93d6 100644
--- a/app/controllers/access_control_lists_controller.rb
+++ b/app/controllers/access_control_lists_controller.rb
@@ -23,6 +23,35 @@ class AccessControlListsController < ApplicationController
end
end
+ def evaluate
+ AccessControlList::EvaluateModification.call(service_params) do |result|
+ on_success { render json: success_json.merge({ current_user_will_lose_permissions: false }) }
+ on_failed_contract { |contract| render_json_error(contract.errors.full_messages) }
+ on_model_not_found(:target_type_klass) { raise Discourse::InvalidParameters }
+ on_failed_policy(:user_will_not_lose_permission) do |target_type_klass:|
+ # NOTE: The target type class (e.g. a Kanban::Board, or Category) will need to define
+ # the translation key here in server.en.yml
+ render_json_error(
+ I18n.t(
+ "access_control_list.errors.#{target_type_klass.acl_target_key}_user_will_lose_permission",
+ ),
+ {
+ extras: {
+ current_user_will_lose_permission: true,
+ loss_warning_permissions: target_type_klass.loss_warning_permissions,
+ },
+ },
+ )
+ end
+ on_failed_policy(:user_will_have_permission) do
+ render_json_error(
+ I18n.t("access_control_list.errors.user_will_not_have_permission"),
+ { extras: { current_user_will_lose_permission: true } },
+ )
+ end
+ end
+ end
+
private
def serialize_users(users)
diff --git a/app/models/access_control_list.rb b/app/models/access_control_list.rb
index 8f08f42ff12..dcf336b7c5b 100644
--- a/app/models/access_control_list.rb
+++ b/app/models/access_control_list.rb
@@ -94,13 +94,19 @@ class AccessControlList < ActiveRecord::Base
->(group) { allowing_any_group([group.id]).or(allowing_users_in_group(group.id)) }
def self.inject_mandatory_acl(flattened_acl, target)
- return flattened_acl if !target.class.has_mandatory_acl?
+ target_klass =
+ if target.is_a?(String)
+ target.safe_constantize
+ else
+ target.class
+ end
+
+ return flattened_acl if !target_klass.has_mandatory_acl?
flattened_acl = dedup_flattened_list(flattened_acl)
- target.class.mandatory_acl.each do |mandatory_acl|
+ target_klass.mandatory_acl.each do |mandatory_acl|
next if flattened_acl.any? { |acl| AclTarget.acl_matches?(acl, mandatory_acl) }
-
flattened_acl << mandatory_acl
end
diff --git a/app/models/concerns/acl_target.rb b/app/models/concerns/acl_target.rb
index be58082ba47..c852b61f3e3 100644
--- a/app/models/concerns/acl_target.rb
+++ b/app/models/concerns/acl_target.rb
@@ -77,5 +77,14 @@ module AclTarget
def acl_is_banned?(acl)
has_banned_acl? && banned_acl.any? { |banned_acl| AclTarget.acl_matches?(acl, banned_acl) }
end
+
+ def has_loss_warning_permissions?
+ defined?(loss_warning_permissions).present? && loss_warning_permissions.length.positive?
+ end
+
+ def acl_triggers_loss_warning?(acl)
+ has_loss_warning_permissions? &&
+ loss_warning_permissions.any? { |permission| acl[:permission].to_s == permission.to_s }
+ end
end
end
diff --git a/app/models/site.rb b/app/models/site.rb
index d25c683bf97..ccbc8000d25 100644
--- a/app/models/site.rb
+++ b/app/models/site.rb
@@ -57,35 +57,36 @@ class Site
self.class.access_control
end
- def self.access_control
- target_classes =
- (
- AclTarget.target_classes +
- DiscoursePluginRegistry.acl_target_classes.filter_map do |target_class|
- if target_class.is_a?(String)
- target_class = target_class.safe_constantize
- if target_class.nil?
- Rails.logger.warn(
- "[ACL] Unknown target class in plugin registry for site (#{target_class}) maybe the plugin is gone, the class has been renamed, or the class does not include AclTarget",
- )
- end
- target_class
- else
- target_class
+ def self.access_control_target_classes
+ (
+ AclTarget.target_classes +
+ DiscoursePluginRegistry.acl_target_classes.filter_map do |target_class|
+ if target_class.is_a?(String)
+ target_class = target_class.safe_constantize
+ if target_class.nil?
+ Rails.logger.warn(
+ "[ACL] Unknown target class in plugin registry for site (#{target_class}) maybe the plugin is gone, the class has been renamed, or the class does not include AclTarget",
+ )
end
+ target_class
+ else
+ target_class
end
- ).compact.uniq
+ end
+ ).compact.uniq
+ end
+ def self.access_control
{
mandatory_acl:
- target_classes.each_with_object({}) do |target_class, mandatory_acl|
+ access_control_target_classes.each_with_object({}) do |target_class, mandatory_acl|
next if !target_class.respond_to?(:has_mandatory_acl?)
next if !target_class.has_mandatory_acl?
mandatory_acl[target_class.acl_target_key] = target_class.mandatory_acl
end,
banned_acl:
- target_classes.each_with_object({}) do |target_class, banned_acl|
+ access_control_target_classes.each_with_object({}) do |target_class, banned_acl|
next if !target_class.respond_to?(:has_banned_acl?)
next if !target_class.has_banned_acl?
diff --git a/app/services/access_control_list/evaluate_modification.rb b/app/services/access_control_list/evaluate_modification.rb
new file mode 100644
index 00000000000..e1aa040ffb7
--- /dev/null
+++ b/app/services/access_control_list/evaluate_modification.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+class AccessControlList::EvaluateModification
+ include Service::Base
+
+ params do
+ attribute :new_acl, :array
+ attribute :target_type, :string
+
+ validates :target_type, presence: true
+ end
+
+ model :target_type_klass
+ model :new_acl_with_mandatory, optional: true
+ model :acl_user_will_have, optional: true
+ policy :user_will_not_lose_permission
+ policy :user_will_have_permission
+
+ private
+
+ def fetch_target_type_klass(params:)
+ Site.access_control_target_classes.find { |klass| klass.name == params.target_type }
+ end
+
+ def fetch_new_acl_with_mandatory(params:)
+ AccessControlList.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
+ end
+ end
+ end
+
+ def 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?
+ end
+
+ def user_will_have_permission(acl_user_will_have:)
+ acl_user_will_have.any?
+ end
+end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 9b0399bda4b..0cd0b529327 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -60,6 +60,7 @@ en:
mandatory_acl_tooltip: "This permission is mandatory for %{name} and cannot be removed"
mandatory: "Mandatory"
disallowed: "Disallowed"
+ required_permission_not_added: "At least one grantee must have %{permission} permission for this %{typeName}"
carousel:
go_to_slide: "Go to slide %{index}"
previous: "Previous slide"
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 731f3f5b6e7..aa5b1cfc498 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -61,15 +61,17 @@ en:
redirect_warning: "We were unable to verify that the link you selected was actually posted to the forum. If you wish to proceed anyway, select the link below."
on_another_topic: "On another topic"
+ access_control_list:
+ errors:
+ user_will_not_have_permission: "If you remove this ACL entry you will lose access to this entity."
+
topic_category_changed: "From %{from} to %{to}"
topic_tag_changed:
added_and_removed: "Added %{added} and removed %{removed}"
added: "Added %{added}"
removed: "Removed %{removed}"
-
topics_bulk_action:
too_many_topic_ids: "You can only perform a bulk action on up to %{limit} topics at once."
-
inline_oneboxer:
topic_page_title_post_number: "#%{post_number}"
topic_page_title_post_number_by_user: "#%{post_number} by %{username}"
diff --git a/config/routes.rb b/config/routes.rb
index dda88d96eab..3555889c7bc 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -640,6 +640,7 @@ Discourse::Application.routes.draw do
get "edit-directory-columns" => "edit_directory_columns#index", :format => :json
put "edit-directory-columns" => "edit_directory_columns#update", :format => :json
get "access-control/grantees/search" => "access_control_lists#search_grantees"
+ post "access-control/evaluate" => "access_control_lists#evaluate"
%w[users u].each_with_index do |root_path, index|
get "#{root_path}" => "users#index", :constraints => { format: "html" }
diff --git a/docs/developer-guides/docs/03-code-internals/21-form-kit.md b/docs/developer-guides/docs/03-code-internals/21-form-kit.md
index e03b2a62dda..e697164ad82 100644
--- a/docs/developer-guides/docs/03-code-internals/21-form-kit.md
+++ b/docs/developer-guides/docs/03-code-internals/21-form-kit.md
@@ -1797,6 +1797,8 @@ Rules can be combined using the pipe operator: `|`.
## Custom Validation
+Custom validators can call `preventSubmit` to stop the current submission without marking the form invalid. It only affects the current validation pass and must be called again to prevent a later submission attempt. Calling it during a validation pass that was not triggered by submission has no effect.
+
### Field
Field accepts a `@validate` property which allows you to define a callback function to validate a single field.
@@ -1809,6 +1811,7 @@ Field accepts a `@validate` property which allows you to define a callback funct
- `context.data` (Object): Current form draft data.
- `context.type` (string): Field control type.
- `context.addError` (Function): Adds an error if validation fails.
+ - `context.preventSubmit` (Function): Prevents the current submission without adding an error.
**Example**
@@ -1846,6 +1849,7 @@ Form accepts a `@validate` property which allows you to define a callback functi
- `handlers` (Object): An object containing handler functions.
- `handlers.addError` (Function): A function to add an error if validation fails.
- `handlers.removeError` (Function): A function to clear an existing error.
+ - `handlers.preventSubmit` (Function): Prevents the current submission without adding an error.
**Example**
diff --git a/frontend/discourse/app/form-kit/components/fk/field-data.gjs b/frontend/discourse/app/form-kit/components/fk/field-data.gjs
index a4a1f1e41cd..2a2460b4845 100644
--- a/frontend/discourse/app/form-kit/components/fk/field-data.gjs
+++ b/frontend/discourse/app/form-kit/components/fk/field-data.gjs
@@ -321,9 +321,11 @@ export default class FKFieldData extends Component {
* @param {string} name - The name of the field.
* @param {any} value - The value of the field.
* @param {Object} data - Additional data for validation.
- * @returns {Promise<Object>} The validation errors.
+ * @param {Object} context - Additional validation handlers.
+ * @param {Function} context.preventSubmit - Prevents the current submission.
+ * @returns {Promise<void>}
*/
- async validate(name, value, data) {
+ async validate(name, value, data, { preventSubmit }) {
if (this.disabled) {
return;
}
@@ -332,6 +334,7 @@ export default class FKFieldData extends Component {
data,
type: this.type,
addError: this.addError,
+ preventSubmit,
});
const validator = new Validator(value, this.rules);
diff --git a/frontend/discourse/app/form-kit/components/fk/form.gjs b/frontend/discourse/app/form-kit/components/fk/form.gjs
index bdd19d0d397..129a99a7e53 100644
--- a/frontend/discourse/app/form-kit/components/fk/form.gjs
+++ b/frontend/discourse/app/form-kit/components/fk/form.gjs
@@ -273,7 +273,13 @@ class FKForm extends Component {
try {
this.isSubmitting = true;
- await this.validate([...this.fields.values()]);
+ const submissionPrevented = await this.validate([
+ ...this.fields.values(),
+ ]);
+
+ if (submissionPrevented) {
+ return;
+ }
if (this.formData.isValid) {
if (this.args.commitOnSubmit !== false) {
@@ -323,6 +329,8 @@ class FKForm extends Component {
}
this.isValidating = true;
+ let submissionPrevented = false;
+ const preventSubmit = () => (submissionPrevented = true);
try {
for (const field of fields) {
@@ -331,17 +339,21 @@ class FKForm extends Component {
await field.validate?.(
field.name,
this.formData.get(field.name),
- this.formData.draftData
+ this.formData.draftData,
+ { preventSubmit }
);
}
await this.args.validate?.(this.formData.draftData, {
addError: this.addError,
removeError: this.removeError,
+ preventSubmit,
});
} finally {
this.isValidating = false;
}
+
+ return submissionPrevented;
}
<template>
diff --git a/frontend/discourse/app/ui-kit/d-access-control-field.gjs b/frontend/discourse/app/ui-kit/d-access-control-field.gjs
new file mode 100644
index 00000000000..49ed3a5d886
--- /dev/null
+++ b/frontend/discourse/app/ui-kit/d-access-control-field.gjs
@@ -0,0 +1,102 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import DAccessControl from "discourse/ui-kit/d-access-control";
+import { i18n } from "discourse-i18n";
+
+export default class DAccessControlField extends Component {
+ @service site;
+ @service dialog;
+
+ @action
+ async validateAccess(name, value, { addError, preventSubmit }) {
+ const acl = value || [];
+
+ if (this.args.mustHavePermissions) {
+ if (
+ !acl.some((entry) =>
+ this.args.mustHavePermissions.includes(entry.permission)
+ )
+ ) {
+ addError(name, {
+ title: this.args.title,
+ message: i18n("access_control.manage.required_permission_not_added", {
+ permission: this.args.mustHavePermissions.join(", "),
+ typeName: this.args.aclTarget.name,
+ }),
+ });
+ }
+ }
+
+ let evaluation = {};
+
+ try {
+ await ajax("/access-control/evaluate.json", {
+ type: "POST",
+ contentType: "application/json",
+ data: JSON.stringify({
+ target_type: this.args.aclTarget.type,
+ target_id: this.args.aclTarget.id,
+ new_acl: acl,
+ }),
+ });
+ } catch (err) {
+ if (
+ !Object.hasOwn(
+ err.jqXHR.responseJSON.extras,
+ "current_user_will_lose_permission"
+ )
+ ) {
+ addError(name, {
+ title: this.args.title,
+ message: i18n("generic_error"),
+ });
+ return;
+ } else {
+ // extras is where we store current_user_will_lose_permission and loss_warning_permissions
+ Object.assign(evaluation, err.jqXHR.responseJSON.extras);
+ evaluation.errorMessage = err.jqXHR.responseJSON.errors[0];
+ }
+ }
+
+ if (!evaluation.current_user_will_lose_permission) {
+ return;
+ }
+
+ const confirmed = await this.dialog.confirm({
+ message: evaluation.errorMessage,
+ });
+
+ if (!confirmed) {
+ preventSubmit();
+ return;
+ }
+
+ this.args.onAccessLossConfirmed?.({
+ permissions: evaluation.loss_warning_permissions ?? [],
+ });
+ }
+
+ <template>
+ <@form.Field
+ @name="acl"
+ @title={{@title}}
+ @description={{@description}}
+ @format="max"
+ @type="custom"
+ @validate={{this.validateAccess}}
+ as |field|
+ >
+ <field.Control>
+ <DAccessControl
+ @groups={{this.site.groups}}
+ @acl={{field.value}}
+ @aclTarget={{@aclTarget}}
+ @onChange={{@onChange}}
+ @transformPermissionOptions={{@transformPermissionOptions}}
+ />
+ </field.Control>
+ </@form.Field>
+ </template>
+}
diff --git a/frontend/discourse/app/ui-kit/d-access-control-grantee-chooser.gjs b/frontend/discourse/app/ui-kit/d-access-control-grantee-chooser.gjs
index dc8c01624c1..8a8df751262 100644
--- a/frontend/discourse/app/ui-kit/d-access-control-grantee-chooser.gjs
+++ b/frontend/discourse/app/ui-kit/d-access-control-grantee-chooser.gjs
@@ -76,7 +76,7 @@ export default class DAccessControlGranteeChooser extends EmailGroupUserChooser
const results = await ajax(ACCESS_CONTROL_GRANTEE_SEARCH_URL, {
data: {
term: filter,
- acl_target: this.selectKit.options.aclTarget,
+ acl_target: this.selectKit.options.aclTargetType,
},
});
return this.excludeSelectedGrantees(
diff --git a/frontend/discourse/app/ui-kit/d-access-control.gjs b/frontend/discourse/app/ui-kit/d-access-control.gjs
index c2f5bd0d378..51700c5f082 100644
--- a/frontend/discourse/app/ui-kit/d-access-control.gjs
+++ b/frontend/discourse/app/ui-kit/d-access-control.gjs
@@ -116,7 +116,9 @@ export default class DAccessControl extends Component {
return [];
}
- return this.site.access_control?.mandatory_acl?.[this.args.aclTarget] || [];
+ return (
+ this.site.access_control?.mandatory_acl?.[this.args.aclTarget.type] || []
+ );
}
/**
@@ -131,7 +133,9 @@ export default class DAccessControl extends Component {
return [];
}
- return this.site.access_control?.banned_acl?.[this.args.aclTarget] || [];
+ return (
+ this.site.access_control?.banned_acl?.[this.args.aclTarget.type] || []
+ );
}
/**
@@ -386,7 +390,7 @@ export default class DAccessControl extends Component {
@labelProperty="name"
@filterPlaceholder="access_control.manage.add_group"
@options={{hash
- aclTarget=@aclTarget
customSearchOptions=(hash
defaultSearchResults=this.defaultAvailableGrantees
)
diff --git a/frontend/discourse/tests/integration/components/d-access-control-test.gjs b/frontend/discourse/tests/integration/components/d-access-control-test.gjs
index 22e016a4419..9751e099b92 100644
--- a/frontend/discourse/tests/integration/components/d-access-control-test.gjs
+++ b/frontend/discourse/tests/integration/components/d-access-control-test.gjs
@@ -1,11 +1,16 @@
import { tracked } from "@glimmer/tracking";
+import { getOwner } from "@ember/owner";
import { click, findAll, render } from "@ember/test-helpers";
import { module, test } from "qunit";
+import sinon from "sinon";
+import Form from "discourse/components/form";
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 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";
import { i18n } from "discourse-i18n";
// A non-automatic group, plus the "logged_in_users" auto group (id: 5) which is one of
@@ -31,6 +36,12 @@ const GROUPS = [
},
];
+const aclTarget = {
+ type: "TestTarget",
+ id: 123,
+ name: "Test Target",
+};
+
// Builds a controlled-component wrapper: `onChange` writes the next acl back into
// tracked state so the component re-renders the way it would in a real parent.
function controlledState(initialAcl = []) {
@@ -191,7 +202,7 @@ module("Integration | Component | DAccessControl", function (hooks) {
<DAccessControl
@groups={{GROUPS}}
@acl={{state.acl}}
- @aclTarget="TestTarget"
+ @aclTarget={{aclTarget}}
@onChange={{state.onChange}}
/>
</template>
@@ -289,7 +300,7 @@ module("Integration | Component | DAccessControl", function (hooks) {
<DAccessControl
@groups={{GROUPS}}
@acl={{state.acl}}
- @aclTarget="TestTarget"
+ @aclTarget={{aclTarget}}
@onChange={{state.onChange}}
/>
</template>
@@ -571,7 +582,7 @@ module("Integration | Component | DAccessControl", function (hooks) {
<DAccessControl
@groups={{GROUPS}}
@acl={{state.acl}}
- @aclTarget="TestTarget"
+ @aclTarget={{aclTarget}}
@onChange={{state.onChange}}
@transformPermissionOptions={{transformPermissionOptions}}
/>
@@ -699,7 +710,7 @@ module("Integration | Component | DAccessControl", function (hooks) {
<DAccessControl
@groups={{GROUPS}}
@acl={{state.acl}}
- @aclTarget="TestTarget"
+ @aclTarget={{aclTarget}}
@onChange={{state.onChange}}
/>
</template>
@@ -748,7 +759,7 @@ module("Integration | Component | DAccessControl", function (hooks) {
<DAccessControl
@groups={{GROUPS}}
@acl={{state.acl}}
- @aclTarget="TestTarget"
+ @aclTarget={{aclTarget}}
@onChange={{state.onChange}}
/>
</template>
@@ -766,3 +777,51 @@ module("Integration | Component | DAccessControl", function (hooks) {
);
});
});
+
+module("Integration | Component | DAccessControlField", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("reports confirmed access loss and allows submission", async function (assert) {
+ const dialog = getOwner(this).lookup("service:dialog");
+ sinon.stub(dialog, "confirm").resolves(true);
+
+ pretender.post("/access-control/evaluate.json", () =>
+ response(422, {
+ errors: ["You will lose permission to manage this target."],
+ extras: {
+ current_user_will_lose_permission: true,
+ loss_warning_permissions: ["manage"],
+ },
+ })
+ );
+
+ this.data = { acl: [] };
+ this.onChange = sinon.spy();
+ this.onSubmit = sinon.spy();
+ this.onAccessLossConfirmed = sinon.spy();
+
+ await render(
+ <template>
+ <Form @data={{this.data}} @onSubmit={{this.onSubmit}} as |form|>
+ <DAccessControlField
+ @form={{form}}
+ @title="Access"
+ @aclTarget={{aclTarget}}
+ @onChange={{this.onChange}}
+ @onAccessLossConfirmed={{this.onAccessLossConfirmed}}
+ />
+ <form.Submit />
+ </Form>
+ </template>
+ );
+
+ await formKit().submit();
+
+ assert.true(this.onSubmit.calledOnce, "the form submits");
+ assert.deepEqual(
+ this.onAccessLossConfirmed.firstCall.args,
+ [{ permissions: ["manage"] }],
+ "the confirmed warning permissions are reported"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/components/form-kit/field-test.gjs b/frontend/discourse/tests/integration/components/form-kit/field-test.gjs
index add2fa59a8d..f3013142c68 100644
--- a/frontend/discourse/tests/integration/components/form-kit/field-test.gjs
+++ b/frontend/discourse/tests/integration/components/form-kit/field-test.gjs
@@ -275,6 +275,34 @@ module("Integration | Component | FormKit | Field", function (hooks) {
.hasError("error", "the callback has the addError helper as param");
});
+ test("@validate can prevent the current submission", async function (assert) {
+ const onSubmit = sinon.spy();
+ const validate = (_name, _value, { preventSubmit }) => preventSubmit();
+
+ await render(
+ <template>
+ <Form @data={{hash foo="bar"}} @onSubmit={{onSubmit}} as |form|>
+ <form.Field
+ @type="input"
+ @name="foo"
+ @title="Foo"
+ @validate={{validate}}
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+
+ <form.Submit />
+ </Form>
+ </template>
+ );
+
+ await formKit().submit();
+
+ assert.false(onSubmit.called, "the submission callback is not called");
+ assert.form().hasNoErrors("no validation error is displayed");
+ });
+
test("@showTitle", async function (assert) {
await render(
<template>
diff --git a/frontend/discourse/tests/integration/components/form-kit/form-test.gjs b/frontend/discourse/tests/integration/components/form-kit/form-test.gjs
index ff4d95a14d8..cf2122550cb 100644
--- a/frontend/discourse/tests/integration/components/form-kit/form-test.gjs
+++ b/frontend/discourse/tests/integration/components/form-kit/form-test.gjs
@@ -1,6 +1,7 @@
import { array, fn, hash } from "@ember/helper";
import { click, render } from "@ember/test-helpers";
import { module, test } from "qunit";
+import sinon from "sinon";
import Form from "discourse/components/form";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
import formKit from "discourse/tests/helpers/form-kit-helper";
@@ -47,6 +48,42 @@ module("Integration | Component | FormKit | Form", function (hooks) {
assert.strictEqual(formApi.get("foo"), 1, "the failed change can be reset");
});
+ test("@validate can prevent the current submission", async function (assert) {
+ let formApi;
+ let shouldPreventSubmit = true;
+ const onSubmit = sinon.spy();
+ const registerApi = (api) => (formApi = api);
+ const validate = (_data, { preventSubmit }) => {
+ if (shouldPreventSubmit) {
+ preventSubmit();
+ }
+ };
+
+ await render(
+ <template>
+ <Form
+ @data={{hash foo=1}}
+ @onSubmit={{onSubmit}}
+ @onRegisterApi={{registerApi}}
+ @validate={{validate}}
+ />
+ </template>
+ );
+
+ await formApi.set("foo", 2);
+ await formApi.submit();
+
+ assert.false(onSubmit.called, "the submission callback is not called");
+ assert.true(formApi.isDirty, "the draft data is not committed");
+ assert.form().hasNoErrors("no validation error is displayed");
+
+ shouldPreventSubmit = false;
+ await formApi.submit();
+
+ assert.true(onSubmit.calledOnce, "a later submission can proceed");
+ assert.false(formApi.isDirty, "the successful submission is committed");
+ });
+
test("@onSet", async function (assert) {
const calls = [];
const onSet = (name, value, data) => {
diff --git a/spec/services/access_control_list/evaluate_modification_spec.rb b/spec/services/access_control_list/evaluate_modification_spec.rb
new file mode 100644
index 00000000000..09f2b0da14c
--- /dev/null
+++ b/spec/services/access_control_list/evaluate_modification_spec.rb
@@ -0,0 +1,91 @@
+# frozen_string_literal: true
+
+RSpec.describe AccessControlList::EvaluateModification do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:target_type) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:current_user, :user)
+
+ let(:params) { { new_acl:, 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_type) { "EvaluateModificationTestTargetClass" }
+
+ class EvaluateModificationTestTargetClass < ActiveRecord::Base
+ include AclTarget
+
+ self.table_name = "posts"
+
+ def self.mandatory_acl
+ [{ type: :group, id: Group::AUTO_GROUPS[:admins], permission: "manage" }]
+ end
+
+ def self.loss_warning_permissions
+ []
+ end
+ end
+
+ context "when the target type does not exist" do
+ let(:target_type) { "UnknownAclTarget" }
+
+ it { is_expected.to fail_to_find_a_model(:target_type_klass) }
+ end
+
+ context "when the new ACL is empty" do
+ let(:new_acl) { [] }
+
+ it { is_expected.to fail_a_policy(:user_will_have_permission) }
+ end
+
+ context "when the new ACL is empty but the target has mandatory ACL entries that cover the current user" do
+ let(:new_acl) { [] }
+
+ before do
+ current_user.grant_admin!
+ guardian.user.reload
+ end
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when the new ACL is not empty" do
+ fab!(:group)
+ let(:new_acl) { [{ type: "group", id: group.id, permission: "edit" }] }
+
+ context "when a group in the new ACL grants the current user permission" do
+ before do
+ group.add(current_user)
+ guardian.user.reload
+ end
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when a user in the new ACL grants the current user permission" do
+ let(:new_acl) { [{ type: "user", id: current_user.id, permission: "edit" }] }
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when no entries grant the current user permission" do
+ it { is_expected.to fail_a_policy(:user_will_have_permission) }
+ end
+
+ context "when the new ACL is missing a loss warning permission defined by the target" do
+ before do
+ EvaluateModificationTestTargetClass.stubs(:loss_warning_permissions).returns(["manage"])
+ end
+
+ it { is_expected.to fail_a_policy(:user_will_not_lose_permission) }
+ end
+ end
+ end
+end
diff --git a/spec/system/page_objects/components/d_access_control.rb b/spec/system/page_objects/components/d_access_control.rb
new file mode 100644
index 00000000000..51245e32530
--- /dev/null
+++ b/spec/system/page_objects/components/d_access_control.rb
@@ -0,0 +1,86 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Components
+ class DAccessControl < PageObjects::Components::Base
+ FIELD_NAME = "acl"
+ FORM_SELECTOR = ".form-kit"
+ ROW_SELECTOR = ".d-access-control__row"
+
+ def form
+ @form ||= PageObjects::Components::FormKit.new(FORM_SELECTOR)
+ end
+
+ def dialog
+ @dialog ||= PageObjects::Components::Dialog.new
+ end
+
+ def add_group(group)
+ add_grantee(type: "group", id: group.id)
+ end
+
+ def add_user(user)
+ add_grantee(type: "user", id: user.id, search: user.username)
+ end
+
+ def has_row?(type:, id:)
+ component.has_css?(row_selector(type:, id:))
+ end
+
+ def has_no_row?(type:, id:)
+ component.has_no_css?(row_selector(type:, id:))
+ end
+
+ def row(type:, id:)
+ DAccessControlRow.new(scoped_row_selector(type:, id:))
+ end
+
+ def remove_permission_row(type:, id:)
+ row(type:, id:).select_permission("remove")
+ end
+
+ def save
+ form.submit
+ end
+
+ def has_loss_warning?(message)
+ dialog.has_content?(message)
+ end
+
+ def confirm_loss_warning
+ dialog.click_yes
+ end
+
+ def cancel_loss_warning
+ dialog.click_no
+ end
+
+ private
+
+ def component
+ form.field(FIELD_NAME).component.find(".d-access-control")
+ end
+
+ def add_grantee(type:, id:, search: nil)
+ chooser = grantee_chooser
+ chooser.expand
+ chooser.search(search) if search
+ chooser.select_row_by_value("#{type}:#{id}")
+ end
+
+ def grantee_chooser
+ chooser = component.find(".d-access-control__chooser")
+ PageObjects::Components::SelectKit.new("##{chooser["id"]}")
+ end
+
+ def row_selector(type:, id:)
+ "#{ROW_SELECTOR}[data-row-type='#{type}'][data-row-id='#{id}']"
+ end
+
+ def scoped_row_selector(type:, id:)
+ field = form.field(FIELD_NAME).component
+ "##{field["id"]} #{row_selector(type:, id:)}"
+ end
+ end
+ end
+end
diff --git a/spec/system/page_objects/components/d_access_control_row.rb b/spec/system/page_objects/components/d_access_control_row.rb
new file mode 100644
index 00000000000..1430290130c
--- /dev/null
+++ b/spec/system/page_objects/components/d_access_control_row.rb
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Components
+ class DAccessControlRow < PageObjects::Components::Base
+ PERMISSION_MENU_IDENTIFIER = "d-access-control__permission-menu"
+ PERMISSION_OPTION_SELECTOR = ".d-access-control__permission-option"
+
+ def initialize(selector)
+ @selector = selector
+ end
+
+ def permission
+ component.find("[data-permission]")["data-permission"]
+ end
+
+ def has_permission?(permission)
+ component.has_css?("[data-permission='#{permission}']")
+ end
+
+ def has_available_permissions?(*permissions)
+ menu = open_permission_menu
+
+ within(menu.portal_with_identifier_selector) do
+ has_css?(PERMISSION_OPTION_SELECTOR, count: permissions.length) &&
+ permissions.all? { |permission| has_css?(permission_option_selector(permission)) }
+ end
+ end
+
+ def has_available_permission?(permission)
+ open_permission_menu.has_option?(permission_option_selector(permission))
+ end
+
+ def has_no_available_permission?(permission)
+ open_permission_menu.has_no_option?(permission_option_selector(permission))
+ end
+
+ def select_permission(permission)
+ open_permission_menu.option(permission_option_selector(permission)).click
+ end
+
+ private
+
+ def component
+ find(@selector)
+ end
+
+ def permission_menu
+ PageObjects::Components::DMenu.new(
+ component.find(".d-access-control__permission"),
+ PERMISSION_MENU_IDENTIFIER,
+ )
+ end
+
+ def open_permission_menu
+ menu = permission_menu
+ menu.expand if menu.is_collapsed?
+ menu
+ end
+
+ def permission_option_selector(permission)
+ "#{PERMISSION_OPTION_SELECTOR}[data-permission-id='#{permission}']"
+ end
+ end
+ end
+end