From f05c587ca51304de69cd86f54892e2e85069cf83 Mon Sep 17 00:00:00 2001 From: ncou Date: Thu, 1 Oct 2020 18:52:14 +0200 Subject: [PATCH] update --- .editorconfig | 21 +++++ .gitattributes | 9 +++ .gitignore | 6 ++ .phplint.yml | 5 ++ .travis.yml | 26 ++++++ LICENSE.md | 21 +++++ README.md | 44 ++++++++++ composer.json | 35 ++++++++ phpcs.xml.dist | 25 ++++++ phpstan.neon.dist | 5 ++ phpunit.xml.dist | 18 +++++ src/Config/CsrfConfig.php | 130 ++++++++++++++++++++++++++++++ src/Middleware/CsrfFirewall.php | 98 ++++++++++++++++++++++ src/Middleware/CsrfMiddleware.php | 107 ++++++++++++++++++++++++ tests/.gitkeep | 0 15 files changed, 550 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 .phplint.yml create mode 100644 .travis.yml create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 composer.json create mode 100644 phpcs.xml.dist create mode 100644 phpstan.neon.dist create mode 100644 phpunit.xml.dist create mode 100644 src/Config/CsrfConfig.php create mode 100644 src/Middleware/CsrfFirewall.php create mode 100644 src/Middleware/CsrfMiddleware.php create mode 100644 tests/.gitkeep diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..5013243 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,21 @@ +; This file is for unifying the coding style for different editors and IDEs. +; More information at http://editorconfig.org + +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false + +[*.{yml,yaml}] +indent_size = 2 + +[*.bat] +end_of_line = crlf diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3c4e550 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# .gitattributes +/.gitattributes export-ignore +/.gitignore export-ignore +/.travis.yml export-ignore +/phpunit.xml.dist export-ignore +/tests export-ignore + +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ca3e78d --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/vendor/ +composer.lock +.phplint-cache +.phpcs-cache +.phpunit.result.cache +.idea/ diff --git a/.phplint.yml b/.phplint.yml new file mode 100644 index 0000000..0a32e1a --- /dev/null +++ b/.phplint.yml @@ -0,0 +1,5 @@ +path: ./src/ +extensions: + - php +exclude: + - vendor diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..22639ea --- /dev/null +++ b/.travis.yml @@ -0,0 +1,26 @@ +language: php + +notifications: + email: + on_success: never + +php: + - 7.3 + - 7.4 + +matrix: + fast_finish: true + include: + - php: 7.3 + env: dependencies=lowest + +cache: + directories: + - $HOME/.composer/cache + +before_script: + - composer install -n + - if [ "$dependencies" = "lowest" ]; then composer update --prefer-lowest --prefer-stable -n; fi; + +script: + - vendor/bin/phpunit diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..e2e2118 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 ncou + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..681eea0 --- /dev/null +++ b/README.md @@ -0,0 +1,44 @@ +# My Awesome Project + +This is the catchphrase: what does this project do and how is it unique? + +[![Build Status](https://img.shields.io/travis/org/PHP-DI/PHP-DI/master.svg?style=flat-square)](https://travis-ci.org/PHP-DI/PHP-DI) +[![Latest Version](https://img.shields.io/github/release/PHP-DI/PHP-DI.svg?style=flat-square)](https://packagist.org/packages/PHP-DI/php-di) +[![Total Downloads](https://img.shields.io/packagist/dt/PHP-DI/PHP-DI.svg?style=flat-square)](https://packagist.org/packages/PHP-DI/php-di) + +Here is an additional quick introduction, if necessary. + +## Why? + +Why does this project exist? Come on, don't delete this part. Fill it. +Yes it's hard, but it's perhaps the most important part of the README. + +As to why *this* project exist, it's to serve as a template for future open +source PHP projects. Of course, feel free to fork it and make your own recipe. + +## Installation + +Describe how to install the project/library/framework/… + +Make sure your installation instructions work by testing them! + +## Usage + +Describe how to use the project. A gif or a short code example is the best +way to show how it works. Also keep paragraphs short and sentences simple: not +everybody speaks english well. + +For the sake of the example here is how you can use this project template +as a basis for your own repository: + +```bash +git clone https://github.com/ncou/project-template.git my-project +cd my-project +# Remove the git repository metadata +rm -rf .git/ +# Start a brand new repository +git init +git add . +``` + +Easy peasy! Now you just have to code. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..29e4ff1 --- /dev/null +++ b/composer.json @@ -0,0 +1,35 @@ +{ + "name": "chiron/csrf", + "description": "Give it a nice description!", + "keywords": [], + "license": "MIT", + "type": "library", + "autoload": { + "psr-4": { + "Chiron\\Csrf\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Chiron\\Csrf\\Test\\": "tests/" + } + }, + "require": { + "php": "^7.2" + }, + "require-dev": { + "phpunit/phpunit": "^8.0", + "phpstan/phpstan": "^0.12", + "phpstan/phpstan-phpunit": "^0.12", + "overtrue/phplint": "^2.0", + "chiron/coding-standard": "^3.0" + }, + "scripts": { + "phpunit": "phpunit --colors=always", + "test-coverage": "phpunit --coverage-clover clover.xml", + "phpstan": "phpstan analyse --ansi", + "phplint": "phplint --ansi", + "check-style": "phpcs src tests", + "fix-style": "phpcbf src tests" + } +} diff --git a/phpcs.xml.dist b/phpcs.xml.dist new file mode 100644 index 0000000..0e40fac --- /dev/null +++ b/phpcs.xml.dist @@ -0,0 +1,25 @@ + + + PHP Coding Standards + + + + + + + + + + + + + + + + + src/ + tests/ + + + + diff --git a/phpstan.neon.dist b/phpstan.neon.dist new file mode 100644 index 0000000..1494f51 --- /dev/null +++ b/phpstan.neon.dist @@ -0,0 +1,5 @@ +parameters: + level: max + paths: + - src + - tests diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..e2aa834 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,18 @@ + + + + + + + tests/ + + + + + + src/ + + + + diff --git a/src/Config/CsrfConfig.php b/src/Config/CsrfConfig.php new file mode 100644 index 0000000..4e03325 --- /dev/null +++ b/src/Config/CsrfConfig.php @@ -0,0 +1,130 @@ + Expect::structure([ + 'debug' => Expect::bool()->default(setting('debug')), + 'charset' => Expect::string()->default(setting('charset')), // TODO : il faudrait pas refaire un test sur la validité du Charset ? comme c'est fait pour le settingsConfig ? + 'strict_variables' => Expect::bool()->default(false), + 'autoescape' => Expect::anyOf(false, Expect::string(), Expect::callable())->default('name'), + //'cache' => Expect::anyOf(false, Expect::string(), Expect::is(CacheInterface::class))->default(directory('@cache/twig/')), + 'cache' => Expect::anyOf(false, Expect::string(), Expect::object())->assert(Closure::fromCallable([$this, 'objectIsCacheInterface']), 'instanceof CacheInterface')->default(directory('@cache/twig/')), // TODO : on devrait peut etre ne pas gérer la possibilité de passer un objet Cache*Interface ca simplifierai le code non ???? + 'auto_reload' => Expect::bool()->default(setting('debug')), + 'optimizations' => Expect::anyOf(-1, 0)->default(-1), + ]), + // date settings + 'date' => Expect::structure([ + 'format' => Expect::string()->default('F j, Y H:i'), + 'interval_format' => Expect::string()->default('%d days'), + 'timezone' => Expect::string()->nullable()->default(setting('timezone')), // TODO : il faudrait pas refaire un test sur la validité du TimeZone ? comme c'est fait pour le settingsConfig ? Si on ajoute ce controle il ne sera plus nécessaire de lever d'exception dans la méthode "setTimeZone()" de la factory car on sera sur que le format de la timezone est correct !!!! + ]), + // number settings + 'number_format' => Expect::structure([ + 'decimals' => Expect::int()->default(0), + 'decimal_point' => Expect::string()->default('.'), + 'thousands_separator' => Expect::string()->default(','), + ]), + // generic parameters + // TODO : améliorer la vérification des tableaux pour bien vérifier le type d'objet qui sont autorisés dans ces tableaux !!! + 'extensions' => Expect::array(), // extension could be a string classename or an ExtensionInterface object. + 'functions' => Expect::array(), + 'filters' => Expect::array(), + 'globals' => Expect::arrayOf('string')->assert([Validator::class, 'isArrayAssociative'], 'associative array'), + 'facades' => Expect::array()->assert(Closure::fromCallable([$this, 'isValidFacadeArray']), 'facades array structure'), + 'lexer' => Expect::array(), + ]); + } + + public function getOptions(): array + { + return $this->get('options'); + } + + public function getFacades(): array + { + return $this->get('facades'); + } + + public function getGlobals(): array + { + return $this->get('globals'); + } + + public function getFunctions(): array + { + return $this->get('functions'); + } + + public function getFilters(): array + { + return $this->get('filters'); + } + + public function getExtensions(): array + { + return $this->get('extensions'); + } + + public function getLexer(): array + { + return $this->get('lexer'); + } + + public function getDate(): array + { + return $this->get('date'); + } + + public function getNumberFormat(): array + { + return $this->get('number_format'); + } + + private function objectIsCacheInterface($value): bool + { + if (! is_object($value)) { + // if it's not an object we ignore this validation. + return true; + } + + return Validator::is($value, CacheInterface::class); + } + + // The facades array structure should be : a string index (used as the facade name), and the value should be an array with at least an existing 'class' key. + private function isValidFacadeArray(array $facades): bool + { + foreach ($facades as $key => $value) { + if (! is_string($key)) { + return false; + } + + if (! is_array($value)) { + return false; + } + + if (! isset($value['class'])) { + return false; + } + } + + return true; + } +} diff --git a/src/Middleware/CsrfFirewall.php b/src/Middleware/CsrfFirewall.php new file mode 100644 index 0000000..c3ce6b4 --- /dev/null +++ b/src/Middleware/CsrfFirewall.php @@ -0,0 +1,98 @@ +responseFactory = $responseFactory; + $this->allowMethods = $allowMethods; + } + + /** + * {@inheritdoc} + */ + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + { + $token = $request->getAttribute(CsrfMiddleware::ATTRIBUTE); + + if (empty($token)) { + throw new \LogicException('Unable to apply CSRF firewall, attribute is missing'); + } + + if ($this->isRequired($request) && !hash_equals($token, $this->fetchToken($request))) { + return $this->responseFactory->createResponse(412, 'Bad CSRF Token'); + } + + return $handler->handle($request); + } + + /** + * Check if middleware should validate csrf token. + * + * @param ServerRequestInterface $request + * @return bool + */ + protected function isRequired(ServerRequestInterface $request): bool + { + return !in_array($request->getMethod(), $this->allowMethods, true); + } + + /** + * Fetch token from request. + * + * @param ServerRequestInterface $request + * @return string + */ + protected function fetchToken(ServerRequestInterface $request): string + { + if ($request->hasHeader(self::HEADER)) { + return (string)$request->getHeaderLine(self::HEADER); + } + + $data = $request->getParsedBody(); + if (is_array($data) && isset($data[self::PARAMETER]) && is_string($data[self::PARAMETER])) { + return $data[self::PARAMETER]; + } + + return ''; + } +} diff --git a/src/Middleware/CsrfMiddleware.php b/src/Middleware/CsrfMiddleware.php new file mode 100644 index 0000000..89fd08d --- /dev/null +++ b/src/Middleware/CsrfMiddleware.php @@ -0,0 +1,107 @@ +config = $config; + } + + /** + * {@inheritdoc} + */ + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + { + if (isset($request->getCookieParams()[$this->config->getCookie()])) { + $token = $request->getCookieParams()[$this->config->getCookie()]; + } else { + //Making new token + $token = $this->random($this->config->getTokenLength()); + + //Token cookie! + $cookie = $this->tokenCookie($token); + } + + //CSRF issues must be handled by Firewall middleware + $response = $handler->handle($request->withAttribute(static::ATTRIBUTE, $token)); + + if (!empty($cookie)) { + return $response->withAddedHeader('Set-Cookie', $cookie); + } + + return $response; + } + + /** + * Generate CSRF cookie. + * + * @param string $token + * @return string + */ + protected function tokenCookie(string $token): string + { + return Cookie::create( + $this->config->getCookie(), + $token, + $this->config->getCookieLifetime(), + null, + null, + $this->config->isCookieSecure(), + true, + $this->config->getSameSite() + )->createHeader(); + } + + /** + * Create a random string with desired length. + * + * @param int $length String length. 32 symbols by default. + * @return string + */ + private function random(int $length = 32): string + { + try { + if (empty($string = random_bytes($length))) { + throw new \RuntimeException('Unable to generate random string'); + } + } catch (\Throwable $e) { + throw new \RuntimeException('Unable to generate random string', $e->getCode(), $e); + } + + return substr(base64_encode($string), 0, $length); + } +} diff --git a/tests/.gitkeep b/tests/.gitkeep new file mode 100644 index 0000000..e69de29