Generated with the help of an LLM.

Problem/Motivation

Since updating from 11.3.19 to 11.4.11 we see a recurring error in production that did not exist prior to the update:

    Error: Call to a member function getSession() on null in
    Drupal\Core\Session\SessionHandler::doWrite()
    (line 74 of core/lib/Drupal/Core/Session/SessionHandler.php)

    #3 .../core/lib/Drupal/Core/Session/SessionHandler.php(80): ...->{closure}()
    #2 .../core/lib/Drupal/Core/Session/WriteSafeSessionHandler.php(76): write()
    #1 [internal function]: session_write_close()
    #0 {main}

Cause: #2613044: Requests are pushed onto the request stack twice, popped once made DrupalKernel::terminate() pop the main request off the request stack. Before 11.4 that request stayed on the stack until the process ended. When PHP's shutdown saves a session that is still open, SessionHandler::doWrite() asks the stack for the current request so it can stamp uid and hostname on the row, and never checks for null.

For us this predominantly occurs following a 403 from our OIDC module's failed-login callback which leaves an open, changed session.

Impact: Nothing is user-visible, but the late session data is silently lost (before 11.4 these writes succeeded), the fatal is logged every time, and it stops any later shutdown functions from running.

Steps to reproduce

Add a throwaway http_middleware with priority between Session (50) and KernelPreHandle (100) that changes the session after the inner kernel returns:

public function handle(Request $request, int $type = self::MAIN_REQUEST, bool $catch = TRUE): Response {
  $response = $this->httpKernel->handle($request, $type, $catch);
  if ($request->cookies->count() && $request->hasSession()) {
    $request->getSession()->set('probe', time());
  }
  return $response;
}

Visit any page while logged in. On 11.4.x PHP's shutdown save produces the exact fatal above. On 11.3.x the same write succeeds.

Proposed resolution

Move the Session stack middleware's save() into the finally leg of a try/finally around the inner kernel call, so the session is saved even when the kernel throws. See comment #6.

$result = NULL;
try {
  $result = $this->httpKernel->handle($request, $type, $catch);
}
finally {
  if ($type === self::MAIN_REQUEST && PHP_SAPI !== 'cli' && !$result instanceof ResponseKeepSessionOpenInterface) {
    $request->getSession()->save();
  }
}

return $result;

Issue fork drupal-3634400

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

codebaboon created an issue. See original summary.

cilefen’s picture

Issue summary: View changes
cilefen’s picture

codebaboon’s picture

Version: main » 11.4.x-dev

A a follow-up here are steps to reproduce through the standard OpenID Connect callback, with no custom code involved.

On a site running 11.4.x, with a configured OIDC provider (I used FusionAuth):

  • go to a private session in your browser
  • open the website, open network tools
  • log in to the website with an existing account
  • in the network results find the URL that start like this: https://[your-site]/openid-connect/[your-oidc-client]?code=
  • copy paste that full URL into another tab in the same browser, you get an error page.

This scenario, while contrived, simulates something similar to a delayed login exchange where the code expires before being handed off. The module takes its failure path for the stale state, the request ends in an error response, and the session is left open and modified. PHP's shutdown session_write_close() then runs against the empty request stack and fatals with the exact stack trace in the summary:

#3 [internal function]: WriteSafeSessionHandler->write(...)
#4 [internal function]: session_write_close()
#5 {main}
nicxvan’s picture

Version: 11.4.x-dev » main

Fixes are made on main and backported as necessary.

ghost of drupal past’s picture

Title: Regression: fatal "Call to a member function getSession() on null" in SessionHandler::doWrite() when PHP shutdown writes a still-active session, after the request stack pop added to DrupalKernel::terminate() » SessionHandler::doWrite() fatals due to a missed null check

no need for a slop title

Suggested fixes:

  1. Move the $request->getSession()->save(); in the Session middleware into the finally leg of a try-finally. That should fix the issue of this save not firing on a 403 as far as I understand the request handling.
  2. Having a middleware to mutate session after the session middleware is broken code and core should be broken with that. This should be documented on the session middleware.

Hardwiring a session close into DrupalKernel is a very bad idea. Do not hardwire things into the poor kernel.

codebaboon’s picture

Issue summary: View changes
StatusFileSize
new973 bytes

re #6: thanks, you were right. I moved the save into a try/finally in the Session middleware as you suggested, and it resolves the error.

In drupal/html/core/lib/Drupal/Core/StackMiddleware/Session.php:

    $result = NULL;
    try {
      $result = $this->httpKernel->handle($request, $type, $catch);
    }
    finally {
      if ($type === self::MAIN_REQUEST && PHP_SAPI !== 'cli' && !$result instanceof ResponseKeepSessionOpenInterface) {
        $request->getSession()->save();
      }
    }

    return $result;

See attached patch, I've updated the summary Proposed Resolution to match this suggestion.

nicxvan’s picture

Thank you, please create an issue fork here so that tests can run and we can review it properly.

cilefen’s picture

Issue tags: +Needs merge request
ghost of drupal past’s picture

Also please add the documentation on the session middleware.

codebaboon’s picture

Status: Active » Needs review
Issue tags: -Needs merge request

I have opened MR !17865 against main. This merge request includes the session middleware fix, documentation asked for by ghost of drupal past in #10, and also a test that will fail if this fix is not in place.

A backport to `11.4.x` would be appreciated, as we hit this in production and have needed to introduce a composer patch in the interim.

Generated with the help of an LLM.