Giter Site home page Giter Site logo

laminas / laminas-session Goto Github PK

View Code? Open in Web Editor NEW
54.0 23.0 25.0 3.14 MB

Object-oriented interface to PHP sessions and storage

Home Page: https://docs.laminas.dev/laminas-session/

License: BSD 3-Clause "New" or "Revised" License

PHP 99.72% Shell 0.28%
session sessionstorage

laminas-session's Introduction

laminas-session

Build Status Coverage Status

🇷🇺 Русским гражданам

Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.

У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.

Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"

🇺🇸 To Citizens of Russia

We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.

One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.

You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"

laminas-session manages PHP sessions using an object oriented interface.

laminas-session's People

Contributors

akrabat avatar bakura10 avatar boesing avatar dasprid avatar evandotpro avatar ezimuel avatar freeaqingme avatar froschdesign avatar ghostwriter avatar gsteel avatar koopzington avatar kynx avatar maks3w avatar marc-mabe avatar michalbundyra avatar mikaelkael avatar mwillbanks avatar ocramius avatar prolic avatar ralphschindler avatar renovate[bot] avatar rieschl avatar samsonasik avatar sawarame avatar sgehrig avatar slamdunk avatar thinkscape avatar veewee avatar wdalmut avatar weierophinney avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laminas-session's Issues

SessionManager doesn't call rememberMe() automatically

Trying to figure out how to use sessions in ZF3, I've found that SessionManager doesn't use the configuration I pass. For example, I configure it as follows:

    // Session configuration.
    'session_config' => [
        'remember_me_seconds' => 60*60,  // Session will expire in 1 hour.
        'name'                => 'zf3',    // Session name.
    ],
    // Session manager configuration.
    'session_manager' => [
        // Session validators (used for security).
        'validators' => [
            RemoteAddr::class,
            HttpUserAgent::class,
        ]
    ],
    // Session storage configuration.
    'session_storage' => [
        'type' => SessionArrayStorage::class
    ],

However, SessionManager never use remember_me_seconds parameter unless I manually call its rememberMe() method. But, I expect it to call it automatically when session is started. Is this a bug?


Originally posted by @olegkrivtsov at zendframework/zend-session#59

session_write_close(): Failed to write session data using user defined save handler.

Occasionally,we get the following not yet reproducible warning:

WARN: session_write_close(): Failed to write session data using user defined save handler. (session.save_path: ) {"errno":2,"file":"/var/www/html/vendor/zendframework/zend-session/src/SessionManager.php","line":229}

This is how we initialize the session:

// Load config
$config = $serviceManager->get('Config');

// Initialize session
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config['session']);

$sessionTableGateway = new TableGateway('session', $serviceManager->get('Zend\Db\Adapter\Adapter'));
$saveHandler = new DbTableGateway($sessionTableGateway, new DbTableGatewayOptions());

$sessionManager = new SessionManager($sessionConfig, null, $saveHandler);
$sessionManager->setName($config['session']['name']);

$sessionManager->start();

Container::setDefaultManager($sessionManager);

Originally posted by @intellent at zendframework/zend-session#77

session_regenerate_id error

Warning: session_regenerate_id(): Session object destruction failed. ID: user (path: /var/lib/php/sessions) in /var/www/vendor/zendframework/zend-session/src/SessionManager.php on line 324

Using

PHP 7.0.13-0ubuntu0.16.04.1 (cli) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
    with Zend OPcache v7.0.13-0ubuntu0.16.04.1, Copyright (c) 1999-2016, by Zend Technologies
    with Xdebug v2.4.0, Copyright (c) 2002-2016, by Derick Rethans

Originally posted by @pensiero at zendframework/zend-session#70

Zend\Session::AbstractContainer::offsetExists() returning FALSE for key with NULL value

@weierophinney @Ocramius

As said in the title, checking if specific offset exists when it is set with NULL value always return FALSE.

// Zend session container
$session = Application::getInstance()->getSession();
$session['key'] = NULL;
if($session->offsetExists('key')) {
        // do something
}

The problem is that current implementation rely on PHP isset() language construct which return FALSE for keys with NULL value. Shouldn't it be preferable to use the PHP array_key_exists() function? What we want there is knonwing if a specific offset exists, whatever it value, right? Else, is there any reliable way to check if a particular key was set, whatever it value and without first having to get an array copy?

Even worse is that trying to unset an offset with NULL value will lead to a NO OP because we return early from Zend\Session::AbstractContainer::offsetUnset() if the offset isn't set in regard of the Zend\Session::AbstractContainer::offsetExists() current implementation:

// Zend session container
$session = Application::getInstance()->getSession();
$session['key'] = NULL;
$session->offsetUnset('key'); NO OP... Key will still be in storage...

Thank you.


Originally posted by @nuxwin at zendframework/zend-session#111

Missing dependency on laminas-http

Bug Report

We started trying to use laminas-session in an app that's not using any other laminas components, and hit an error:

Fatal error: Uncaught Error: Class 'Laminas\Http\PhpEnvironment\RemoteAddress' not found in vendor/laminas/laminas-session/src/Validator/RemoteAddr.php on line 127

It seems this class is provided by laminas-http, however this package is not marked as a dependency of laminas-session

Tests for SessionManager preserveStorage flag

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7129
User: @Martin-P
Created On: 2015-01-16T18:01:35Z
Updated At: 2015-03-19T20:26:23Z
Body
Zend/Session/SessionManager::start() has an optional flag $preserveStorage: Zend/Session/SessionManager line 84

If set to true, current session storage will not be overwritten by the contents of $_SESSION.

This PR tests that functionality. Not all tests pass, because the $preserveStorage flag is not working as it should.


Comment

User: @Ocramius
Created On: 2015-02-01T13:03:29Z
Updated At: 2015-02-01T13:03:29Z
Body
@Martin-P that functionality actually never worked in 2.x as far as I can see...


Comment

User: @Martin-P
Created On: 2015-02-01T20:49:04Z
Updated At: 2015-02-01T20:49:04Z
Body
That's possible, I only added the tests for what it should do. Not sure if it needs fixing if nobody uses this feature.


Comment

User: @weierophinney
Created On: 2015-03-18T16:42:09Z
Updated At: 2015-03-18T16:42:09Z
Body
@Martin-P want to take a crack at making it work? If so, I need changes by tomorrow, 19 March 2015.


Comment

User: @Martin-P
Created On: 2015-03-18T20:53:30Z
Updated At: 2015-03-18T20:53:30Z
Body
@weierophinney I do not think this can ever work. The security fix for session validators made me aware of this feature (zendframework/zendframework@ddbf43a). The preservation of $_SESSION data is part of the security fix. Making the preservation of $_SESSION data optional would compromise the security fix.

To make this work the security fix needs a change. The tests covering the security fix are present, so theoretically it should not be a problem. I don't know if you consider it an option to change the security fix?


Comment

User: @weierophinney
Created On: 2015-03-18T22:17:30Z
Updated At: 2015-03-18T22:17:30Z
Body
@Martin-P We can change the security fix so long as the tests introduced by it continue to pass.


Comment

User: @Martin-P
Created On: 2015-03-18T22:29:16Z
Updated At: 2015-03-18T22:29:16Z
Body
I can take a look at this, but I think it will be after the 2.4.0 release however.



Originally posted by @GeeH at zendframework/zend-session#50

[Feature] Allow Session validators to be created using the service manager

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7381
User: @larsnystrom
Created On: 2015-03-28T13:55:05Z
Updated At: 2015-03-30T13:26:15Z
Body
At the moment it is not possible to inject any dependencies into a session validator. There is simply no way to do that, since all session validators are created inside the SessionManager or the ValidatorChain.

In a perfect world, the word new would never have made it into any of the Session classes, but here we are.

I think I can hack a way around this by extending ValidatorInterface and add a method called setData(), which could be used to inject the session value to validate, instead of using the constructor to do that. This would allow a factory to create the validator, and the ValidatorChain to inject the session value to validate.

By extending the ValidatorInterface there will be no BC breaks, but the code will get pretty ugly. I still think that would be better than the current situation.

Do you have any thoughts on this?


Comment

User: @Martin-P
Created On: 2015-03-28T14:22:01Z
Updated At: 2015-03-28T14:22:01Z
Body

I think I can hack a way around this by extending ValidatorInterface and add a method called setData(), which could be used to inject the session value to validate

When the reference value exists in the current session it is automatically injected into the validator in Zend\Session\SessionManager::initializeValidatorChain(). You don't have to do this yourself.

You can also add validators to the ValidatorChain directly by using SessionManager::getValidatorChain().


Comment

User: @larsnystrom
Created On: 2015-03-28T14:33:53Z
Updated At: 2015-03-28T14:33:53Z
Body
Inserting the reference value is not the problem I'm trying to address. It's inserting dependencies that is a problem.

Let's just look at the RemoteAddr validator. The only reason $useProxy is static is because we can't inject the value. Usually that kind of configuration would be injected when the object is created.

I'm also working on an application where I need to inject some configuration and objects into the validator. I could go the static road, and create a static member with a static setter and configure the class during bootstrap. But really, shouldn't that be part of a factory? Isn't that the whole point of a factory?


Comment

User: @larsnystrom
Created On: 2015-03-28T14:42:57Z
Updated At: 2015-03-28T14:45:08Z
Body

When the reference value exists in the current session it is automatically injected into the validator in Zend\Session\SessionManager::initializeValidatorChain().

This is not correct. I just submitted PR #7380 which removes that misconception. Reference values are only injected in the ValidatorChain constructor.

But that is a separate issue.


Comment

User: @Martin-P
Created On: 2015-03-28T14:59:17Z
Updated At: 2015-03-28T14:59:17Z
Body
I see my PR which introduced that code had some redundant code, nice catch 👍 However, this does not make it a misconception. Reference values are still injected in the ValidatorChain.

Reference values are only injected in the ValidatorChain constructor.

That is correct. To start a session you have to call SessionManager::start() which always creates a ValidatorChain (line 127) which creates validators based on key/value pairs in $_SESSION['__VALID'].

Perhaps you can post some code for your use case to make the issue more clear? Thanks.


Comment

User: @larsnystrom
Created On: 2015-03-28T15:34:50Z
Updated At: 2015-03-28T15:34:50Z
Body
Here's a crude example:

public function isValid()
{
    $config = require APPLICATION_ROOT . '/module/Application/config/module.config.php';

    $appVersion = $config['app']['version'];

    return ($appVersion == $this->getData());
}

Obviously, requiring the entire module configuration in the session validator is a very bad idea. This is my problem right now, but in other validators I want objects which are created using factories when i validate the session. Basically I want to inject configuation values and services.

Do you know of a way to inject the application version number in the above session validator without using public static anywhere? (Of course, public static would still be better than the above)


Comment

User: @Martin-P
Created On: 2015-03-28T17:05:19Z
Updated At: 2015-03-28T17:05:19Z
Body
I think you should be able to add those validators like this:

// This validator can be created using a factory
$customValidator = $serviceManager->get('My\Custom\Session\Validator');
$sessionManager  = $serviceManager->get('Zend\Session\ServiceManagerInterface');

$event    = 'session.validate';
$callback = array($customValidator, 'customMethod');
$priority = 100;
$sessionManager->getValidatorChain()->attach($event, $callback, $priority);

$sessionManager->start();

Comment

User: @larsnystrom
Created On: 2015-03-28T17:44:19Z
Updated At: 2015-03-28T17:44:49Z
Body
The problem is that the validators are stored in the session storage, so when the session is started the next time, the validator will get created inside the ValidatorChain constructor where it'll only get the reference value injected. The ValidatorChain doesn't have a service manager to create the validator with.


Comment

User: @Martin-P
Created On: 2015-03-30T07:44:16Z
Updated At: 2015-03-30T07:44:16Z
Body
Okay, I see what you mean, that is indeed a problem.

Validators can be created at multiple points in the process: inside SessionManager and inside ValidatorChain. IMO the ValidatorChain should never create its own validators and should only be a dumb object containing the callback functions for validating the session. The validators itself should be injected at one point in the process and the session values can be injected there. Also that would make it easier to implement the feature with the ServiceManager.



Originally posted by @GeeH at zendframework/zend-session#49

Support PHP7's read_and_close

Since PHP7 it is possible to set the option read_and_close. See: `http://php.net/manual/en/migration70.new-features.php#migration70.new-features.session-options

I use this library and want to enable this option. However it seems not to be supported yet. Would be willing to contribute. My plan is as follows.

  • Introduce this option to StandardConfig
  • Simply apply setting in SessionManager::start
  • Maybe emit a message when setting this value on PHP < 7 ??

Before I start. Does repo owner agree on the necessity and plan?


Originally posted by @roelvanduijnhoven at zendframework/zend-session#39

[Question] Insufficient data for unserializing

Hello, maybe someone will be able to help me. I'm trying to save UserEntity (simple getters and setters, 1:1 mapping to db table, no extra methods or logic) into SessionArrayStorage, save handler is db table (session value column - text without length restrictions).
When I just simply put stdClass from getResultRowObject of Zend Authentication into storage, everything works fine. But when I hydrate stdClass into UserEntity, data inside DB value column is truncated:

...{s:7:"storage";O:23:"User\Entity\UserEntity":6:{s:36:" <- session value ends here

and warnings are generated: PHP Warning: Insufficient data for unserializing, Warning: session_start(): Failed to decode session object. Session has been destroyed

I've disabled DB storage and serialized data inside sess_xxx file was complete, getIdentity returned full UserEntity object. So, are there some restrictions when using DB storage and automatic serialization or is it my fault somewhere?


Originally posted by @xorock at zendframework/zend-session#64

RemoteAddr Validation Issue on Chrome of android

Hello

I'm using zend framework 3 and I've added the following validators in my session configuration :

   'session_manager' => [
        'validators' => [
            Zend\Session\Validator\RemoteAddr::class,
            Zend\Session\Validator\HttpUserAgent::class,
        ],
    ],

I have a strange issue in android cellphones/tablets, I get invalid session. I debugged the Zend Session code and I noticed that the 'RemoteAddr' validator returns false on 'isValid' method and it detects different ips on the following line of code :

return ($this->getIpAddress() === $this->getData());

I don't understand why the '$this->getIpAddress()' is different from '$this->getData()'. While I don't have this issue in my laptop, and also firefox browser on android does not have this issue.

Do you have any clue what is the problem and how can I solve this to work on android chrome ?


Originally posted by @alenoosh at zendframework/zend-session#113

SessionManager Validates session_id After session_start() Causing a Warning

Hi,

session_start() in SessionManager is causing a warning using an id with invalid characters. This behaviour should be handled to prevent problems like "information disclosures". An attacker can trigger the warning too easy.

Code to reproduce the issue

        $config = new SessionConfig();
        $manager = Container::getDefaultManager();
        $manager->setConfig($config);

        $this->sessionContainer = new Container('foo', $manager);

Reproduce The Issue

% curl -I 'http://zend.local/' -H 'Cookie: PHPSESSID=_test_'
HTTP/2 500 
server: nginx/1.10.3
date: Tue, 02 Jul 2019 08:59:35 GMT
content-type: text/html; charset=UTF-8

Expected results

There a three possible ways to handle the situation:

  1. Suppress the warning, regenerate a new id, start the session again
if (! @session_start()) {
    $this->regenerateId();
    session_start();
}
  1. Suppress the warning but also throw an exception that the session is not be started
if (! @session_start()) {
    throw new Exception\RuntimeException('Failed to start the session');
}
  1. Just ignore the warning and move handling to the validators
@session_start();

I'm personally a fan of the first option because I think that the developer doesn't want to handle errors that occurred during session start.
"If the session doesn't start, just ignore the user provided id and create a new/correct one."

Actual results

.../vendor/zendframework/zend-session/src/SessionManager.php:140
session_start(): The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,' [E_WARNING]

Zend\Session\Validator\Id is trying to address the problem, but fails to do so because the validation happens after session_start().

Related Issue

I found #21, but @SvenRtbg's comment is not 100% addressing what I'm concerned about.
My concern is information disclosures when the system is not handling warnings properly (never show any errors to the end user).

I hope the filed issue is clear and has enough details. Let me know if you need more background.

Best regards


Originally posted by @sbani at zendframework/zend-session#119

Lazy session start

The current container object starts a session in the constructor automatically. This works fine for most use cases, but it could come in handy to use some kind of delayed session start. I'm working on a REST API which accepts API keys, but also check for authenticated users in their sessions. The authentication for the users are stored in sessions. However, every API call from a REST client generates a session. It will send a cookie to the REST client, while also storing the session information on disk. This should not happen with every API call by REST clients.

It would be great to have a container which does not automatically starts a session, only under the following circumstances:

  • If data is written to the container, start a new session
  • If trying to read data from the container, only start a session when session_status return PHP_SESSION_NONE and $_COOKIE[session_name()] is set. This will only start a session when the browser actually has send a cookie to the server.

Originally posted by @dekker-m at zendframework/zend-session#43

Fatal error: Session validation failed

If computer only one browser. then open the size is ok.
If have other browser, like open the site use chrome. it's ok, then open the site use firefox.
The session will trow exception.
It's an abominable question.
The zend-session have half year no updated. The ZendFramework is ok?


Originally posted by @leolicai at zendframework/zend-session#69

Remove exception thrown when session validation fails

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.

Switch from Travis-Ci to GitHub actions for continuous integration workflow

To prepare a pull request following these steps:

  • Remove the CHANGELOG.md file (we will be doing changelogs in the milestone descriptions, and those get propagated to tags and release notes)
  • Add the workflow file:
    mkdir -p .github/workflows ; cd  .github/workflows ; wget https://gist.githubusercontent.com/weierophinney/9decd19f76b7d9745c6559074053fa65/raw/6ffb33e59796cfec569405139aa65da9396ea5cd/continuous-integration.yml
  • Check to see if there are any differences between what the Travis config and the GHA workflow do - don't worry about code coverage - but check for things like: extensions required, any pre-script tasks, etc. (Most of the time, there aren't any). If you see any, either: (1) add a .laminas-ci.json file with required configuration (e.g., adding extensions, adding php.ini settings; see https://github.com/laminas/laminas-ci-matrix-action#configuration for details), or (2) add information to the GHA workflow file (e.g., adding a service such as MySQL, Redis, etc.; see the laminas-db or laminas-cache adapter packages for examples).
  • Remove the .travis.yml file.
  • Remove the entry for composer.lock from the .gitignore file.
  • In the .gitattributes file:
    • Remove the entry for .travis.yml
    • Add an entry for .laminas-ci.json if you created one
    • Add an entry for .github if one does not exist
  • Using PHP 7.4, run composer update
  • Update the README.md file:
    • Remove any existing badges for Travis and/or Coveralls.
    • Add a badge with the following (substituting in the correct organization and repository name):
      [![Build Status](https://github.com/laminas/laminas-session/actions/workflows/continuous-integration.yml/badge.svg)](https://github.com/laminas/laminas-session/actions/workflows/continuous-integration.yml)
  • Add and commit the GHA workflow, the .gitignore and .gitattribute files, the composer.lock file, and the README.md file.
  • Push to your fork and create the PR. If there are any QA job failures, fix and push the changes.
  • If the package supports PHP ^5.6 | ^7.0, you will need to exclude locked runs for PHP 5.6 - 7.2. The way to do that is to create the .laminas-ci.json file if you haven't already, and ensure it has the following contents:
    {
        "exclude": [
            {"name": "PHPUnit on PHP 5.6 with locked dependencies"},
            {"name": "PHPUnit on PHP 7.0 with locked dependencies"},
            {"name": "PHPUnit on PHP 7.1 with locked dependencies"},
            {"name": "PHPUnit on PHP 7.2 with locked dependencies"}
        ]
    }

Possible unescaped special chars in session name and bug after PHP patch #79699

Bug Report

Q A
Version(s) 2.9.3

Summary

After the patch https://bugs.php.net/bug.php?id=79699 certain session names are buggy and won't work anymore.

Current behavior

The generated cookie name doesn't necessarily match the internal session name which is a problem after the php patch.

How to reproduce

  1. Install the latest PHP featuring above bugfix.
  2. Set up the session for example like this:
    'session_config' => [
        'name' => 'my:session',
    ],
  1. The generated cookie name is my%3Asession but the module still expects to get a cookie for my:session, which it won't get with the security patch.

Expected behavior

Special characters like : should also be escaped during initalisation, so the cookie name and session name match.

Remove default session manager as it introduces hidden dependencies

Currently the Zend\Session\AbstractContainer class has the setDefaultManager() static method which completely breaks the concept which forces developers to explicitly specify the dependencies for a class, model, controller etc. As a result, many ZF3 components implicitly use the default session manager.

If I configure 'not default' session manager, I have to pass it everywhere including controllers, services, validators (like FlashMessenger) etc., but I think this possiblity is not developed enough in ZF3, because all components use default session manager implicitly.

I suggest to remove the static default session manager and force users to configure and provide the session manager explicitly.


Originally posted by @olegkrivtsov at zendframework/zend-session#58

Introduce session.cookie_samesite

Feature Request

As of Chrome 80 a cookie's SameSite setting became more important.

It is however not possible to configure cookie's generated by this repo to set SameSite.

Feature: make it possible to configure using session.cookie_samesite.

Q A
New Feature yes
RFC no
BC Break no

Summary

This would require changing this piece of code. However, it is not trivial to do so, as setcookie only allows setting this since PHP 7.3.

So to implement this properly for PHP >= 7.0 we need to use setheader explicitly.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • Lock file maintenance

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

composer
composer.json
  • php ~8.1.0 || ~8.2.0 || ~8.3.0
  • laminas/laminas-eventmanager ^3.12
  • laminas/laminas-servicemanager ^3.22
  • laminas/laminas-stdlib ^3.18
  • laminas/laminas-cache ^3.12.1
  • laminas/laminas-cache-storage-adapter-memory ^2.3
  • laminas/laminas-coding-standard ~2.5.0
  • laminas/laminas-db ^2.19.0
  • laminas/laminas-http ^2.19
  • laminas/laminas-validator ^2.49.0
  • mongodb/mongodb ~1.17.0
  • phpunit/phpunit ^9.6.17
  • psalm/plugin-phpunit ^0.19.0
  • vimeo/psalm ^5.22.2
github-actions
.github/workflows/continuous-integration.yml
  • laminas/laminas-ci-matrix-action v1
  • laminas/laminas-continuous-integration-action v1
  • mysql 8
.github/workflows/docs-build.yml
.github/workflows/release-on-milestone-closed.yml

  • Check this box to trigger a request for Renovate to run again on this repository

Error Running Sessions (v2.7) with EventManager (v3)

In ValidatorChain.php:

use Zend\EventManager\GlobalEventManager;`

// ...

if (class_exists(GlobalEventManager::class)) {
    class_alias(Validator\AbstractValidatorChainEM2::class, AbstractValidatorChain::class);
} else {
    class_alias(Validator\AbstractValidatorChainEM3::class, AbstractValidatorChain::class);
}

However GlobalEventManager is not available since version 2.6 of the EventManager and therefor causes problems with version 3.

PHP 5.6 running on WAMP Server.

I don't know if this happens all the time, guess it will... What I've done is NOT loading the module and initialize the session manager by hand:

$sessionConfig = new SessionConfig();
$session = new SessionManager($sessionConfig);
$session->start();

It will cause the error due to the missing GlobalEventManager class and if you bring the class from version 2.6 then the next reported error comes allong due to the missing callabledeclaration in AbstractValidatorChainEM2::attach method.


Originally posted by @JPG-Consulting at zendframework/zend-session#62

Documentation clarifications - ext/session vs. ext-session, and "entry of" vs. "entry in"

The documentation at https://docs.zendframework.com/zend-session/config/
says

Zend\Session\Config\StandardConfig provides the base interface for configuring sessions when not leveraging ext/session

What is ext/session? Do they mean the "PHP session extension"?

If so, I'll do a PR with a global search/replace, because that really threw me off.

Also, https://docs.zendframework.com/zend-session/container/ says:

Each instance of Zend\Session\Container corresponds to an entry of the Zend\Session\Storage, where the namespace is used as the key.

What's meant by "corresponds to an entry of"? Do they mean "is an entry in"?


Originally posted by @bitwombat at zendframework/zend-session#125

Session gc_maxlifetime and cookie_lifetime with php-fpm pool config

Continuing the bug report from zendframework/zendframework#4733

TL:DR;

When the following settings are set via the pool config from php-fpm and not in php.ini, they cannot be overwritten via php's ini_set():

  • session.gc_maxlifetime
  • session.cookie_lifetime

ZF2 tries to reset them anyway and fails (see old bug report for details).
ZF2 Versions tested: 2.2.1, 2.4.1, 2.5.3
On PHP 5.6

example php-fpm pool conf line:
php_admin_value[session.gc_maxlifetime] = 1880


Originally posted by @maces at zendframework/zend-session#53

clear() does not clear metadata for provided key

Bug Report

Summary

I really do not know if the problem described bellow is a bug or just a layer 8 feature, so I hope this clears the issue a bit.

Current behavior

\Laminas\Session\Storage\AbstractSessionArrayStorage::clear() does not remove meta data set with \Laminas\Session\Storage\AbstractSessionArrayStorage::setMetadata()

How to reproduce

/** 
 * @var \Laminas\Session\Storage\StorageInterface $storage
 */
$storage->setMetadata('foo', 'bar');
$storage->clear('foo');

var_dump($storage->getMetadata('foo'));  // "string" => "bar"

Expected behavior

/** 
 * @var \Laminas\Session\Storage\StorageInterface $storage
 */
$storage->setMetadata('foo', 'bar');
$storage->clear('foo');

var_dump($storage->getMetadata('foo'));  // "bool" => "false"

Assumption

The early return statement in the class AbstractSessionArrayStorage:424 prevents the expected behavior. Method setMetadata() puts all data into the session index __Laminas but clear() breaks to early on line 424 but should break after line 432.

PHP 8.0 support

Feature Request

Q A
New Feature yes

Summary

To be prepared for the december release of PHP 8.0, this repository has some additional TODOs to be tested against the new major version.

In order to make this repository compatible, one has to follow these steps:

  • Modify composer.json to provide support for PHP 8.0 by adding the constraint ~8.0.0
  • Modify composer.json to drop support for PHP less than 7.3
  • Modify composer.json to implement phpunit 9.3 which supports PHP 7.3+
  • Modify .travis.yml to ignore platform requirements when installing composer dependencies (simply add --ignore-platform-reqs to COMPOSER_ARGS env variable)
  • Modify .travis.yml to add PHP 8.0 to the matrix (NOTE: Do not allow failures as PHP 8.0 has a feature freeze since 2020-08-04!)
  • Modify source code in case there are incompatibilities with PHP 8.0

Add ValidatorServiceInterface for session validators

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7384
User: @larsnystrom
Created On: 2015-03-30T14:29:30Z
Updated At: 2015-11-06T23:54:06Z
Body
This PR fixes #7381 without any BC breaks. It allows a session validator to be instantiated with dependencies and adds some default functionality to the SessionManagerFactory to get() session validators from the ServiceManager.

It introduces the new interface Zend\Session\Validator\ValidatorServiceInterface which extends Zend\Session\Validator\ValidatorInterface. It modifies the Zend\Session\Service\SessionManagerFactory to also inject validator services into the session manager. Lastly it modifies Zend\Session\SessionManager and Zend\Session\ValidatorChain to attach the validator services to the ValidatorChain and inject the reference value from the current session into the validator service using the setData() method defined in the ValidatorServiceInterface.

A validator which implements the ValidatorServiceInterface can be registered under the key services in the configuration array for session validators, like this:

array (
    'session_manager' => array(
        'validators' => array(
            'OldSessionValidatorWillWork',
            'services' => array(
                'NewValidatorServicesGoHere',
            ),
        ),
    ),
);

The example above illustrates that the old way of registering validators still works, and that new validator services goes under the services key of the validators array.

All validators under the services key must:

  • implement the ValidatorServiceInterface, and
  • be registered with the ServiceManager.

I'm open for discussion, but I think this is the best way to implement this feature without a BC break.

Caveats:

  • In the old way of doing things we only registered session validators when creating the session. On subsequent requests the session validators would be instantiated automatically. The new validator services work differently in that they must be injected in the SessionManager on each request. If a service validator isn't injected it will be improperly created by the ValidatorChain, which may cause unknowing developers some trouble.

Things I haven't thought of yet: (hey, that's a paradox!)

  • How to insert the validators when creating the session. I'm not sure how to do this without removing them all, re-getting them from the service manager, injecting the reference value and then attaching them again. There are probably other ways, but it's still overly complicated.

Comment

User: @Martin-P
Created On: 2015-03-30T14:44:32Z
Updated At: 2015-03-30T14:44:32Z
Body
I like the way you fixed this without a BC break, but it also feels a bit like a workaround for the somewhat messy implementation of the SessionValidators. Personally I think Zend\Session can use a bit of a cleanup, so SessionValidators are created at one point in the process. Yes, that would mean a BC break, but looking at the current implementation I think that it can only be an improvement of the code.

See also my other comment (zendframework/zendframework#7381 (comment)) regarding the SessionValidators:

Validators can be created at multiple points in the process: inside SessionManager and inside ValidatorChain. IMO the ValidatorChain should never create its own validators and should only be a dumb object containing the callback functions for validating the session. The validators itself should be injected at one point in the process and the session values can be injected there. Also that would make it easier to implement the feature with the ServiceManager.


Comment

User: @larsnystrom
Created On: 2015-03-30T15:54:19Z
Updated At: 2015-03-30T15:54:19Z
Body
I'm all for refactoring of Zend\Session, but since it would cause a BC break it will probably have to wait until ZF3 (or until somebody splits ZF into it's separate components). There are some serious issues with the current implementation, so I'm looking forward to that, but without word from higher up the chain of command here, it's just not possible.

I also agree with you that the ValidatorChain should never create it's own objects. However, that's another thing that can't be changed without a BC break. To be honest I think we should scrap the ValidatorChain altogether and just use an array in the SessionManager. I don't see the point in using a priority queue when we can't even specify priorities.

I also think it was a bad idea to force validation of the session in SessionManager::start(), especially when you can't specify which values to validate before running it.

One thing that could be done is adding an argument to ValidatorInterface::isValid(), to provide the session storage to the validator. That way you could validate pretty much anything you'd like, even certain combinations of values. It would also be a more intuitive way of doing the validation, following the same pattern used in Zend\Validator where isValid() always takes the value to be validated as the argument.

I guess this component was put together in a hurry. Splitting ZF into separate components would allow us to start fixing the real problems here. In the meantime we can stuff like I did here.



Originally posted by @GeeH at zendframework/zend-session#48

Psalm integration

Feature Request

Q A
QA yes

Summary

As decided during the Technical-Steering-Committee Meeting on August 3rd, 2020, Laminas wants to implement vimeo/psalm in all packages.

Implementing psalm is quite easy.

Required

  • Create a .psalm.xml.dist in the project root
  • Copy and paste the contents from this psalm.xml.dist
  • Run $ composer require vimeo/psalm
  • Run $ vendor/bin/psalm --set-baseline=psalm-baseline.xml
  • Add a composer script static-analysis with the command psalm --shepherd --stats
  • Add a new line to script: in .travis.yml: - if [[ $TEST_COVERAGE == 'true' ]]; then composer static-analysis ; fi
  • Remove phpstan from the project (phpstan.neon.dist, .travis.yml entry, composer.json require-dev and scripts)
Optional
  • Fix as many psalm errors as possible.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.