Skip to content

Commit

Permalink
Merge pull request #79 from psr7-sessions/feature/remove-csrf-require…
Browse files Browse the repository at this point in the history
…ment

Enforce `SameSite=Lax`, PHP 7.2, PHPCS, PHPStan, Infection
  • Loading branch information
Ocramius authored Aug 6, 2018
2 parents 57dcf3d + 8d7a35f commit 7959dca
Show file tree
Hide file tree
Showing 15 changed files with 430 additions and 216 deletions.
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@ vendor
composer.lock
composer.phar
clover.xml
humbuglog.txt
humbuglog.json
infectionlog.txt
2 changes: 1 addition & 1 deletion .scrutinizer.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ before_commands:
build:
environment:
php:
version: 7.1.0
version: 7.2.0

tools:
external_code_coverage:
Expand Down
9 changes: 7 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ language: php
sudo: false

php:
- 7.1
- 7.2
- nightly

Expand All @@ -15,10 +14,16 @@ before_script:
- composer update --prefer-source --ignore-platform-reqs

script:
- ./vendor/bin/phpstan analyse
- ./vendor/bin/phpunit $PHPUNIT_FLAGS
- php examples/index.php > /dev/null
- if php -i |grep -qE xdebug; then ./vendor/bin/humbug; fi
- if php -i |grep -qE xdebug; then ./vendor/bin/infection --log-verbosity=none --threads=4; fi
- ./vendor/bin/phpcs

after_script:
- wget https://scrutinizer-ci.com/ocular.phar
- if [ -f clover.xml ]; then php ocular.phar code-coverage:upload --format=php-clover ./clover.xml; fi

matrix:
allow_failures:
- php: nightly
18 changes: 12 additions & 6 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,24 @@
}
],
"require": {
"php": "^7.1",
"php": "^7.2",
"ext-json": "*",
"psr/http-message": "^1.0.1",
"psr/http-server-handler": "^1.0.0",
"psr/http-server-middleware": "^1.0.0",
"lcobucci/jwt": "^3.2.2",
"dflydev/fig-cookies": "^1.0.2",
"lcobucci/jwt": "^3.2.3",
"dflydev/fig-cookies": "^2.0.0",
"lcobucci/clock": "^1.1.0"
},
"require-dev": {
"phpunit/phpunit": "^6.5.5",
"zendframework/zend-diactoros": "^1.7.0",
"humbug/humbug": "^1.0.0-rc.0"
"phpunit/phpunit": "^7.3.0",
"zendframework/zend-diactoros": "^1.8.4",
"infection/infection": "^0.9.2",
"phpstan/phpstan": "^0.10.2",
"phpstan/phpstan-phpunit": "^0.10",
"phpstan/phpstan-strict-rules": "^0.10.1",
"squizlabs/php_codesniffer": "^3.3.1",
"doctrine/coding-standard": "^4.0.0"
},
"replace": {
"ocramius/psr7-session": "self.version"
Expand Down
17 changes: 13 additions & 4 deletions examples/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use PSR7Sessions\Storageless\Http\SessionMiddleware;
use PSR7Sessions\Storageless\Session\SessionInterface;
use Zend\Diactoros\Response;
use Zend\Diactoros\Response\SapiEmitter;
use Zend\Diactoros\ServerRequestFactory;
Expand Down Expand Up @@ -53,16 +54,24 @@
);

$myMiddleware = new class implements RequestHandlerInterface {
public function handle(ServerRequestInterface $request) : ResponseInterface {
/* @var \PSR7Sessions\Storageless\Session\SessionInterface $session */
public function handle(ServerRequestInterface $request) : ResponseInterface
{
/** @var SessionInterface $session */
$session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
$session->set('counter', $session->get('counter', 0) + 1);

$counterValue = $session->get('counter', 0);

assert(is_int($counterValue));

$counterValue += 1;

$session->set('counter', $counterValue);

$response = new Response();

$response
->getBody()
->write('Counter Value: ' . $session->get('counter'));
->write('Counter Value: ' . $counterValue);

return $response;
}
Expand Down
3 changes: 1 addition & 2 deletions humbug.json.dist → infection.json.dist
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
},
"timeout": 10,
"logs": {
"text": "humbuglog.txt",
"json": "humbuglog.json"
"text": "infectionlog.txt"
}
}
24 changes: 24 additions & 0 deletions phpcs.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?xml version="1.0"?>
<ruleset
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd"
name="psr7-sessions/storageless"
>
<arg name="basepath" value="."/>
<arg name="extensions" value="php"/>
<arg name="parallel" value="80"/>
<arg name="cache" value=".phpcs-cache"/>
<arg name="colors" />

<!-- Ignore warnings and show progress of the run -->
<arg value="np"/>

<file>examples</file>
<file>src</file>
<file>test</file>

<rule ref="Doctrine">
<exclude name="SlevomatCodingStandard.Classes.SuperfluousInterfaceNaming"/>
</rule>
</ruleset>

47 changes: 47 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
parameters:
level: 7
paths:
- examples
- src
- test
polluteScopeWithLoopInitialAssignments: false
checkAlwaysTrueCheckTypeFunctionCall: true
checkAlwaysTrueInstanceof: true
checkAlwaysTrueStrictComparison: true
checkFunctionNameCase: true
includes:
- vendor/phpstan/phpstan-phpunit/extension.neon
- vendor/phpstan/phpstan-phpunit/rules.neon

rules:
- PHPStan\Rules\BooleansInConditions\BooleanInBooleanOrRule
- PHPStan\Rules\BooleansInConditions\BooleanInElseIfConditionRule
- PHPStan\Rules\BooleansInConditions\BooleanInIfConditionRule
- PHPStan\Rules\BooleansInConditions\BooleanInTernaryOperatorRule
- PHPStan\Rules\DisallowedConstructs\DisallowedEmptyRule
- PHPStan\Rules\DisallowedConstructs\DisallowedImplicitArrayCreationRule
- PHPStan\Rules\Functions\MissingFunctionParameterTypehintRule
- PHPStan\Rules\Functions\MissingFunctionReturnTypehintRule
- PHPStan\Rules\Methods\MissingMethodParameterTypehintRule
- PHPStan\Rules\Methods\MissingMethodReturnTypehintRule
- PHPStan\Rules\Methods\WrongCaseOfInheritedMethodRule
- PHPStan\Rules\Operators\OperandInArithmeticPostDecrementRule
- PHPStan\Rules\Operators\OperandInArithmeticPostIncrementRule
- PHPStan\Rules\Operators\OperandInArithmeticPreDecrementRule
- PHPStan\Rules\Operators\OperandInArithmeticPreIncrementRule
- PHPStan\Rules\Operators\OperandsInArithmeticAdditionRule
- PHPStan\Rules\Operators\OperandsInArithmeticDivisionRule
- PHPStan\Rules\Operators\OperandsInArithmeticExponentiationRule
- PHPStan\Rules\Operators\OperandsInArithmeticModuloRule
- PHPStan\Rules\Operators\OperandsInArithmeticMultiplicationRule
- PHPStan\Rules\Operators\OperandsInArithmeticSubtractionRule
- PHPStan\Rules\Properties\MissingPropertyTypehintRule
- PHPStan\Rules\StrictCalls\DynamicCallOnStaticMethodsRule
- PHPStan\Rules\StrictCalls\StrictFunctionCallsRule
- PHPStan\Rules\SwitchConditions\MatchingTypeInSwitchCaseConditionRule

services:
-
class: PHPStan\Rules\BooleansInConditions\BooleanRuleHelper
-
class: PHPStan\Rules\Operators\OperatorRuleHelper
54 changes: 18 additions & 36 deletions src/Storageless/Http/SessionMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
namespace PSR7Sessions\Storageless\Http;

use Dflydev\FigCookies\FigResponseCookies;
use Dflydev\FigCookies\Modifier\SameSite;
use Dflydev\FigCookies\SetCookie;
use Lcobucci\Clock\Clock;
use Lcobucci\Clock\SystemClock;
Expand All @@ -45,56 +46,30 @@ final class SessionMiddleware implements MiddlewareInterface
public const DEFAULT_COOKIE = 'slsession';
public const DEFAULT_REFRESH_TIME = 60;

/**
* @var Signer
*/
/** @var Signer */
private $signer;

/**
* @var string
*/
/** @var string */
private $signatureKey;

/**
* @var string
*/
/** @var string */
private $verificationKey;

/**
* @var int
*/
/** @var int */
private $expirationTime;

/**
* @var int
*/
/** @var int */
private $refreshTime;

/**
* @var Parser
*/
/** @var Parser */
private $tokenParser;

/**
* @var SetCookie
*/
/** @var SetCookie */
private $defaultCookie;

/**
* @var Clock
*/
/** @var Clock */
private $clock;

/**
* @param Signer $signer
* @param string $signatureKey
* @param string $verificationKey
* @param SetCookie $defaultCookie
* @param Parser $tokenParser
* @param int $expirationTime
* @param Clock $clock
* @param int $refreshTime
*/
public function __construct(
Signer $signer,
string $signatureKey,
Expand Down Expand Up @@ -127,6 +102,7 @@ public static function fromSymmetricKeyDefaults(string $symmetricKey, int $expir
SetCookie::create(self::DEFAULT_COOKIE)
->withSecure(true)
->withHttpOnly(true)
->withSameSite(SameSite::lax())
->withPath('/'),
new Parser(),
$expirationTime,
Expand All @@ -150,6 +126,7 @@ public static function fromAsymmetricKeyDefaults(
SetCookie::create(self::DEFAULT_COOKIE)
->withSecure(true)
->withHttpOnly(true)
->withSameSite(SameSite::lax())
->withPath('/'),
new Parser(),
$expirationTime,
Expand Down Expand Up @@ -207,8 +184,12 @@ private function parseToken(Request $request) : ?Token
*/
private function extractSessionContainer(?Token $token) : SessionInterface
{
if (! $token) {
return DefaultSessionData::newEmptySession();
}

try {
if (null === $token || ! $token->verify($this->signer, $this->verificationKey)) {
if (! $token->verify($this->signer, $this->verificationKey)) {
return DefaultSessionData::newEmptySession();
}

Expand Down Expand Up @@ -241,7 +222,7 @@ private function appendToken(SessionInterface $sessionContainer, Response $respo

private function shouldTokenBeRefreshed(?Token $token) : bool
{
if (! $token || ! $token->hasClaim(self::ISSUED_AT_CLAIM)) {
if (! ($token && $token->hasClaim(self::ISSUED_AT_CLAIM))) {
return false;
}

Expand All @@ -264,6 +245,7 @@ private function getTokenCookie(SessionInterface $sessionContainer) : SetCookie
->set(self::SESSION_CLAIM, $sessionContainer)
->sign($this->signer, $this->signatureKey)
->getToken()
->__toString()
)
->withExpires($timestamp + $this->expirationTime);
}
Expand Down
Loading

0 comments on commit 7959dca

Please sign in to comment.