Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[HttpKernel] Add session cookie handling in cli context #41390

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ public function load(array $configs, ContainerBuilder $container)
$this->sessionConfigEnabled = true;
$this->registerSessionConfiguration($config['session'], $container, $loader);
if (!empty($config['test'])) {
$container->getDefinition('test.session.listener')->setArgument(1, '%session.storage.options%');
$container->getDefinition('test.session.listener')->setArgument(2, '%session.storage.options%');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is because we switched from TestSessionListener to SessionListener

}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,10 @@
'session_collector' => service('data_collector.request.session_collector')->ignoreOnInvalid(),
]),
param('kernel.debug'),
param('session.storage.options'),
])
->tag('kernel.event_subscriber')
->tag('kernel.reset', ['method' => 'reset'])

// for BC
->alias('session.storage.filesystem', 'session.storage.mock_file')
Expand Down
6 changes: 4 additions & 2 deletions 6 src/Symfony/Bundle/FrameworkBundle/Resources/config/test.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
use Symfony\Component\BrowserKit\CookieJar;
use Symfony\Component\BrowserKit\History;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\HttpKernel\EventListener\TestSessionListener;
use Symfony\Component\HttpKernel\EventListener\SessionListener;

return static function (ContainerConfigurator $container) {
$container->parameters()->set('test.client.parameters', []);
Expand All @@ -35,11 +35,13 @@
->set('test.client.history', History::class)->share(false)
->set('test.client.cookiejar', CookieJar::class)->share(false)

->set('test.session.listener', TestSessionListener::class)
->set('test.session.listener', SessionListener::class)
->args([
service_locator([
'session' => service('.session.do-not-use')->ignoreOnInvalid(),
]),
param('kernel.debug'),
param('session.storage.options'),
])
->tag('kernel.event_subscriber')

Expand Down
4 changes: 3 additions & 1 deletion 4 src/Symfony/Component/HttpFoundation/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ class Request
protected $format;

/**
* @var SessionInterface|callable
* @var SessionInterface|callable(): SessionInterface
*/
protected $session;

Expand Down Expand Up @@ -775,6 +775,8 @@ public function setSession(SessionInterface $session)

/**
* @internal
*
* @param callable(): SessionInterface $factory
*/
public function setSessionFactory(callable $factory)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,16 @@

use Psr\Container\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\Session\SessionUtils;
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\Exception\UnexpectedSessionUsageException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Contracts\Service\ResetInterface;

/**
* Sets the session onto the request on the "kernel.request" event and saves
Expand All @@ -36,18 +39,24 @@
*
* @internal
*/
abstract class AbstractSessionListener implements EventSubscriberInterface
abstract class AbstractSessionListener implements EventSubscriberInterface, ResetInterface
{
public const NO_AUTO_CACHE_CONTROL_HEADER = 'Symfony-Session-NoAutoCacheControl';

protected $container;
private $sessionUsageStack = [];
private $debug;

public function __construct(ContainerInterface $container = null, bool $debug = false)
/**
* @var array<string, mixed>
*/
private $sessionOptions;

public function __construct(ContainerInterface $container = null, bool $debug = false, array $sessionOptions = [])
{
$this->container = $container;
$this->debug = $debug;
$this->sessionOptions = $sessionOptions;
}

public function onKernelRequest(RequestEvent $event)
Expand All @@ -60,7 +69,22 @@ public function onKernelRequest(RequestEvent $event)
if (!$request->hasSession()) {
// This variable prevents calling `$this->getSession()` twice in case the Request (and the below factory) is cloned
$sess = null;
$request->setSessionFactory(function () use (&$sess) { return $sess ?? $sess = $this->getSession(); });
$request->setSessionFactory(function () use (&$sess, $request) {
if (!$sess) {
$sess = $this->getSession();
}

/*
* For supporting sessions in php runtime with runners like roadrunner or swoole the session
* cookie need read from the cookie bag and set on the session storage.
*/
if ($sess && !$sess->isStarted()) {
$sessionId = $request->cookies->get($sess->getName(), '');
$sess->setId($sessionId);
}

return $sess;
});
}

$session = $this->container && $this->container->has('initialized_session') ? $this->container->get('initialized_session') : null;
Expand Down Expand Up @@ -109,6 +133,54 @@ public function onKernelResponse(ResponseEvent $event)
* it is saved will just restart it.
*/
$session->save();

/*
* For supporting sessions in php runtime with runners like roadrunner or swoole the session
jderusse marked this conversation as resolved.
Show resolved Hide resolved
* cookie need to be written on the response object and should not be written by PHP itself.
*/
$sessionName = $session->getName();
$sessionId = $session->getId();
$sessionCookiePath = $this->sessionOptions['cookie_path'] ?? '/';
$sessionCookieDomain = $this->sessionOptions['cookie_domain'] ?? null;
$sessionCookieSecure = $this->sessionOptions['cookie_secure'] ?? false;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$sessionCookieHttpOnly = $this->sessionOptions['cookie_httponly'] ?? true;
$sessionCookieSameSite = $this->sessionOptions['cookie_samesite'] ?? Cookie::SAMESITE_LAX;

SessionUtils::popSessionCookie($sessionName, $sessionCookiePath);

$request = $event->getRequest();
$requestSessionCookieId = $request->cookies->get($sessionName);

if ($requestSessionCookieId && $session->isEmpty()) {
$response->headers->clearCookie(
$sessionName,
$sessionCookiePath,
$sessionCookieDomain,
$sessionCookieSecure,
$sessionCookieHttpOnly,
$sessionCookieSameSite
);
} elseif ($sessionId !== $requestSessionCookieId) {
Nyholm marked this conversation as resolved.
Show resolved Hide resolved
$expire = 0;
$lifetime = $this->sessionOptions['cookie_lifetime'] ?? null;
if ($lifetime) {
$expire = time() + $lifetime;
}

$response->headers->setCookie(
Cookie::create(
$sessionName,
$sessionId,
$expire,
$sessionCookiePath,
$sessionCookieDomain,
$sessionCookieSecure,
$sessionCookieHttpOnly,
false,
$sessionCookieSameSite
)
);
}
}

if ($session instanceof Session ? $session->getUsageIndex() === end($this->sessionUsageStack) : !$session->isStarted()) {
Expand Down Expand Up @@ -188,6 +260,20 @@ public static function getSubscribedEvents(): array
];
}

public function reset(): void
{
if (\PHP_SESSION_ACTIVE === session_status()) {
session_abort();
}

session_unset();
$_SESSION = [];

if (!headers_sent()) { // session id can only be reset when no headers were so we check for headers_sent first
session_id('');
}
}

/**
* Gets the session object.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
* @author Fabien Potencier <fabien@symfony.com>
*
* @internal
*
* @deprecated the TestSessionListener use the default SessionListener instead
*/
abstract class AbstractTestSessionListener implements EventSubscriberInterface
{
Expand All @@ -37,6 +39,8 @@ abstract class AbstractTestSessionListener implements EventSubscriberInterface
public function __construct(array $sessionOptions = [])
{
$this->sessionOptions = $sessionOptions;

trigger_deprecation('symfony/http-kernel', '5.4', 'The %s is deprecated use the %s instead.', __CLASS__, AbstractSessionListener::class);
}

public function onKernelRequest(RequestEvent $event)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

namespace Symfony\Component\HttpKernel\EventListener;

use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpKernel\Event\RequestEvent;
Expand All @@ -29,11 +28,6 @@
*/
class SessionListener extends AbstractSessionListener
{
public function __construct(ContainerInterface $container, bool $debug = false)
{
parent::__construct($container, $debug);
}

public function onKernelRequest(RequestEvent $event)
{
parent::onKernelRequest($event);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*
* @deprecated the TestSessionListener use the default SessionListener instead
*/
class TestSessionListener extends AbstractTestSessionListener
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public function testOnlyTriggeredOnMainRequest()
public function testSessionIsSet()
{
$session = $this->createMock(Session::class);
$session->expects($this->exactly(1))->method('getName')->willReturn('PHPSESSID');

$requestStack = $this->createMock(RequestStack::class);
$requestStack->expects($this->once())->method('getMainRequest')->willReturn(null);
Expand All @@ -73,6 +74,7 @@ public function testSessionIsSet()
public function testSessionUsesFactory()
{
$session = $this->createMock(Session::class);
$session->expects($this->exactly(1))->method('getName')->willReturn('PHPSESSID');
$sessionFactory = $this->createMock(SessionFactory::class);
$sessionFactory->expects($this->once())->method('createSession')->willReturn($session);

Expand Down Expand Up @@ -142,6 +144,32 @@ public function testResponseIsStillPublicIfSessionStartedAndHeaderPresent()
$this->assertFalse($response->headers->has(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER));
}

public function testSessionSaveAndResponseHasSessionCookie()
{
$session = $this->getMockBuilder(Session::class)->disableOriginalConstructor()->getMock();
$session->expects($this->exactly(2))->method('getUsageIndex')->will($this->onConsecutiveCalls(0, 1));
$session->expects($this->exactly(1))->method('getId')->willReturn('123456');
$session->expects($this->exactly(1))->method('getName')->willReturn('PHPSESSID');
$session->expects($this->exactly(1))->method('save');
$session->expects($this->exactly(1))->method('isStarted')->willReturn(true);

$container = new Container();
$container->set('initialized_session', $session);

$listener = new SessionListener($container);
$kernel = $this->getMockBuilder(HttpKernelInterface::class)->disableOriginalConstructor()->getMock();

$request = new Request();
$listener->onKernelRequest(new RequestEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST));

$response = new Response();
$listener->onKernelResponse(new ResponseEvent($kernel, new Request(), HttpKernelInterface::MASTER_REQUEST, $response));

$cookies = $response->headers->getCookies();
$this->assertSame('PHPSESSID', $cookies[0]->getName());
$this->assertSame('123456', $cookies[0]->getValue());
}

public function testUninitializedSession()
{
$kernel = $this->createMock(HttpKernelInterface::class);
Expand All @@ -166,6 +194,7 @@ public function testUninitializedSession()
public function testSurrogateMainRequestIsPublic()
{
$session = $this->createMock(Session::class);
$session->expects($this->exactly(2))->method('getName')->willReturn('PHPSESSID');
$session->expects($this->exactly(4))->method('getUsageIndex')->will($this->onConsecutiveCalls(0, 1, 1, 1));

$container = new Container();
Expand Down Expand Up @@ -205,6 +234,7 @@ public function testSurrogateMainRequestIsPublic()
public function testGetSessionIsCalledOnce()
{
$session = $this->createMock(Session::class);
$session->expects($this->exactly(2))->method('getName')->willReturn('PHPSESSID');
$sessionStorage = $this->createMock(NativeSessionStorage::class);
$kernel = $this->createMock(KernelInterface::class);

Expand Down Expand Up @@ -282,6 +312,7 @@ public function testSessionUsageLogIfStatelessAndSessionUsed()
public function testSessionIsSavedWhenUnexpectedSessionExceptionThrown()
{
$session = $this->createMock(Session::class);
$session->expects($this->exactly(1))->method('getName')->willReturn('PHPSESSID');
$session->method('isStarted')->willReturn(true);
$session->expects($this->exactly(2))->method('getUsageIndex')->will($this->onConsecutiveCalls(0, 1));
$session->expects($this->exactly(1))->method('save');
Expand Down Expand Up @@ -368,4 +399,46 @@ public function testSessionUsageCallbackWhenNoStateless()

(new SessionListener($container, true))->onSessionUsage();
}

/**
* @runInSeparateProcess
*/
public function testReset()
{
session_start();
$_SESSION['test'] = ['test'];
session_write_close();

$this->assertNotEmpty($_SESSION);
$this->assertNotEmpty(session_id());

$container = new Container();

(new SessionListener($container, true))->reset();

$this->assertEmpty($_SESSION);
$this->assertEmpty(session_id());
$this->assertSame(\PHP_SESSION_NONE, session_status());
}

/**
* @runInSeparateProcess
*/
public function testResetUnclosedSession()
{
session_start();
$_SESSION['test'] = ['test'];

$this->assertNotEmpty($_SESSION);
$this->assertNotEmpty(session_id());
$this->assertSame(\PHP_SESSION_ACTIVE, session_status());

$container = new Container();

(new SessionListener($container, true))->reset();

$this->assertEmpty($_SESSION);
$this->assertEmpty(session_id());
$this->assertSame(\PHP_SESSION_NONE, session_status());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
* Tests SessionListener.
*
* @author Bulat Shakirzyanov <mallluhuct@gmail.com>
* @group legacy
*/
class TestSessionListenerTest extends TestCase
{
Expand Down
Morty Proxy This is a proxified and sanitized view of the page, visit original site.