Skip to content
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

Add standalone service #572

Open
wants to merge 6 commits into
base: 9.2.x
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions examples/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
// simply run `php -S localhost:9999 index.php`
// then point your browser at `http://localhost:9999/`

$clock = SystemClock::fromUTC();

Check failure on line 44 in examples/index.php

View workflow job for this annotation

GitHub Actions / QA Checks (Psalm [8.2, locked], ubuntu-latest, laminas/laminas-continuous-integration-action@v1, ...

UndefinedClass

examples/index.php:44:22: UndefinedClass: Class, interface or enum named SystemClock does not exist (see https://psalm.dev/019)
$sessionMiddleware = new SessionMiddleware(
(new Configuration(
JwtConfig::forSymmetricSigner(
Expand Down
167 changes: 9 additions & 158 deletions src/Storageless/Http/SessionMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,37 +21,26 @@
namespace PSR7Sessions\Storageless\Http;

use BadMethodCallException;
use DateInterval;
use Dflydev\FigCookies\FigResponseCookies;
use Dflydev\FigCookies\SetCookie;
use InvalidArgumentException;
use Lcobucci\JWT\Encoding\ChainedFormatter;
use Lcobucci\JWT\Token;
use Lcobucci\JWT\UnencryptedToken;
use Lcobucci\JWT\Validation\Constraint\SignedWith;
use Lcobucci\JWT\Validation\Constraint\StrictValidAt;
use OutOfBoundsException;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use PSR7Sessions\Storageless\Http\ClientFingerprint\SameOriginRequest;
use PSR7Sessions\Storageless\Session\DefaultSessionData;
use PSR7Sessions\Storageless\Service\StoragelessSession;
use PSR7Sessions\Storageless\Session\LazySession;
use PSR7Sessions\Storageless\Session\SessionInterface;
use stdClass;

use function sprintf;

/** @immutable */
final class SessionMiddleware implements MiddlewareInterface
{
public const SESSION_CLAIM = 'session-data';
public const SESSION_ATTRIBUTE = 'session';

private readonly StoragelessSession $service;

public function __construct(
private readonly Configuration $config,
) {
$this->service = new StoragelessSession($config);
}

/**
Expand All @@ -62,149 +51,11 @@ public function __construct(
*/
public function process(Request $request, RequestHandlerInterface $handler): Response
{
$sameOriginRequest = new SameOriginRequest($this->config->getClientFingerprintConfiguration(), $request);
$token = $this->parseToken($request, $sameOriginRequest);
$sessionContainer = LazySession::fromContainerBuildingCallback(function () use ($token): SessionInterface {
return $this->extractSessionContainer($token);
});

return $this->appendToken(
$sessionContainer,
$handler->handle($request->withAttribute($this->config->getSessionAttribute(), $sessionContainer)),
$token,
$sameOriginRequest,
return $this->service->appendSession(
LazySession::fromToken($this->service->requestToToken($request)),
$request,
null,
$handler,
);
}

/**
* Extract the token from the given request object
*/
private function parseToken(Request $request, SameOriginRequest $sameOriginRequest): UnencryptedToken|null
{
/** @var array<string, string> $cookies */
$cookies = $request->getCookieParams();
$cookieName = $this->config->getCookie()->getName();

if (! isset($cookies[$cookieName])) {
return null;
}

$cookie = $cookies[$cookieName];
if ($cookie === '') {
return null;
}

$jwtConfiguration = $this->config->getJwtConfiguration();
try {
$token = $jwtConfiguration->parser()->parse($cookie);
} catch (InvalidArgumentException) {
return null;
}

if (! $token instanceof UnencryptedToken) {
return null;
}

$constraints = [
new StrictValidAt($this->config->getClock()),
new SignedWith($jwtConfiguration->signer(), $jwtConfiguration->verificationKey()),
$sameOriginRequest,
];

if (! $jwtConfiguration->validator()->validate($token, ...$constraints)) {
return null;
}

return $token;
}

/** @throws OutOfBoundsException */
private function extractSessionContainer(UnencryptedToken|null $token): SessionInterface
{
if (! $token) {
return DefaultSessionData::newEmptySession();
}

try {
return DefaultSessionData::fromDecodedTokenData(
(object) $token->claims()->get(self::SESSION_CLAIM, new stdClass()),
);
} catch (BadMethodCallException) {
return DefaultSessionData::newEmptySession();
}
}

/**
* @throws BadMethodCallException
* @throws InvalidArgumentException
*/
private function appendToken(
SessionInterface $sessionContainer,
Response $response,
Token|null $token,
SameOriginRequest $sameOriginRequest,
): Response {
$sessionContainerChanged = $sessionContainer->hasChanged();

if ($sessionContainerChanged && $sessionContainer->isEmpty()) {
return FigResponseCookies::set($response, $this->getExpirationCookie());
}

if ($sessionContainerChanged || $this->shouldTokenBeRefreshed($token)) {
return FigResponseCookies::set($response, $this->getTokenCookie($sessionContainer, $sameOriginRequest));
}

return $response;
}

private function shouldTokenBeRefreshed(Token|null $token): bool
{
if ($token === null) {
return false;
}

return $token->hasBeenIssuedBefore(
$this->config->getClock()
->now()
->sub(new DateInterval(sprintf('PT%sS', $this->config->getRefreshTime()))),
);
}

/** @throws BadMethodCallException */
private function getTokenCookie(SessionInterface $sessionContainer, SameOriginRequest $sameOriginRequest): SetCookie
{
$now = $this->config->getClock()->now();
$expiresAt = $now->add(new DateInterval(sprintf('PT%sS', $this->config->getIdleTimeout())));

$jwtConfiguration = $this->config->getJwtConfiguration();

$builder = $jwtConfiguration->builder(ChainedFormatter::withUnixTimestampDates())
->issuedAt($now)
->canOnlyBeUsedAfter($now)
->expiresAt($expiresAt)
->withClaim(self::SESSION_CLAIM, $sessionContainer);

$builder = $sameOriginRequest->configure($builder);

return $this
->config->getCookie()
->withValue(
$builder
->getToken($jwtConfiguration->signer(), $jwtConfiguration->signingKey())
->toString(),
)
->withExpires($expiresAt);
}

private function getExpirationCookie(): SetCookie
{
return $this
->config->getCookie()
->withValue(null)
->withExpires(
$this->config->getClock()
->now()
->modify('-30 days'),
);
}
}
33 changes: 33 additions & 0 deletions src/Storageless/Service/SessionStorage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/

declare(strict_types=1);

namespace PSR7Sessions\Storageless\Service;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use PSR7Sessions\Storageless\Session\SessionInterface;

interface SessionStorage
{
public function appendSession(SessionInterface $session, ServerRequestInterface $request, ResponseInterface|null $response = null, RequestHandlerInterface|null $handler = null): ResponseInterface;

public function getSession(ServerRequestInterface $request): SessionInterface;
}
Loading