Skip to content

Remove exception thrown when session validation fails #28

@rjd22

Description

@rjd22

Bug Report

Q A
Version(s) 2.9.2 and less

Summary

When a session is started and the session validation does not pass and an exception is thrown on:

throw new Exception\RuntimeException('Session validation failed');

The problem that I experience is, that this exception will be thrown when initializing the ServiceContainer in Laminas, making it really hard to catch this and deal with it without breaking the flow of a user.

This is because of the following code on the AbstractContainer:

$this->getManager()->start();

To deal with this the following kind of code needs to be made:

    /**
     * @param MvcEvent $e
     */
    public function startSession(MvcEvent $e)
    {
        $request = $e->getRequest();
        //only start sessions when it's an http request
        if (!$request instanceof HttpRequest) {
            return;
        }

        $locator = $e->getApplication()->getServiceManager();

        try {
            $sessionManager = $locator->get(SessionManager::class);
            $sessionManager->start(true);
        } catch (ServiceNotCreatedException $exception) {
            if (strpos($exception->getMessage(), 'Session validation failed') === false) {
                throw $exception;
            }

            // The session manager tries to start the session with a cookie that has a invalid cookie id. The validation
            // goes wrong causing this exception. When this happens unset the session so a new cookie is generated.
            // Issue: https://github.com/laminas/laminas-session/issues/9
            session_regenerate_id(true);
            session_reset();

            $sessionManager = $locator->get(SessionManager::class);
            $sessionManager->start(true);
        }
    }

Current behavior

An exception this thrown and the service manager fails. The result when not catched is that the user ends up with a 500 error, that will keep coming up, until the user removes the cookies from the browser.

How to reproduce

Generate a cookie with invalid characters as ID. The cookie should not pass the validators.

Expected behavior

I would expect the session manager to try to invalidate the cookie by running session_regenerate_id and session_reset and trying to restart the session after doing so. Most likely logging the user out, but allowing the user to get out of the 500 loop.

I'm willing to submit an PR to change this behavior, but since this will be a breaking change, I would like to know if you find this a good idea, and/or that I might be missing something in my own application.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions