# Permissions Camaleon CMS defines role permissions in two families, both rendered in the User Roles form in the admin UI so site owners can toggle them per-role: - **Manager permissions** — `CamaleonCms::UserRole::ROLES[:manager]`, stored in a role's `_manager_` meta, and site-wide in scope. They become abilities through `Ability#define_manage_rules`, which grants `can :manage, ` for any key present and truthy in that meta. Checked as `can?(:manage, :key)`. - **Post-type permissions** — `CamaleonCms::UserRole::ROLES[:post_type]`, stored in `_post_type_`, and scoped to a list of post type IDs. Checked by passing a concrete post type, e.g. `can?(:post_content_unfiltered_html, post_type)`. Users with the `admin` role satisfy every check through `can :manage, :all` in the Ability class, independently of role meta. ## The gating rule Every permission on this page is an instance of one rule, and a new security-sensitive capability MUST follow it: 1. **Administrators can do anything.** The `admin` role satisfies every check through `can :manage, :all`, before any role meta is read. 2. **For every other role, an action that presents a security threat is allowed only through a dedicated permission that is off by default.** The permission is never seeded onto a non-admin role, so an existing install reads it as not-granted with no migration; and the check **fails closed** — with no `CurrentRequest` user or site (a background job, a rake task, the console), the caller is treated as untrusted. 3. **A gate is the last resort, not the first.** Where the threat is *content* and that content can be judged, the save-time scan judges it (see the remedy rule below) — a blanket refusal by file type, format or category is wrong there. A dedicated permission is the remedy only where no scan can reach a verdict at all. Uploaded JavaScript is the worked example: it has no safe subset and every dangerous capability is reachable through dynamic construction (`window['fet'+'ch']`, `[]['constructor']['constructor']`), so no static rule decides it and the check fails closed. Uploaded markup is the counter-example: it has a finite grammar, so the parse-based scan decides it and `.html` is deliberately *not* gated by type. Where an existing permission's holders already possess the capability, extend that permission rather than adding one — a new permission would *revoke* the capability from installs that already granted the old one. `media_unfiltered_upload` covers script uploads for exactly this reason: a holder already skips the scan and could already store them. The gate is an **authorization** decision, never a proxy for one. A filesystem path, an output filename, a client-supplied flag or a network location can each be walked through by the caller; [#1228](https://github.com/owen2345/camaleon-cms/pull/1228) replaced exactly such a path-based upload exemption with `media_unfiltered_upload` for that reason. Where content can be substituted after the check — a `before_upload` handler rewriting the scanned bytes — the substituted content is re-checked, not trusted because the handler ran. A check that fails *open* (allowing the action when it cannot evaluate the permission) is the bug this rule exists to prevent. **Adding a new gated capability** — the four documented below are the templates: 1. Add the key to `UserRole::ROLES[:manager]` (site-wide) or `ROLES[:post_type]` (per post type) with `color: 'danger'` and an i18n label/description. 2. Gate the dangerous work behind a predicate that mirrors `Post#trusted_for_unfiltered_html?` or `CamaleonCms::UploaderContentSecurity#cama_trusted_for_unfiltered_upload?`: read `CurrentRequest.user` and `CurrentRequest.site`, return false if either is blank, otherwise ask `CamaleonCms::Ability`, and `rescue StandardError` to false. Check it *before* doing the work. 3. Seed no non-admin role with the key. For a **post-type** permission, also add `next if key == ''` to the Editor post-type seeding in `site_default_settings.rb`, which otherwise grants every post-type key. 4. Ship a spec that reproduces the threat (per `AGENTS.md`) and covers the admin-allowed, non-admin-refused, granted-allowed and no-request-context-refused cases. The convention is specified as `openspec/specs/security-capability-gating/spec.md`. ## The remedy rule: reject, don't transform The gating rule says *who* may perform a dangerous action; this rule says what happens when an untrusted user submits dangerous **content**: the save is **refused with an error naming the problem** — the content is never sanitized, stripped, escaped-away, or otherwise rewritten (maintainer decision, 2026-08-13). Four properties follow, and every content gate relies on them: 1. **Stored content always equals authored content.** What the gate admitted is byte-for-byte what the author wrote, so the frontend may render it verbatim (`raw post.the_content`, editor and field_attrs custom-field values). There is no render-time sanitization anywhere: a transform at render would silently mutate a trusted author's work and mask gate regressions. 2. **Refusal is loud.** A sanitizer that silently drops markup surprises the author later and invites probing until a payload slips through; a refusal names the field and the remedy (remove the markup, or hold the relevant permission). 3. **History is reported, not rewritten.** Content stored before a gate existed is left untouched; `rake camaleon_cms:security:scan_content` lists everything today's gates would refuse so an operator can clean it up deliberately, and `rake camaleon_cms:security:scan_uploads` does the same for files already under the media root. 4. **The save-time decision is the only lever.** Content that passes the gate is stored *and served* verbatim. No response header, CSP, `X-Content-Type-Options`, `Content-Disposition`, separate media origin or other serving-side control constrains what a stored file does in the browser — a trusted user was permitted to store it, so it behaves exactly as they intended. This bounds the rule from below as the no-transform clause bounds it from above. The test before proposing any control: *would it constrain a trusted user's content?* If yes, it is outside this model whatever its merit as general security hygiene. The pieces that implement the rule: - **`CamaleonCms::UnsafeMarkup`** (`lib/camaleon_cms/unsafe_markup.rb`) is the shared detector for authored markup: one parse, safe-list scrub compared against the parse's own reserialization (only genuine removals register), plus structural guards — markup the parser drops or leaves open, a translation marker inside a tag, and markup smuggled through an attribute value (a value that entity-decodes to a tag-open, which a client-side `data-html` sink would inject). It bounds value size (an over-size value is refused, and callers report it with a size-specific message) and yields a verdict for mis-encoded input rather than raising. It mirrors the cama_contact_form gate — keep the two in parity. Scan the content **the renderer will emit**, not the stored encoding: `CustomFieldsRelationship.gate_rejection_reason` decodes every member of a `field_attrs` value's JSON (any shape — object, array, nested) before scanning, because the JSON encoder hides `<` behind unicode escapes, and the same class-level dispatch backs the `scan_content` audit task so the two cannot drift. - **Gates sit on models** (`Post#reject_untrusted_dangerous_content`, `CustomFieldsRelationship#reject_untrusted_dangerous_value`), so no controller path can skip them; the admin post save wraps the parent and its field values in one transaction, so a refused value rolls the whole save back rather than leaving a half-applied post. Positions the platform escapes by default (plain `<%= %>` output of non-markup values) carry no gate — that is the platform's normal output encoding, not a remedy. - **Trust and fail-closed follow the gating rule above**: admins always pass; non-admins pass through the dedicated permission (`post_content_unfiltered_html` for a post's content and its gated field values); no request context means the gate applies. Trusted server-side pipelines opt out explicitly per record (`Post#unfiltered_content!`, `CustomFieldsRelationship#unfiltered_value!` — bang enablers with no writers, unreachable by mass assignment). - **Uploads already follow the rule** (`svg-upload-sanitization`, `upload-content-security`: scan and refuse, with `media_unfiltered_upload` as the trusted skip). The rule is codified as a requirement in `openspec/specs/security-capability-gating/spec.md`. ## The admin role Because administrators can do anything (rule 1 above), the `admin` role is the most powerful grant on a site. Three properties of it matter to operators: - **Only an admin may grant or remove it.** Holding the `users` manager permission (`can?(:manage, :users)`) lets a role create and edit user accounts and assign roles, but it is **not** a path to superadmin. Assigning a user the `admin` role — the role `User#admin?` tests, which maps to `can :manage, :all` — or changing the role of a user who is *already* an admin, is permitted only when the acting user is themselves an admin. This is enforced server-side in `CamaleonCms::UserDecorator#role_grantor?` and applied by `Admin::UsersController#user_params` (the user form also hides the `admin` option, and disables the role selector, for anyone who cannot grant it). A non-admin user manager can still assign every non-admin role. Pinned by `openspec/specs/admin-role-grant-authorization/spec.md`. - **Only an admin may edit an admin's account.** The role restriction alone would not close the escalation: a `:manage, :users` holder who could reset an admin's password would simply sign in as that admin, and one who could repoint the admin's email would hijack a password-reset link. Changing an existing admin's password or recovery identifiers (email/username) therefore also requires being an admin. This is enforced server-side in `CamaleonCms::UserDecorator#may_edit_credentials?`, applied by `Admin::UsersController#user_params` and `#updated_ajax` (the user form likewise disables those inputs and hides the change-password action for anyone who cannot use them). A non-admin user manager keeps full control of every non-admin account, and of their own — only other admins are off-limits. - **It is global, not per-site.** `User#admin?` is `role == 'admin'` with no site scope, so a user with the `admin` role administers **every** site in the installation — most visibly when `users_share_sites` is enabled and all users are shared across sites. Treat granting `admin` as granting site-wide superadmin across the whole install, not just the current site. Per-site administration would require a per-`(user, site)` role model and is not currently supported. Editing another user's account at all requires `:manage, :users`; the admin-only rules above are exceptions layered on top of that base boundary. The boundary holds at every write path, not only the user form: `Admin::MediaController#crop` gates its `saved_avatar` avatar write on `:manage, :users` for any non-self target — a caller may set **their own** avatar with only `:manage, :media`, but not another user's — so the media library cannot be used to edit another user's profile without the user-management permission. As on the profile endpoint, the decision is read from the request parameter before the target is resolved, so it discloses nothing about which users exist. ## Manager permissions - `custom_fields` — Controls who can create/update Custom Field Groups and Custom Fields (write-time permission). This is a manager-level permission and should be granted only to trusted users. The permission is checked at write-time by the admin controller so that only permitted roles can persist custom field definitions that may contain advanced behavior. - `contact_form_unfiltered_html` — Permits storing raw HTML anywhere in the bundled contact-form plugin. Without it, a save carrying such content is refused rather than rewritten. See [Security: Unfiltered HTML](#security-unfiltered-html) below. - `media_unfiltered_upload` — Permits uploading files without the malicious-content scan. Without it, every upload is scanned whatever its source, and a file carrying scripts, event handlers, blocked elements or blocked URI schemes is refused rather than cleaned up. See [Security: Unfiltered HTML](#security-unfiltered-html) below. Where enforcement happens - Write-time enforcement: `CamaleonCms::Admin::Settings::CustomFieldsController` uses CanCan (`authorize! :manage, :custom_fields`) to require the `custom_fields` manager permission for create/update/destroy actions. This prevents users without the permission from saving Custom Field Groups or fields. - Render-time behavior: certain field types (notably the `select_eval` field) evaluate stored data when rendering. The project maintains render-time behavior for backward compatibility, but write-time restrictions are the primary control: only users with the `custom_fields` permission can create or modify fields that might include executable commands. If you need a more restrictive runtime policy, consider auditing/clearing any stored `select_eval` commands in the database. ### Security: select_eval Custom Field Type The `select_eval` custom field type is **restricted due to security concerns** as it can execute arbitrary Ruby code. Starting from version 2.9.2, explicit permission is required to create or modify `select_eval` fields. **For Administrators:** - Users with the 'admin' role automatically have full access to all custom field types including `select_eval` - This access is granted through `can :manage, :all` in the Ability class, not through role meta - Note: The Admin role's "Select Eval" checkbox in the UI will remain unchecked (this is expected behavior) - Client users are restricted by default **For Custom Roles:** To grant `select_eval` permission to a non-admin role: ```ruby # Via Rails console or application code role = site.user_roles.find_by(slug: 'editor') current_meta = role.get_meta("_manager_#{site.id}", {}) role.set_meta("_manager_#{site.id}", current_meta.merge(select_eval: 1)) ``` **Via Admin UI:** 1. Navigate to Settings → User Roles 2. Edit the desired role 3. Check the "Select Eval" permission under Manager Permissions 4. Save the role **Security Implications:** ⚠️ **WARNING**: The `select_eval` field type can execute arbitrary Ruby code. Only grant this permission to **fully trusted users** who understand the security implications. Example of dangerous usage: ```ruby # A malicious select_eval command could do: `rm -rf /` # System command execution User.destroy_all # Database destruction ENV['SECRET_KEY_BASE'] # Access to sensitive data ``` **Best Practices:** - Only grant `select_eval` permission to site administrators or developers - Regularly audit users with this permission - Consider removing `select_eval` fields from production sites if not actively needed - Use alternative field types (select, radio, checkbox) when possible **For Existing Installations:** If upgrading from a version prior to 2.9.2, you can use this rake task to ensure admin roles have the `select_eval` permission: ```bash # Run from your application root bundle exec rake camaleon_cms:backfill_select_eval_permission # This task does NOT grant new permissions to admins (they already have all permissions by design via `can :manage, :all`). # It only corrects the display of the select_eval checkbox for admin roles in the UI, so it appears enabled as expected. ``` This task is idempotent and safe to run multiple times. **Note:** Custom roles (e.g., 'editor', 'contributor') will need manual permission grants via Rails console or the Admin UI if they require `select_eval` access. **Background Jobs & Console Usage:** When creating `select_eval` fields from background jobs or Rails console, you must set the user context: ```ruby # In a background job or console user = User.find_by(username: 'admin') site = Site.first CurrentRequest.user = user CurrentRequest.site = site # Now you can create select_eval fields group.add_field({ name: 'My Field', slug: 'my_field' }, { field_key: 'select_eval', command: 'my_command' }) # Clean up CurrentRequest.reset ``` Backfilling existing roles - If you are upgrading an existing installation to `2.9.2`, see the [migration guide](../upgrading-to-2.9.2.md) for the one-off backfill task and rollout steps. Security notes - The `custom_fields` manager permission can allow storing code-like commands (e.g., `select_eval`) - Treat `custom_fields` as a high-privilege permission — grant it only to trusted administrators. If you inherit a database with pre-existing `select_eval` fields, audit their contents before granting the permission widely ## Security: Unfiltered HTML Camaleon restricts the HTML a role may store, and three permissions lift that restriction. **They are different permissions with similar names**, they do not all live in the same family, and holding one does not grant the others. All three are introduced in 2.9.3. They also work differently, which matters when you are deciding who to grant them to. Post content is **sanitized**: an untrusted author's save succeeds and the disallowed markup is quietly removed. Contact forms and uploads are **refused**: an untrusted author's save or upload does not happen at all. Nothing in a contact form or an uploaded file is ever rewritten. | | `post_content_unfiltered_html` | `contact_form_unfiltered_html` | `media_unfiltered_upload` | |---|---|---|---| | Family | post-type (`ROLES[:post_type]`) | manager (`ROLES[:manager]`) | manager (`ROLES[:manager]`) | | Role meta | `_post_type_` | `_manager_` | `_manager_` | | Scope | per post type | all contact forms on the site | all uploads on the site | | Checked as | `can?(:post_content_unfiltered_html, post_type)` | `can?(:manage, :contact_form_unfiltered_html)` | `can?(:manage, :media_unfiltered_upload)` | | Without it | `Post#content` is sanitized on save | the save is refused; nothing is stored | the upload is refused; nothing is stored | | Covers | `Post#content` | every contact-form value that reaches the page | every upload, whatever its source | | Introduced in | [#1206](https://github.com/owen2345/camaleon-cms/pull/1206) | [#1215](https://github.com/owen2345/camaleon-cms/pull/1215) | [#1228](https://github.com/owen2345/camaleon-cms/pull/1228) | ⚠️ **WARNING**: all three permissions let a role publish markup that is later served without escaping — including `