Skip to content

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

FIX: Validate ACL permissions before saving ACLs (#43440)

Martin Brennan8535d1bccbbf
diff --git a/.skills/discourse-acl-authoring/SKILL.md b/.skills/discourse-acl-authoring/SKILL.md
index 4ef16403f2b..6c348363e6b 100644
--- a/.skills/discourse-acl-authoring/SKILL.md
+++ b/.skills/discourse-acl-authoring/SKILL.md
@@ -9,7 +9,7 @@ Use this skill before adding or reviewing ACL-backed resource permissions in Dis
## Workflow
-1. Identify the target resource and desired permission vocabulary. Prefer simple strings such as `view`, `edit`, and `manage`, but confirm the target's domain semantics.
+1. Identify the target resource and its `ACL_PERMISSIONS` declaration. Prefer simple IDs 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`, `DAccessControlField`, or FormKit ACL validation.
@@ -18,6 +18,8 @@ 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.
+- 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 `AccessControlList.flattened_list` as the API shape for UI/client payloads and `AccessControlList.expand_list_for_bulk_insert` as the DB insert shape.
@@ -27,12 +29,13 @@ Use this skill before adding or reviewing ACL-backed resource permissions in Dis
- 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.
+- 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.
## Local Anchors
- Model and relation API: `app/models/access_control_list.rb`
- Target concern: `app/models/concerns/acl_target.rb`
+- Permission declarations: `lib/acl/permissions.rb`, `spec/lib/acl/permissions_spec.rb`
- Permission lookup objects: `lib/acl/target.rb`, `lib/acl/user.rb`
- Guardian helpers: `lib/guardian.rb`
- User ACL cache: `app/models/user.rb`
@@ -42,4 +45,4 @@ Use this skill before adding or reviewing ACL-backed resource permissions in Dis
- 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`
-- Plugin consumer example: `plugins/discourse-kanban` or the external `discourse-kanban` checkout when present.
+- 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.md
index 78d3b4cc1de..c71210e9207 100644
--- a/.skills/discourse-acl-authoring/references/backend-model.md
+++ b/.skills/discourse-acl-authoring/references/backend-model.md
@@ -9,9 +9,9 @@ Use this reference when working with `AccessControlList`, `AclTarget`, `Acl::Tar
Important columns:
- `target_type`, `target_id`: polymorphic target.
-- `permission`: freeform string such as `view`, `edit`, `manage`, or target-specific permissions.
+- `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.
- `allowed_group_ids`: bigint array of groups that hold the permission.
-- `allowed_user_ids`: bigint array of users that hold the permission. Backend lookup and persistence support is partial; the main remaining gap is complete `DAccessControl` user editing.
+- `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.
The model has a uniqueness validation and DB index for target + permission. Multiple groups for the same permission collapse into one row.
@@ -133,9 +133,13 @@ Include `AclTarget` in any model that owns ACL rows:
```ruby
class Board < ActiveRecord::Base
include AclTarget
+
+ ACL_PERMISSIONS = Acl::Permissions.new(:view, :edit, :manage)
end
```
+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.
+
The concern provides:
- `has_many :access_control_lists, as: :target, dependent: :destroy`
@@ -150,7 +154,6 @@ The concern provides:
- `.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.
@@ -160,7 +163,7 @@ Define `self.mandatory_acl` on the target class when some grants must always exi
```ruby
def self.mandatory_acl
- [{ type: :group, id: Group::AUTO_GROUPS[:admins], permission: "manage" }]
+ [{ type: :group, id: Group::AUTO_GROUPS[:admins], permission: ACL_PERMISSIONS.manage }]
end
```
@@ -168,7 +171,7 @@ Define `self.banned_acl` on the target class when specific grants must never be
```ruby
def self.banned_acl
- [{ type: :group, id: Group::AUTO_GROUPS[:anonymous_users], permission: "edit" }]
+ [{ type: :group, id: Group::AUTO_GROUPS[:anonymous_users], permission: ACL_PERMISSIONS.edit }]
end
```
@@ -193,7 +196,7 @@ Define `self.loss_warning_permissions` when the current actor should confirm los
```ruby
def self.loss_warning_permissions
- %w[manage]
+ [ACL_PERMISSIONS.manage]
end
```
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 3252d53863a..299bd678072 100644
--- a/.skills/discourse-acl-authoring/references/frontend-d-access-control.md
+++ b/.skills/discourse-acl-authoring/references/frontend-d-access-control.md
@@ -28,7 +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.
-- `@transformPermissionOptions`: optional callback to customize default permission labels/descriptions or add target-specific permissions.
+- `@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:
@@ -88,6 +88,8 @@ 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`.
+
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.
Target-specific options added via `@transformPermissionOptions` can still be banned for individual grantees. For example, a target may add `manage` and then define `banned_acl` entries that remove `edit` and `manage` from the `anonymous_users` auto group.
@@ -164,7 +166,7 @@ Core component tests live in `frontend/discourse/tests/integration/components/d-
Consumer tests should cover:
-- target-specific permission options are present
+- target-specific permission options are present and their IDs match the server's `ACL_PERMISSIONS`
- `@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
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 0a9ee07b1af..83905d7e5f9 100644
--- a/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md
+++ b/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md
@@ -12,7 +12,7 @@ AccessControlListManager.call(
params: {
target: board,
flattened_acl: flattened_acl,
- owner: DiscourseKanban::PLUGIN_NAME,
+ owner: Boards::PLUGIN_NAME,
},
) do |result|
on_success do |previous_permissions:, new_permissions:|
@@ -30,6 +30,8 @@ Behavior:
- validates `target` and `owner`
- fetches previous target permissions
- injects mandatory ACLs into `flattened_acl`
+- 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
@@ -66,7 +68,7 @@ Plugin target classes must include `AclTarget` and be registered after initializ
```ruby
after_initialize do
- DiscoursePluginRegistry.register_acl_target_class(DiscourseKanban::Board, self)
+ DiscoursePluginRegistry.register_acl_target_class(Boards::Board, self)
end
```
@@ -83,12 +85,12 @@ Shape:
```ruby
{
mandatory_acl: {
- "DiscourseKanban::Board" => [
+ "Boards::Board" => [
{ type: :group, id: Group::AUTO_GROUPS[:admins], permission: "manage" },
],
},
banned_acl: {
- "DiscourseKanban::Board" => [
+ "Boards::Board" => [
{ type: :group, id: Group::AUTO_GROUPS[:anonymous_users], permission: "edit" },
],
},
@@ -166,6 +168,6 @@ When migrating legacy permission columns into ACLs:
## 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` remains group-first: it does not yet provide user picking or complete user ACL editing, even though backend rows can contain `allowed_user_ids`.
+- `DAccessControl` supports user/group search and user grants. Mandatory ACL injection remains group-first; targets with 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.
diff --git a/.skills/discourse-acl-authoring/references/testing-and-review.md b/.skills/discourse-acl-authoring/references/testing-and-review.md
index 4dd6a0da473..487d6365037 100644
--- a/.skills/discourse-acl-authoring/references/testing-and-review.md
+++ b/.skills/discourse-acl-authoring/references/testing-and-review.md
@@ -7,6 +7,7 @@ Use this reference when adding specs or reviewing ACL-backed features.
For target models:
- Include `AclTarget`.
+- Define or inherit `ACL_PERMISSIONS` using `Acl::Permissions`; use named readers in mandatory, banned, and loss-warning declarations.
- 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`.
@@ -30,6 +31,9 @@ For Guardian methods:
For services using `AccessControlListManager`:
+- 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 with `acl: []` persists mandatory ACLs or fails closed when no mandatory ACL exists.
- Update with explicit `acl: []` replaces existing ACLs with mandatory ACLs.
@@ -68,6 +72,7 @@ For migration specs:
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.
- 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.
@@ -90,6 +95,7 @@ Use `.skills/discourse-writing-js-tests` for QUnit patterns.
Ask these questions during code review:
- Is every ACL write routed through `AccessControlListManager`?
+- 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 service distinguish omitted ACL params from explicit empty ACL params when that matters?
- Are mandatory ACLs enforced in both backend writes and frontend display?
@@ -107,8 +113,7 @@ Ask these questions during code review:
## Known Sharp Edges
- `AccessControlListManager` currently assumes caller-side authorization.
-- Backend user ACL support is partial: expansion, flattening, preloading, lookup helpers, matching scopes, and cleanup jobs handle `allowed_user_ids`, but shared UI authoring is not complete.
-- `DAccessControl` remains group-first and does not provide complete user ACL editing yet.
+- Backend storage/lookups and the frontend search picker support user grants; 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.
- `DAccessControlField` cancellation leaves the proposed ACL in draft state. `preventSubmit` is not a rollback API.
diff --git a/.skills/discourse-writing-rspec-tests/SKILL.md b/.skills/discourse-writing-rspec-tests/SKILL.md
index ea9a021b73b..3a06ae94e42 100644
--- a/.skills/discourse-writing-rspec-tests/SKILL.md
+++ b/.skills/discourse-writing-rspec-tests/SKILL.md
@@ -19,6 +19,7 @@ Discourse uses RSpec for testing. Follow these patterns for all test types.
- **Choose the smallest fitting test primitive** — use `fab!` for records shared across examples, `let` for lazy per-example values, `let!` when a per-example record must exist before the action, and `subject` for the operation under test. Use inline `Fabricate` for a record local to one example. Because `fab!` uses TestProf `let_it_be`, it cannot depend on `let` or other per-example setup. Keep `let` value-oriented rather than hiding a parameterized helper in a Proc or lambda. When parameterized behavior needs a name to keep one spec readable, define a small method in that example group; do not introduce one merely to wrap a simple `Fabricate`, `create!`, or direct call. Move the method into a focused, auto-loaded `spec/support` module only when it is shared by multiple spec files. Search `spec/fabricators` before creating setup by hand, and define a derived fabricator for a recurring record shape.
- **Test edge cases** — nil inputs, empty collections, boundary values, permission failures — not just happy paths.
- **Keep tests independent** — no test should depend on another test's execution or shared mutable state.
+- Use `stub_const(target, :CONSTANT, value) { ... }` for temporary constants rather than `const_set` and manual cleanup. Use an `around` hook when the constant is needed throughout an example; the helper restores existing constants and removes newly introduced ones.
- **Verify placement in parent context** — before adding a new test, always read the surrounding `describe`/`context` block to confirm the test belongs there. Check that the parent context's description, `let`/`fab!` setup, and `before` hooks match the scenario being tested. A misplaced test inherits the wrong setup and produces misleading results.
- **Arrange-Act-Assert** — clear separation of setup, action, and verification in each test.
- **Don't test framework behavior** — don't test that Rails validations work; test your business logic.
diff --git a/app/services/access_control_list_manager.rb b/app/services/access_control_list_manager.rb
index e25ad14afed..f2eaf8d4e3f 100644
--- a/app/services/access_control_list_manager.rb
+++ b/app/services/access_control_list_manager.rb
@@ -19,6 +19,7 @@ class AccessControlListManager
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
@@ -47,6 +48,11 @@ class AccessControlListManager
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) }
diff --git a/lib/acl/permissions.rb b/lib/acl/permissions.rb
new file mode 100644
index 00000000000..0960ef9f958
--- /dev/null
+++ b/lib/acl/permissions.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module Acl
+ class Permissions
+ attr_reader :values
+
+ def initialize(*permissions)
+ @values = permissions.map { |permission| permission.to_s.freeze }.uniq.freeze
+
+ @values.each do |permission|
+ if !permission.match?(/\A[a-z][a-z0-9_]*\z/) || respond_to?(permission, true)
+ raise ArgumentError, "Invalid ACL permission name: #{permission}"
+ end
+
+ define_singleton_method(permission) { permission }
+ end
+
+ freeze
+ end
+ end
+end
diff --git a/plugins/boards/app/models/boards/board.rb b/plugins/boards/app/models/boards/board.rb
index 6c106756d1a..de1187a7619 100644
--- a/plugins/boards/app/models/boards/board.rb
+++ b/plugins/boards/app/models/boards/board.rb
@@ -4,6 +4,8 @@ module Boards
class Board < ActiveRecord::Base
include ::AclTarget
+ ACL_PERMISSIONS = Acl::Permissions.new(:view, :edit, :manage)
+
self.table_name = "discourse_kanban_boards"
self.ignored_columns = %w[
base_filter_query
@@ -36,22 +38,30 @@ module Boards
before_validation :normalize_slug
def self.mandatory_acl
- [{ type: :group, id: Group::AUTO_GROUPS[:admins], permission: "manage" }]
+ [{ type: :group, id: Group::AUTO_GROUPS[:admins], permission: ACL_PERMISSIONS.manage }]
end
def self.banned_acl
[
- { type: :group, id: Group::AUTO_GROUPS[:anonymous_users], permission: "manage" },
- { type: :group, id: Group::AUTO_GROUPS[:anonymous_users], permission: "edit" },
+ {
+ type: :group,
+ id: Group::AUTO_GROUPS[:anonymous_users],
+ permission: ACL_PERMISSIONS.manage,
+ },
+ {
+ type: :group,
+ id: Group::AUTO_GROUPS[:anonymous_users],
+ permission: ACL_PERMISSIONS.edit,
+ },
# Essentially a legacy group ID, don't want anyone to use it.
- { type: :group, id: Group::AUTO_GROUPS[:everyone], permission: "manage" },
- { type: :group, id: Group::AUTO_GROUPS[:everyone], permission: "edit" },
- { type: :group, id: Group::AUTO_GROUPS[:everyone], permission: "view" },
+ { type: :group, id: Group::AUTO_GROUPS[:everyone], permission: ACL_PERMISSIONS.manage },
+ { type: :group, id: Group::AUTO_GROUPS[:everyone], permission: ACL_PERMISSIONS.edit },
+ { type: :group, id: Group::AUTO_GROUPS[:everyone], permission: ACL_PERMISSIONS.view },
]
end
def self.loss_warning_permissions
- ["manage"]
+ [ACL_PERMISSIONS.manage]
end
def url
@@ -59,13 +69,16 @@ module Boards
end
def anonymous_can_read?
- permission_acl.group_has_permission?(Group::AUTO_GROUPS[:anonymous_users], "view")
+ permission_acl.group_has_permission?(
+ Group::AUTO_GROUPS[:anonymous_users],
+ ACL_PERMISSIONS.view,
+ )
end
def logged_in_user_can_read?
permission_acl.group_has_any_permission?(
Group::AUTO_GROUPS[:logged_in_users],
- %w[view edit manage],
+ ACL_PERMISSIONS.values,
)
end
diff --git a/plugins/boards/config/locales/server.en.yml b/plugins/boards/config/locales/server.en.yml
index 8eb825851fd..b2c31d4472f 100644
--- a/plugins/boards/config/locales/server.en.yml
+++ b/plugins/boards/config/locales/server.en.yml
@@ -7,6 +7,10 @@ en:
"Boards::Board_user_will_lose_permission": "You will lose permissions to manage this board if you make this change. Continue?"
"Boards::Board_user_will_lose_permission_on_create": "If you create this board with these permissions, you will not be able to manage it. Continue?"
boards:
+ board:
+ errors:
+ acl_update_failed: "Failed to update board permissions."
+ acl_create_failed: "Failed to create board permissions."
errors:
board_not_found: "Board not found"
board_read_forbidden: "You do not have permission to view this board"
diff --git a/plugins/boards/spec/requests/boards/boards_controller_spec.rb b/plugins/boards/spec/requests/boards/boards_controller_spec.rb
index 7f3ecee0ebe..981b4447ade 100644
--- a/plugins/boards/spec/requests/boards/boards_controller_spec.rb
+++ b/plugins/boards/spec/requests/boards/boards_controller_spec.rb
@@ -514,7 +514,63 @@ RSpec.describe Boards::Api::BoardsController do
end
end
- describe "POST /boards/api/boards" do
+ describe "#create" do
+ it "accepts all supported ACL permissions and retains mandatory admin access" do
+ sign_in(manager)
+
+ post "/boards/api/boards.json",
+ params: {
+ board: {
+ name: "Permission board",
+ slug: "permission-board",
+ acl: [
+ { type: "group", id: read_group.id, permission: "view" },
+ { type: "group", id: write_group.id, permission: "edit" },
+ { type: "group", id: manage_group.id, permission: "manage" },
+ ],
+ },
+ }
+
+ expect(response.status).to eq(201)
+ board = Boards::Board.find(response.parsed_body["board"]["id"])
+ expect(
+ AccessControlList.where(target: board).pluck(:permission, :allowed_group_ids),
+ ).to contain_exactly(
+ ["view", [read_group.id]],
+ ["edit", [write_group.id]],
+ ["manage", [manage_group.id, Group::AUTO_GROUPS[:admins]]],
+ )
+ end
+
+ it "rejects an invalid permission name without creating a board, columns, or ACLs" do
+ sign_in(manager)
+
+ expect do
+ post "/boards/api/boards.json",
+ params: {
+ board: {
+ name: "Invalid permissions",
+ slug: "invalid-permissions",
+ columns: [{ title: "Backlog" }],
+ acl: [
+ { type: "group", id: read_group.id, permission: "view" },
+ { type: "group", id: manage_group.id, permission: "bogus" },
+ ],
+ },
+ }
+ end.not_to change {
+ [
+ Boards::Board.count,
+ Boards::Column.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" do
sign_in(manager)
@@ -557,7 +613,61 @@ RSpec.describe Boards::Api::BoardsController do
end
end
- describe "PUT /boards/api/boards/:id" do
+ describe "#update" do
+ fab!(:acl_board) do
+ Fabricate(:boards_board, created_by: admin, additional_manage_groups: [manage_group])
+ end
+
+ it "accepts all supported ACL permissions and retains mandatory admin access" do
+ sign_in(manager)
+
+ put "/boards/api/boards/#{acl_board.id}.json",
+ params: {
+ board: {
+ acl: [
+ { type: "group", id: read_group.id, permission: "view" },
+ { type: "group", id: write_group.id, permission: "edit" },
+ { type: "group", id: manage_group.id, permission: "manage" },
+ ],
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(
+ AccessControlList.where(target: acl_board).pluck(:permission, :allowed_group_ids),
+ ).to contain_exactly(
+ ["view", [read_group.id]],
+ ["edit", [write_group.id]],
+ ["manage", [manage_group.id, Group::AUTO_GROUPS[:admins]]],
+ )
+ end
+
+ it "rejects an invalid permission name and preserves the board and its existing ACLs" do
+ sign_in(manager)
+ previous_attributes = acl_board.attributes
+ previous_acls = AccessControlList.where(target: acl_board).order(:id).map(&:attributes)
+
+ expect do
+ put "/boards/api/boards/#{acl_board.id}.json",
+ params: {
+ board: {
+ name: "Invalid update",
+ acl: [
+ { type: "group", id: read_group.id, permission: "view" },
+ { type: "group", id: manage_group.id, permission: "bogus" },
+ ],
+ },
+ }
+ end.not_to change { Boards::BoardHistory.count }
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["failed"]).to eq("FAILED")
+ expect(acl_board.reload.attributes).to eq(previous_attributes)
+ 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" do
board =
Fabricate(
diff --git a/spec/lib/acl/permissions_spec.rb b/spec/lib/acl/permissions_spec.rb
new file mode 100644
index 00000000000..641ecef86ed
--- /dev/null
+++ b/spec/lib/acl/permissions_spec.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+RSpec.describe Acl::Permissions do
+ subject(:permissions) { described_class.new(:view, :edit, :manage) }
+
+ describe "#values" do
+ it "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 be_frozen
+ expect(permissions.values).to all(be_frozen)
+ end
+ end
+
+ describe "named readers" do
+ it "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)
+ end
+
+ it "raises for an undeclared permission" do
+ expect { permissions.jester }.to raise_error(NoMethodError)
+ end
+
+ it "freezes the declaration" do
+ expect(permissions).to be_frozen
+ expect { permissions.define_singleton_method(:view) { "Jester" } }.to raise_error(FrozenError)
+ end
+ end
+
+ describe ".new" do
+ it "rejects names that cannot be permission readers" do
+ ["", "two words", "1view", "view-edit", "view="].each do |name|
+ expect { described_class.new(name) }.to raise_error(ArgumentError)
+ end
+ end
+
+ it "rejects names that conflict with existing methods" do
+ %i[values class freeze to_s initialize].each do |name|
+ expect { described_class.new(name) }.to raise_error(ArgumentError)
+ end
+ end
+ end
+end
diff --git a/spec/models/concerns/acl_target_spec.rb b/spec/models/concerns/acl_target_spec.rb
index fa5d5b5f1e0..79a91b2424f 100644
--- a/spec/models/concerns/acl_target_spec.rb
+++ b/spec/models/concerns/acl_target_spec.rb
@@ -13,6 +13,10 @@ RSpec.describe AclTarget do
end
end
+ around do |example|
+ stub_const(target_class, :ACL_PERMISSIONS, Acl::Permissions.new(:view, :edit)) { example.run }
+ end
+
it "adds mandatory acl class methods" do
expect(target_class).to respond_to(:has_mandatory_acl?, :acl_is_mandatory?)
end
diff --git a/spec/requests/access_control_lists_controller_spec.rb b/spec/requests/access_control_lists_controller_spec.rb
index 17e73834ccd..246bd14073c 100644
--- a/spec/requests/access_control_lists_controller_spec.rb
+++ b/spec/requests/access_control_lists_controller_spec.rb
@@ -8,6 +8,8 @@ RSpec.describe AccessControlListsController do
self.table_name = "posts"
+ ACL_PERMISSIONS = Acl::Permissions.new(:view, :edit, :manage)
+
def self.acl_target_key
"evaluate_modification_request_test_target"
end
diff --git a/spec/serializers/site_serializer_spec.rb b/spec/serializers/site_serializer_spec.rb
index 3a014769752..ff9b7398965 100644
--- a/spec/serializers/site_serializer_spec.rb
+++ b/spec/serializers/site_serializer_spec.rb
@@ -112,6 +112,12 @@ RSpec.describe SiteSerializer do
end
end
+ around do |example|
+ stub_const(target_class, :ACL_PERMISSIONS, Acl::Permissions.new(:edit, :manage)) do
+ example.run
+ end
+ end
+
after { DiscoursePluginRegistry.reset_register!(:acl_target_classes) }
it "includes mandatory ACLs by target class" do
@@ -139,22 +145,21 @@ RSpec.describe SiteSerializer do
end
it "includes plugin-registered target classes" do
- Object.const_set(:SiteSerializerSpecTarget, target_class)
- AclTarget.loaded_target_classes.delete(target_class)
- DiscoursePluginRegistry.register_acl_target_class(
- "SiteSerializerSpecTarget",
- Plugin::Instance.new,
- )
+ stub_const(Object, :SiteSerializerSpecTarget, target_class) do
+ AclTarget.loaded_target_classes.delete(target_class)
+ DiscoursePluginRegistry.register_acl_target_class(
+ "SiteSerializerSpecTarget",
+ Plugin::Instance.new,
+ )
- serialized = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json
+ serialized = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json
- expect(serialized.dig(:access_control, :mandatory_acl)).to include(
- "SiteSerializerSpecTarget" => [
- { type: :group, id: Group::AUTO_GROUPS[:admins], permission: "manage" },
- ],
- )
- ensure
- Object.send(:remove_const, :SiteSerializerSpecTarget) if defined?(SiteSerializerSpecTarget)
+ expect(serialized.dig(:access_control, :mandatory_acl)).to include(
+ "SiteSerializerSpecTarget" => [
+ { type: :group, id: Group::AUTO_GROUPS[:admins], permission: "manage" },
+ ],
+ )
+ end
end
end
diff --git a/spec/services/access_control_list/evaluate_modification_spec.rb b/spec/services/access_control_list/evaluate_modification_spec.rb
index 0b009037341..7a160f65c5a 100644
--- a/spec/services/access_control_list/evaluate_modification_spec.rb
+++ b/spec/services/access_control_list/evaluate_modification_spec.rb
@@ -25,6 +25,8 @@ RSpec.describe AccessControlList::EvaluateModification do
self.table_name = "posts"
+ ACL_PERMISSIONS = Acl::Permissions.new(:view, :edit, :manage)
+
def self.mandatory_acl
[{ type: :group, id: Group::AUTO_GROUPS[:admins], permission: "manage" }]
end
diff --git a/spec/services/access_control_list_manager_spec.rb b/spec/services/access_control_list_manager_spec.rb
index 0cd53ba3b71..323b940b6b0 100644
--- a/spec/services/access_control_list_manager_spec.rb
+++ b/spec/services/access_control_list_manager_spec.rb
@@ -9,6 +9,15 @@ RSpec.describe AccessControlListManager do
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
@@ -54,6 +63,82 @@ RSpec.describe AccessControlListManager do
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 }
diff --git a/spec/support/helpers.rb b/spec/support/helpers.rb
index a96fe5e26ad..14f60db71f9 100644
--- a/spec/support/helpers.rb
+++ b/spec/support/helpers.rb
@@ -223,13 +223,14 @@ module Helpers
end
def stub_const(target, const, value)
- old = target.const_get(const)
- target.send(:remove_const, const)
+ previously_defined = target.const_defined?(const, false)
+ old = target.const_get(const, false) if previously_defined
+ target.send(:remove_const, const) if previously_defined
target.const_set(const, value)
yield
ensure
target.send(:remove_const, const)
- target.const_set(const, old)
+ target.const_set(const, old) if previously_defined
end
def track_sql_queries