Sari la conținutul principal
GratuitUn audit al site-ului tău DrupalUn audit scris al site-ului tău Drupal, în trei zile lucrătoare
Toate articolele

Backend și inginerie3 noiembrie 20269 min de citit

Capabilities: permission bundles and scoped access for Drupal

Valentin ZsigmondFondator și inginer principal

Drupal's permission system answers one question very well: may this person do this kind of thing on this site? It has two weak spots. A site with a few dozen modules has hundreds of permissions, and one job, such as publishing articles, often needs ten or twelve of them ticked on a very long page. And it cannot say "this person may edit pages in this project only".

We wrote Capabilities for both. It is a Drupal module (drupal/capabilities, GPL-2.0-or-later) built on the access policy API that core introduced in Drupal 10.3. A capability is a named bundle of access that people assign as one thing: "Publish articles" for the whole site, or "Manage members" in one project. The examples use its 1.0.x branch, which requires Drupal 11.3 and PHP 8.3.

The Capabilities logo: a shield with the Drupal drop and a check mark

Why roles alone do not say "editor of this project only"

A role is site-wide. If the Editor role has edit any project_page content, every editor can edit every project page on the site. A role carries no reference to a particular project, so "editor of project 12, viewer of project 40" has no direct way to be written down.

The common workarounds each cost something. One role per project grows the role list with every new project and turns content into configuration. Hand-written checks such as "is this user in the project's members field?" work, but the rule ends up spread across controllers, access hooks and templates, each with its own idea of caching. What we wanted was one place that states what a user may do within each project, cached like core permissions and refreshed when membership changes.

Access policies: permissions with a scope and an identifier

Core calculates permissions through access policies. A policy is a service tagged access_policy that implements AccessPolicyInterface, usually by extending AccessPolicyBase. The access_policy_processor service asks every policy that applies() to a scope for its calculatePermissions(), merges the results, lets each policy alterPermissions(), and caches the outcome.

The result is a set of CalculatedPermissionsItem objects. Each item holds a list of permissions, an admin flag, a scope and an identifier. Core's role policy produces items in the drupal scope with the identifier drupal, which is why ordinary permission checks look unchanged. Another policy can produce items in the scope capabilities.project with the identifier 12. That is exactly "these permissions, in project 12".

Capabilities works in both kinds of scope. In the drupal scope, a capability adds the ordinary permissions it stands for, so every existing permission check keeps working. In its own scopes, those starting with capabilities., it collects grants from providers in your modules, checks them against the declared capabilities, and hands the result to core. The module knows nothing about your projects either way.

Declaring capabilities

A capability is a stable machine name with a scope and a label. A module declares its capabilities in a my_module.capabilities.yml file, the way core modules declare permissions, and implies lets one capability bring others with it. These are the scoped ones for a project:

project.view:
  scope: capabilities.project
  label: 'View the project'
project.edit:
  scope: capabilities.project
  label: 'Edit project pages'
  group: Content
  implies: [project.view]
project.manage:
  scope: capabilities.project
  label: 'Manage members'
  group: Administration
  description: 'Add and remove people in this project.'
  implies: [project.edit]

Labels, groups and descriptions are translated like any other interface text. A list that cannot be written down in advance comes from a callback, named under capability_callbacks: in the same file.

Only declared capabilities can ever be granted. When a provider grants project.manage, the module expands it to project.edit and project.view, following implications transitively and stopping at cycles. Any key nobody declared is dropped. Declarations from all modules are merged into one list, so choose keys specific enough that two modules will not pick the same one.

One capability instead of a dozen permissions

In the drupal scope, a capability lists the permissions it stands for:

content.review:
  scope: drupal
  label: 'Review articles'
  group: Content
  permissions:
    - 'access content overview'
    - 'view any unpublished content'
content.publish:
  scope: drupal
  label: 'Publish articles'
  group: Content
  description: 'Write, edit and publish articles.'
  permissions:
    - 'create article content'
    - 'edit any article content'
    - 'use editorial transition publish'
  implies: [content.review]

A role or a single user then gets "Publish articles" and with it every permission on both lists. Site builders can also define capabilities in the user interface; those are stored as configuration and deploy with the rest of the site. An overview page shows each capability, the permissions it grants and who holds it, through which role or directly, so "why can this person do this?" has an answer.

Handing out access in bigger pieces needs a few rules:

  • No escalation. Assigning capabilities needs its own permission, and nobody can assign a capability whose permissions they do not hold themselves. The module enforces this when the data is saved, not only in the forms.
  • Restricted permissions stay visible. A capability that includes one, such as administer users, is marked wherever it can be assigned, the way core marks it on the permissions page.
  • Missing permissions are reported. A capability can name a permission from a module that is not installed. It is never granted, and the status report lists it.

Granting a capability within a scope

Grants come from a provider: a service implementing CapabilityProviderInterface, with two methods. scope() names the scope it serves. calculate() returns every grant the account holds in that scope, one item per identifier, together with cache metadata that describes where the grants came from. In this example the memberships live in a custom table with one row per user, project and capability.

<?php

declare(strict_types=1);

namespace Drupal\my_module\Capability;

use Drupal\Core\Database\Connection;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\CalculatedPermissionsItem;
use Drupal\Core\Session\RefinableCalculatedPermissions;
use Drupal\Core\Session\RefinableCalculatedPermissionsInterface;
use Drupal\capabilities\CapabilityProviderInterface;

final class ProjectCapabilityProvider implements CapabilityProviderInterface {

  public function __construct(private readonly Connection $database) {}

  public function scope(): string {
    return 'capabilities.project';
  }

  public function calculate(AccountInterface $account): RefinableCalculatedPermissionsInterface {
    $result = (new RefinableCalculatedPermissions())
      ->addCacheTags(['my_module_project_member:' . $account->id()]);
    $rows = $this->database->select('my_module_project_member', 'm')
      ->fields('m', ['project_id', 'capability'])
      ->condition('m.uid', (int) $account->id())
      ->execute();
    foreach ($rows as $row) {
      $result->addItem(new CalculatedPermissionsItem([$row->capability], FALSE, $this->scope(), (int) $row->project_id));
    }
    return $result;
  }

}

Three details matter. The identifier is the project ID, so a grant in project 12 never answers for project 40. Core merges items that share a scope and identifier, so one item per row is fine. And the cache tag names the data this calculation read; we come back to it below.

Register the provider with the capabilities.provider tag. The policy picks up tagged services through a service collector, so nothing else is needed.

services:
  my_module.project_capabilities:
    class: Drupal\my_module\Capability\ProjectCapabilityProvider
    arguments: ['@database']
    tags:
      - { name: capabilities.provider }

A provider can also mark an item as admin. The module turns that into an explicit list of every capability declared for the scope, not a blanket pass, so an admin item still cannot grant a key that does not exist. A provider that returns an item for another scope causes a LogicException instead of leaking grants across applications.

Checking a capability

For routes, the module registers an access check for the _scoped_capability requirement. Route options name the scope and the route parameter that holds the identifier.

my_module.project_members:
  path: '/projects/{project}/members'
  defaults:
    _controller: '\Drupal\my_module\Controller\ProjectMembersController::list'
    _title: 'Members'
  requirements:
    _scoped_capability: 'project.manage'
    project: \d+
  options:
    capability_scope: 'capabilities.project'
    capability_parameter: 'project'

Separate alternatives with +: project.edit+project.manage allows either. The check reads the raw parameter, the ID as it appears in the path, so it does not depend on parameter upcasting. For a fixed identifier, use the capability_identifier option instead. A route that names no scope or no identifier is forbidden rather than quietly allowed.

In code, use the capabilities.resolver service. Its access() method returns an access result. Its resolve() method returns every declared capability in the scope mapped to true or false, which suits a page or a frontend component that needs to know which actions to offer. Here is the project page case from the start, as an entity access hook:

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Implements hook_entity_access().
 */
function my_module_entity_access(EntityInterface $entity, string $operation, AccountInterface $account): AccessResultInterface {
  if ($entity->getEntityTypeId() !== 'node' || $entity->bundle() !== 'project_page' || $operation !== 'update') {
    return AccessResult::neutral();
  }
  $project_id = (int) $entity->get('field_project')->target_id;
  $result = \Drupal::service('capabilities.resolver')
    ->access($account, 'capabilities.project', $project_id, 'project.edit');
  // The project reference can change, so the result depends on the node too.
  return AccessResult::neutral()->addCacheableDependency($entity)->orIf($result);
}

A missing grant gives a neutral result, not a forbidden one. Scoped grants add to what roles allow; they never take role permissions away, so a user whose role has edit any project_page content can still edit every project page. Removing permissions is a different job, and core's alterPermissions() is the place for it.

Cache contexts and dependencies that keep it correct

A permission cached wrongly is worse than a slow one. The module relies on core's caching and asks the provider to describe its data honestly.

  • Per user. The scoped policy declares user as its persistent cache context, so core stores one calculated set per user and scope. When you check an account other than the current user, the processor switches to that account while it reads and writes the cache, so the entry lands under the right user.
  • Persistent and tagged. The scoped policy does not implement core's CacheOptionalInterface, so core keeps the calculated permissions in its access policy cache, tagged with access_policies plus every tag the provider added. Without the provider's tag, a removed member would keep their grants until that cache is cleared some other way.
  • Carried into the result. CapabilityResolver::access() adds the calculated permissions as a cacheable dependency, plus the user context, and the route check adds url.path. A cached page or fragment that depends on the check is invalidated together with the grant.

So when a membership changes, invalidate the tag the provider used. A small service that owns the table can do both in one place:

namespace Drupal\my_module\Capability;

use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\Database\Connection;

final class ProjectMembership {

  public function __construct(
    private readonly Connection $database,
    private readonly CacheTagsInvalidatorInterface $cacheTagsInvalidator,
  ) {}

  public function grant(int $uid, int $project_id, string $capability): void {
    $this->database->merge('my_module_project_member')
      ->keys(['uid' => $uid, 'project_id' => $project_id, 'capability' => $capability])
      ->execute();
    $this->cacheTagsInvalidator->invalidateTags(['my_module_project_member:' . $uid]);
  }

  public function revoke(int $uid, int $project_id, string $capability): void {
    $this->database->delete('my_module_project_member')
      ->condition('uid', $uid)
      ->condition('project_id', $project_id)
      ->condition('capability', $capability)
      ->execute();
    $this->cacheTagsInvalidator->invalidateTags(['my_module_project_member:' . $uid]);
  }

}

Register it with @database and @cache_tags.invalidator, and route every change to the table through it. Grants that end at a known time can say so: call mergeCacheMaxAge() on the result in calculate() with the seconds left until the earliest expiry. One rule comes from core's own documentation: never use a cache context that depends on calculated permissions, such as user.permissions, inside a calculation, because it ends in a loop.

Limits and trade-offs

  • Calculation is per user, across the whole scope. calculate() returns grants for every identifier the account can reach. That suits people who belong to a handful of projects, and the result is cached after the first check. For accounts that reach a very large number of identifiers, keep an eye on the size of what gets cached.
  • Listings need their own query access. The module answers access checks. Showing only the projects a user may see in a View or an entity query is query alteration, and that still needs its own code.
  • Roles do not go away. A role can hold a few capabilities instead of a long list of permissions, and permissions given to a role directly keep working. Capabilities only add access, like roles do.
  • A typo denies. An undeclared key is never granted. That is the safe direction, but it fails quietly, so test an allowed and a denied account for every check. The module's own tests cover grants, implications, denied access and cache dependencies; your provider deserves a kernel test against real data, for the reasons in Kernel tests vs unit tests in Drupal.
  • Not released yet. The module is developed on the 1.0.x branch, and the API may still change before the first stable release. Ideas and bug reports are welcome in its issue queue.

The site owner's view of the same topic, roles, permissions and who changed what, is in Who can change what: roles, permissions and audit trails. If your application needs access per project, customer or team and you would like a second pair of eyes on the design, talk to us.

Scris de

Valentin Zsigmond

Fondator și inginer principal

Arhitect Drupal full-stack cu aproape două decenii de experiență în conducerea unor echipe mari în medii enterprise. A fondat Tilizy Digital pentru a aduce expertiză de nivel senior direct organizațiilor care au nevoie de ea. Mentor pentru zeci de dezvoltatori Drupal și creatorul SDX, o extensie Drupal pentru construirea de interfețe moderne cu React și Vue.

Ți-a plăcut articolul?

Dacă te-ai regăsit în articol, imaginează-ți ce am putea face împreună pe site-ul tău Drupal.