Starting a session in hook_entity_access() causing errors

Created on 4 March 2025, about 1 month ago

Problem/Motivation

In paragraphs_blokkli_entity_access() we are getting the active session directly from the request object:

function paragraphs_blokkli_entity_access(EntityInterface $entity, $operation) {
  $session = \Drupal::request()->getSession();
  // ...
}

This implements hook_entity_access() which is a common hook which can fire at any time, also in contexts where a request doesn't exist (e.g. Drush commands, cron jobs, ...), or in cases where a session is not relevant (CLI commands, ...) or is already terminated (e.g. shutdown hooks).

For these reasons the use of \Drupal::request() is strongly discouraged, as mentioned in the API documentation: Drupal::request().

Steps to reproduce

Implement a KernelEvents::TERMINATE subscriber that does an access check on any entity:

class MySubscriber implements EventSubscriberInterface {

  public function onTerminate(TerminateEvent $event): void {
    Node::load(1)->access('view');
  }

  public static function getSubscribedEvents(): array {
    return [KernelEvents::TERMINATE => [['onTerminate', 100]]];
  }

}

Result: an exception is thrown because the session has already been terminated and cannot be restarted:

Failed to start the session because headers have already been sent by "/home/vcap/app/vendor/symfony/http-foundation/Response.php" at line 431.

Proposed resolution

There are some suggestions in the documentation of \Drupal::request() on how to deal with this situation. Maybe one of them is applicable?

🐛 Bug report
Status

Active

Version

1.3

Component

Code

Created by

🇧🇬Bulgaria pfrenssen Sofia

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024