added predis and eseye back in.

This commit is contained in:
2020-12-25 11:28:41 +00:00
parent 0ddd298350
commit 017f72b42e
670 changed files with 60992 additions and 10 deletions
+4
View File
@@ -0,0 +1,4 @@
# Contributing
This repository is a sub repository of [the JWT Framework](https://github.com/web-token/jwt-framework) project and is READ ONLY.
Please do not submit any Pull Requests here. It will be automatically closed.
+1
View File
@@ -0,0 +1 @@
patreon: FlorentMorselli
@@ -0,0 +1,3 @@
Please do not submit any Pull Requests here. It will be automatically closed.
You should submit it here: https://github.com/web-token/jwt-framework/pulls
+68
View File
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use function in_array;
use function is_string;
/**
* This class is a header parameter checker.
* When the "alg" header parameter is present, it will check if the value is within the allowed ones.
*/
final class AlgorithmChecker implements HeaderChecker
{
private const HEADER_NAME = 'alg';
/**
* @var bool
*/
private $protectedHeader = false;
/**
* @var string[]
*/
private $supportedAlgorithms;
/**
* @param string[] $supportedAlgorithms
*/
public function __construct(array $supportedAlgorithms, bool $protectedHeader = false)
{
$this->supportedAlgorithms = $supportedAlgorithms;
$this->protectedHeader = $protectedHeader;
}
/**
* {@inheritdoc}
*/
public function checkHeader($value): void
{
if (!is_string($value)) {
throw new InvalidHeaderException('"alg" must be a string.', self::HEADER_NAME, $value);
}
if (!in_array($value, $this->supportedAlgorithms, true)) {
throw new InvalidHeaderException('Unsupported algorithm.', self::HEADER_NAME, $value);
}
}
public function supportedHeader(): string
{
return self::HEADER_NAME;
}
public function protectedHeaderOnly(): bool
{
return $this->protectedHeader;
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use function in_array;
use function is_array;
use function is_string;
/**
* This class is a header parameter and claim checker.
* When the "aud" header parameter or claim is present, it will check if the value is within the allowed ones.
*/
final class AudienceChecker implements ClaimChecker, HeaderChecker
{
private const CLAIM_NAME = 'aud';
/**
* @var bool
*/
private $protectedHeader = false;
/**
* @var string
*/
private $audience;
public function __construct(string $audience, bool $protectedHeader = false)
{
$this->audience = $audience;
$this->protectedHeader = $protectedHeader;
}
/**
* {@inheritdoc}
*/
public function checkClaim($value): void
{
$this->checkValue($value, InvalidClaimException::class);
}
/**
* {@inheritdoc}
*/
public function checkHeader($value): void
{
$this->checkValue($value, InvalidHeaderException::class);
}
public function supportedClaim(): string
{
return self::CLAIM_NAME;
}
public function supportedHeader(): string
{
return self::CLAIM_NAME;
}
public function protectedHeaderOnly(): bool
{
return $this->protectedHeader;
}
/**
* @param mixed $value
*
* @throws InvalidClaimException if the claim is invalid
* @throws InvalidHeaderException if the header is invalid
*/
private function checkValue($value, string $class): void
{
if (is_string($value) && $value !== $this->audience) {
throw new $class('Bad audience.', self::CLAIM_NAME, $value);
}
if (is_array($value) && !in_array($this->audience, $value, true)) {
throw new $class('Bad audience.', self::CLAIM_NAME, $value);
}
if (!is_array($value) && !is_string($value)) {
throw new $class('Bad audience.', self::CLAIM_NAME, $value);
}
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
interface ClaimChecker
{
/**
* When the token has the applicable claim, the value is checked.
* If for some reason the value is not valid, an InvalidClaimException must be thrown.
*
* @param mixed $value
*
* @throws InvalidClaimException if the claim is invalid
*/
public function checkClaim($value): void;
/**
* The method returns the claim to be checked.
*/
public function supportedClaim(): string;
}
+97
View File
@@ -0,0 +1,97 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use function array_key_exists;
use function count;
/**
* This manager handles as many claim checkers as needed.
*/
class ClaimCheckerManager
{
/**
* @var ClaimChecker[]
*/
private $checkers = [];
/**
* @param ClaimChecker[] $checkers
*/
public function __construct(array $checkers)
{
foreach ($checkers as $checker) {
$this->add($checker);
}
}
/**
* This method returns all checkers handled by this manager.
*
* @return ClaimChecker[]
*/
public function getCheckers(): array
{
return $this->checkers;
}
/**
* This method checks all the claims passed as argument.
* All claims are checked against the claim checkers.
* If one fails, the InvalidClaimException is thrown.
*
* This method returns an array with all checked claims.
* It is up to the implementor to decide use the claims that have not been checked.
*
* @param string[] $mandatoryClaims
*
* @throws InvalidClaimException
* @throws MissingMandatoryClaimException
*/
public function check(array $claims, array $mandatoryClaims = []): array
{
$this->checkMandatoryClaims($mandatoryClaims, $claims);
$checkedClaims = [];
foreach ($this->checkers as $claim => $checker) {
if (array_key_exists($claim, $claims)) {
$checker->checkClaim($claims[$claim]);
$checkedClaims[$claim] = $claims[$claim];
}
}
return $checkedClaims;
}
private function add(ClaimChecker $checker): void
{
$claim = $checker->supportedClaim();
$this->checkers[$claim] = $checker;
}
/**
* @param string[] $mandatoryClaims
*
* @throws MissingMandatoryClaimException
*/
private function checkMandatoryClaims(array $mandatoryClaims, array $claims): void
{
if (0 === count($mandatoryClaims)) {
return;
}
$diff = array_keys(array_diff_key(array_flip($mandatoryClaims), $claims));
if (0 !== count($diff)) {
throw new MissingMandatoryClaimException(sprintf('The following claims are mandatory: %s.', implode(', ', $diff)), $diff);
}
}
}
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use InvalidArgumentException;
class ClaimCheckerManagerFactory
{
/**
* @var ClaimChecker[]
*/
private $checkers = [];
/**
* This method creates a Claim Checker Manager and populate it with the claim checkers found based on the alias.
* If the alias is not supported, an InvalidArgumentException is thrown.
*
* @param string[] $aliases
*/
public function create(array $aliases): ClaimCheckerManager
{
$checkers = [];
foreach ($aliases as $alias) {
if (!isset($this->checkers[$alias])) {
throw new InvalidArgumentException(sprintf('The claim checker with the alias "%s" is not supported.', $alias));
}
$checkers[] = $this->checkers[$alias];
}
return new ClaimCheckerManager($checkers);
}
/**
* This method adds a claim checker to this factory.
*/
public function add(string $alias, ClaimChecker $checker): void
{
$this->checkers[$alias] = $checker;
}
/**
* Returns all claim checker aliases supported by this factory.
*
* @return string[]
*/
public function aliases(): array
{
return array_keys($this->checkers);
}
/**
* Returns all claim checkers supported by this factory.
*
* @return ClaimChecker[]
*/
public function all(): array
{
return $this->checkers;
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use Throwable;
/**
* Exceptions thrown by this component.
*/
interface ClaimExceptionInterface extends Throwable
{
}
+86
View File
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use function is_float;
use function is_int;
/**
* This class is a claim checker.
* When the "exp" is present, it will compare the value with the current timestamp.
*/
final class ExpirationTimeChecker implements ClaimChecker, HeaderChecker
{
private const NAME = 'exp';
/**
* @var int
*/
private $allowedTimeDrift;
/**
* @var bool
*/
private $protectedHeaderOnly;
public function __construct(int $allowedTimeDrift = 0, bool $protectedHeaderOnly = false)
{
$this->allowedTimeDrift = $allowedTimeDrift;
$this->protectedHeaderOnly = $protectedHeaderOnly;
}
/**
* {@inheritdoc}
*
* @throws InvalidClaimException if the claim "exp" is not valid
*/
public function checkClaim($value): void
{
if (!is_float($value) && !is_int($value)) {
throw new InvalidClaimException('"exp" must be an integer.', self::NAME, $value);
}
if (time() > $value + $this->allowedTimeDrift) {
throw new InvalidClaimException('The token expired.', self::NAME, $value);
}
}
public function supportedClaim(): string
{
return self::NAME;
}
/**
* @param mixed $value
*
* @throws InvalidHeaderException if the claim "exp" is not valid
*/
public function checkHeader($value): void
{
if (!is_float($value) && !is_int($value)) {
throw new InvalidHeaderException('"exp" must be an integer.', self::NAME, $value);
}
if (time() > $value + $this->allowedTimeDrift) {
throw new InvalidHeaderException('The token expired.', self::NAME, $value);
}
}
public function supportedHeader(): string
{
return self::NAME;
}
public function protectedHeaderOnly(): bool
{
return $this->protectedHeaderOnly;
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
interface HeaderChecker
{
/**
* This method is called when the header parameter is present.
* If for some reason the value is not valid, an InvalidHeaderException must be thrown.
*
* @param mixed $value
*
* @throws InvalidHeaderException if the header parameter is invalid
*/
public function checkHeader($value): void;
/**
* The method returns the header parameter to be checked.
*/
public function supportedHeader(): string;
/**
* When true, the header parameter to be checked MUST be set in the protected header of the token.
*/
public function protectedHeaderOnly(): bool;
}
+169
View File
@@ -0,0 +1,169 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use function array_key_exists;
use function count;
use InvalidArgumentException;
use function is_array;
use Jose\Component\Core\JWT;
class HeaderCheckerManager
{
/**
* @var HeaderChecker[]
*/
private $checkers = [];
/**
* @var TokenTypeSupport[]
*/
private $tokenTypes = [];
/**
* HeaderCheckerManager constructor.
*
* @param HeaderChecker[] $checkers
* @param TokenTypeSupport[] $tokenTypes
*/
public function __construct(array $checkers, array $tokenTypes)
{
foreach ($checkers as $checker) {
$this->add($checker);
}
foreach ($tokenTypes as $tokenType) {
$this->addTokenTypeSupport($tokenType);
}
}
/**
* This method returns all checkers handled by this manager.
*
* @return HeaderChecker[]
*/
public function getCheckers(): array
{
return $this->checkers;
}
/**
* This method checks all the header parameters passed as argument.
* All header parameters are checked against the header parameter checkers.
* If one fails, the InvalidHeaderException is thrown.
*
* @param string[] $mandatoryHeaderParameters
*
* @throws InvalidArgumentException if the token format is not valid
*/
public function check(JWT $jwt, int $index, array $mandatoryHeaderParameters = []): void
{
foreach ($this->tokenTypes as $tokenType) {
if ($tokenType->supports($jwt)) {
$protected = [];
$unprotected = [];
$tokenType->retrieveTokenHeaders($jwt, $index, $protected, $unprotected);
$this->checkDuplicatedHeaderParameters($protected, $unprotected);
$this->checkMandatoryHeaderParameters($mandatoryHeaderParameters, $protected, $unprotected);
$this->checkHeaders($protected, $unprotected);
return;
}
}
throw new InvalidArgumentException('Unsupported token type.');
}
private function addTokenTypeSupport(TokenTypeSupport $tokenType): void
{
$this->tokenTypes[] = $tokenType;
}
private function add(HeaderChecker $checker): void
{
$header = $checker->supportedHeader();
$this->checkers[$header] = $checker;
}
/**
* @throws InvalidArgumentException if the header contains duplicated entries
*/
private function checkDuplicatedHeaderParameters(array $header1, array $header2): void
{
$inter = array_intersect_key($header1, $header2);
if (0 !== count($inter)) {
throw new InvalidArgumentException(sprintf('The header contains duplicated entries: %s.', implode(', ', array_keys($inter))));
}
}
/**
* @param string[] $mandatoryHeaderParameters
*
* @throws MissingMandatoryHeaderParameterException if a mandatory header parameter is missing
*/
private function checkMandatoryHeaderParameters(array $mandatoryHeaderParameters, array $protected, array $unprotected): void
{
if (0 === count($mandatoryHeaderParameters)) {
return;
}
$diff = array_keys(array_diff_key(array_flip($mandatoryHeaderParameters), array_merge($protected, $unprotected)));
if (0 !== count($diff)) {
throw new MissingMandatoryHeaderParameterException(sprintf('The following header parameters are mandatory: %s.', implode(', ', $diff)), $diff);
}
}
/**
* @throws InvalidHeaderException if a protected header parameter is not in the protected header
*/
private function checkHeaders(array $protected, array $header): void
{
$checkedHeaderParameters = [];
foreach ($this->checkers as $headerParameter => $checker) {
if ($checker->protectedHeaderOnly()) {
if (array_key_exists($headerParameter, $protected)) {
$checker->checkHeader($protected[$headerParameter]);
$checkedHeaderParameters[] = $headerParameter;
} elseif (array_key_exists($headerParameter, $header)) {
throw new InvalidHeaderException(sprintf('The header parameter "%s" must be protected.', $headerParameter), $headerParameter, $header[$headerParameter]);
}
} else {
if (array_key_exists($headerParameter, $protected)) {
$checker->checkHeader($protected[$headerParameter]);
$checkedHeaderParameters[] = $headerParameter;
} elseif (array_key_exists($headerParameter, $header)) {
$checker->checkHeader($header[$headerParameter]);
$checkedHeaderParameters[] = $headerParameter;
}
}
}
$this->checkCriticalHeader($protected, $header, $checkedHeaderParameters);
}
/**
* @throws InvalidHeaderException if the "crit" parameter is not valid or if a critical header parameter cannot be verified
*/
private function checkCriticalHeader(array $protected, array $header, array $checkedHeaderParameters): void
{
if (array_key_exists('crit', $protected)) {
if (!is_array($protected['crit'])) {
throw new InvalidHeaderException('The header "crit" must be a list of header parameters.', 'crit', $protected['crit']);
}
$diff = array_diff($protected['crit'], $checkedHeaderParameters);
if (0 !== count($diff)) {
throw new InvalidHeaderException(sprintf('One or more header parameters are marked as critical, but they are missing or have not been checked: %s.', implode(', ', array_values($diff))), 'crit', $protected['crit']);
}
} elseif (array_key_exists('crit', $header)) {
throw new InvalidHeaderException('The header parameter "crit" must be protected.', 'crit', $header['crit']);
}
}
}
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use InvalidArgumentException;
class HeaderCheckerManagerFactory
{
/**
* @var HeaderChecker[]
*/
private $checkers = [];
/**
* @var TokenTypeSupport[]
*/
private $tokenTypes = [];
/**
* This method creates a Header Checker Manager and populate it with the header parameter checkers found based on the alias.
* If the alias is not supported, an InvalidArgumentException is thrown.
*
* @param string[] $aliases
*
* @throws InvalidArgumentException if an alias is not supported
*/
public function create(array $aliases): HeaderCheckerManager
{
$checkers = [];
foreach ($aliases as $alias) {
if (!isset($this->checkers[$alias])) {
throw new InvalidArgumentException(sprintf('The header checker with the alias "%s" is not supported.', $alias));
}
$checkers[] = $this->checkers[$alias];
}
return new HeaderCheckerManager($checkers, $this->tokenTypes);
}
/**
* This method adds a header parameter checker to this factory.
* The checker is uniquely identified by an alias. This allows the same header parameter checker to be added twice (or more)
* using several configuration options.
*/
public function add(string $alias, HeaderChecker $checker): void
{
$this->checkers[$alias] = $checker;
}
/**
* This method adds a token type support to this factory.
*/
public function addTokenTypeSupport(TokenTypeSupport $tokenType): void
{
$this->tokenTypes[] = $tokenType;
}
/**
* Returns all header parameter checker aliases supported by this factory.
*
* @return string[]
*/
public function aliases(): array
{
return array_keys($this->checkers);
}
/**
* Returns all header parameter checkers supported by this factory.
*
* @return HeaderChecker[]
*/
public function all(): array
{
return $this->checkers;
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use Exception;
/**
* This exception is thrown by claim checkers when a claim check failed.
*/
class InvalidClaimException extends Exception implements ClaimExceptionInterface
{
/**
* @var string
*/
private $claim;
/**
* @var mixed
*/
private $value;
/**
* @param mixed $value
*/
public function __construct(string $message, string $claim, $value)
{
parent::__construct($message);
$this->claim = $claim;
$this->value = $value;
}
/**
* Returns the claim that caused the exception.
*/
public function getClaim(): string
{
return $this->claim;
}
/**
* Returns the claim value that caused the exception.
*
* @return mixed
*/
public function getValue()
{
return $this->value;
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use Exception;
/**
* This exception is thrown by header parameter checkers when a header parameter check failed.
*/
class InvalidHeaderException extends Exception
{
/**
* @var string
*/
private $header;
/**
* @var mixed
*/
private $value;
/**
* @param mixed $value
*/
public function __construct(string $message, string $header, $value)
{
parent::__construct($message);
$this->header = $header;
$this->value = $value;
}
/**
* Returns the header parameter that caused the exception.
*/
public function getHeader(): string
{
return $this->header;
}
/**
* Returns the header parameter value that caused the exception.
*
* @return mixed
*/
public function getValue()
{
return $this->value;
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use function is_float;
use function is_int;
/**
* This class is a claim checker.
* When the "iat" is present, it will compare the value with the current timestamp.
*/
final class IssuedAtChecker implements ClaimChecker, HeaderChecker
{
private const NAME = 'iat';
/**
* @var int
*/
private $allowedTimeDrift;
/**
* @var bool
*/
private $protectedHeaderOnly;
public function __construct(int $allowedTimeDrift = 0, bool $protectedHeaderOnly = false)
{
$this->allowedTimeDrift = $allowedTimeDrift;
$this->protectedHeaderOnly = $protectedHeaderOnly;
}
/**
* {@inheritdoc}
*
* @throws InvalidClaimException if the claim is invalid
*/
public function checkClaim($value): void
{
if (!is_float($value) && !is_int($value)) {
throw new InvalidClaimException('"iat" must be an integer.', self::NAME, $value);
}
if (time() < $value - $this->allowedTimeDrift) {
throw new InvalidClaimException('The JWT is issued in the future.', self::NAME, $value);
}
}
public function supportedClaim(): string
{
return self::NAME;
}
/**
* @param mixed $value
*
* @throws InvalidHeaderException if the header parameter is invalid
*/
public function checkHeader($value): void
{
if (!is_float($value) && !is_int($value)) {
throw new InvalidHeaderException('The header "iat" must be an integer.', self::NAME, $value);
}
if (time() < $value - $this->allowedTimeDrift) {
throw new InvalidHeaderException('The JWT is issued in the future.', self::NAME, $value);
}
}
public function supportedHeader(): string
{
return self::NAME;
}
public function protectedHeaderOnly(): bool
{
return $this->protectedHeaderOnly;
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use function in_array;
use function is_string;
/**
* This class is a header parameter and claim checker.
* When the "iss" header parameter or claim is present, it will check if the value is within the allowed ones.
*/
final class IssuerChecker implements ClaimChecker, HeaderChecker
{
private const CLAIM_NAME = 'iss';
/**
* @var bool
*/
private $protectedHeader = false;
/**
* @var array
*/
private $issuers;
public function __construct(array $issuer, bool $protectedHeader = false)
{
$this->issuers = $issuer;
$this->protectedHeader = $protectedHeader;
}
/**
* @param mixed $value
*
* @throws InvalidClaimException if the claim is invalid
*/
public function checkClaim($value): void
{
$this->checkValue($value, InvalidClaimException::class);
}
/**
* @param mixed $value
*
* @throws InvalidHeaderException if the header parameter is invalid
*/
public function checkHeader($value): void
{
$this->checkValue($value, InvalidHeaderException::class);
}
public function supportedClaim(): string
{
return self::CLAIM_NAME;
}
public function supportedHeader(): string
{
return self::CLAIM_NAME;
}
public function protectedHeaderOnly(): bool
{
return $this->protectedHeader;
}
/**
* @param mixed $value
*
* @throws InvalidClaimException if the claim is invalid
* @throws InvalidHeaderException if the header parameter is invalid
*/
private function checkValue($value, string $class): void
{
if (!is_string($value)) {
throw new $class('Invalid value.', self::CLAIM_NAME, $value);
}
if (!in_array($value, $this->issuers, true)) {
throw new $class('Unknown issuer.', self::CLAIM_NAME, $value);
}
}
}
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2019 Spomky-Labs
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.
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use Exception;
class MissingMandatoryClaimException extends Exception implements ClaimExceptionInterface
{
/**
* @var string[]
*/
private $claims;
/**
* MissingMandatoryClaimException constructor.
*
* @param string[] $claims
*/
public function __construct(string $message, array $claims)
{
parent::__construct($message);
$this->claims = $claims;
}
/**
* @return string[]
*/
public function getClaims(): array
{
return $this->claims;
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use Exception;
class MissingMandatoryHeaderParameterException extends Exception
{
/**
* @var string[]
*/
private $parameters;
/**
* MissingMandatoryHeaderParameterException constructor.
*
* @param string[] $parameters
*/
public function __construct(string $message, array $parameters)
{
parent::__construct($message);
$this->parameters = $parameters;
}
/**
* @return string[]
*/
public function getParameters(): array
{
return $this->parameters;
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use function is_float;
use function is_int;
/**
* This class is a claim checker.
* When the "nbf" is present, it will compare the value with the current timestamp.
*/
final class NotBeforeChecker implements ClaimChecker, HeaderChecker
{
private const NAME = 'nbf';
/**
* @var int
*/
private $allowedTimeDrift;
/**
* @var bool
*/
private $protectedHeaderOnly;
public function __construct(int $allowedTimeDrift = 0, bool $protectedHeaderOnly = false)
{
$this->allowedTimeDrift = $allowedTimeDrift;
$this->protectedHeaderOnly = $protectedHeaderOnly;
}
/**
* {@inheritdoc}
*
* @throws InvalidClaimException if the claim "nbf" is not an integer
* @throws InvalidClaimException if the claim "nbf" restrict the use of the token
*/
public function checkClaim($value): void
{
if (!is_float($value) && !is_int($value)) {
throw new InvalidClaimException('"nbf" must be an integer.', self::NAME, $value);
}
if (time() < $value - $this->allowedTimeDrift) {
throw new InvalidClaimException('The JWT can not be used yet.', self::NAME, $value);
}
}
public function supportedClaim(): string
{
return self::NAME;
}
/**
* @param mixed $value
*
* @throws InvalidHeaderException if the claim "nbf" is not an integer
* @throws InvalidHeaderException if the claim "nbf" restrict the use of the token
*/
public function checkHeader($value): void
{
if (!is_float($value) && !is_int($value)) {
throw new InvalidHeaderException('"nbf" must be an integer.', self::NAME, $value);
}
if (time() < $value - $this->allowedTimeDrift) {
throw new InvalidHeaderException('The JWT can not be used yet.', self::NAME, $value);
}
}
public function supportedHeader(): string
{
return self::NAME;
}
public function protectedHeaderOnly(): bool
{
return $this->protectedHeaderOnly;
}
}
+15
View File
@@ -0,0 +1,15 @@
PHP JWT Checker Component
=========================
This repository is a sub repository of [the JWT Framework](https://github.com/web-token/jwt-framework) project and is READ ONLY.
**Please do not submit any Pull Request here.**
You should go to [the main repository](https://github.com/web-token/jwt-framework) instead.
# Documentation
The official documentation is available as https://web-token.spomky-labs.com/
# Licence
This software is release under [MIT licence](LICENSE).
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker\Tests;
use Jose\Component\Checker\AlgorithmChecker;
use Jose\Component\Checker\InvalidHeaderException;
use PHPUnit\Framework\TestCase;
/**
* @group HeaderChecker
* @group functional
*
* @internal
*/
class AlgorithmHeaderCheckerTest extends TestCase
{
/**
* @test
*/
public function anAlgorithmMustBeAString(): void
{
$this->expectException(InvalidHeaderException::class);
$this->expectExceptionMessage('"alg" must be a string.');
$checker = new AlgorithmChecker(['foo']);
$checker->checkHeader(1);
}
/**
* @test
*/
public function theAlgorithmHeaderIsNotAllowed(): void
{
$this->expectException(InvalidHeaderException::class);
$this->expectExceptionMessage('Unsupported algorithm.');
$checker = new AlgorithmChecker(['foo']);
$checker->checkHeader('bar');
}
/**
* @test
*/
public function theAlgorithmHeaderIsSupported(): void
{
$checker = new AlgorithmChecker(['foo']);
$checker->checkHeader('foo');
static::assertFalse($checker->protectedHeaderOnly());
static::assertEquals('alg', $checker->supportedHeader());
}
}
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker\Tests;
use Jose\Component\Checker\AudienceChecker;
use Jose\Component\Checker\InvalidClaimException;
use PHPUnit\Framework\TestCase;
/**
* @group ClaimChecker
* @group functional
*
* @internal
*/
class AudienceClaimCheckerTest extends TestCase
{
/**
* @test
*/
public function anAudienceClaimMustBeAStringOrAnArrayOfStrings(): void
{
$this->expectException(InvalidClaimException::class);
$this->expectExceptionMessage('Bad audience.');
$checker = new AudienceChecker('foo');
$checker->checkClaim(1);
}
/**
* @test
*/
public function theAudienceClaimIsNotKnown(): void
{
$this->expectException(InvalidClaimException::class);
$this->expectExceptionMessage('Bad audience.');
$checker = new AudienceChecker('foo');
$checker->checkClaim('bar');
}
/**
* @test
*/
public function theAudienceClaimListDoesNotContainTheCurrentAudience(): void
{
$this->expectException(InvalidClaimException::class);
$this->expectExceptionMessage('Bad audience.');
$checker = new AudienceChecker('foo');
$checker->checkClaim(['bar']);
}
/**
* @test
*/
public function theAudienceClaimIsSupported(): void
{
$checker = new AudienceChecker('foo');
$checker->checkClaim('foo');
$checker->checkClaim(['foo']);
static::assertEquals('aud', $checker->supportedClaim());
}
}
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker\Tests;
use Jose\Component\Checker\AudienceChecker;
use Jose\Component\Checker\InvalidHeaderException;
use PHPUnit\Framework\TestCase;
/**
* @group HeaderChecker
* @group functional
*
* @internal
*/
class AudienceHeaderCheckerTest extends TestCase
{
/**
* @test
*/
public function anAudienceHeaderMustBeAStringOrAnArrayOfStrings(): void
{
$this->expectException(InvalidHeaderException::class);
$this->expectExceptionMessage('Bad audience.');
$checker = new AudienceChecker('foo');
$checker->checkHeader(1);
}
/**
* @test
*/
public function theAudienceHeaderIsNotKnown(): void
{
$this->expectException(InvalidHeaderException::class);
$this->expectExceptionMessage('Bad audience.');
$checker = new AudienceChecker('foo');
$checker->checkHeader('bar');
}
/**
* @test
*/
public function theAudienceHeaderListDoesNotContainTheCurrentAudience(): void
{
$this->expectException(InvalidHeaderException::class);
$this->expectExceptionMessage('Bad audience.');
$checker = new AudienceChecker('foo');
$checker->checkHeader(['bar']);
}
/**
* @test
*/
public function theAudienceHeaderIsSupported(): void
{
$checker = new AudienceChecker('foo');
$checker->checkHeader('foo');
$checker->checkHeader(['foo']);
static::assertFalse($checker->protectedHeaderOnly());
static::assertEquals('aud', $checker->supportedHeader());
}
}
@@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker\Tests;
use InvalidArgumentException;
use Jose\Component\Checker\AudienceChecker;
use Jose\Component\Checker\ClaimCheckerManagerFactory;
use Jose\Component\Checker\ExpirationTimeChecker;
use Jose\Component\Checker\IssuedAtChecker;
use Jose\Component\Checker\NotBeforeChecker;
use PHPUnit\Framework\TestCase;
/**
* @group ClaimChecker
* @group functional
*
* @internal
*/
class ClaimCheckerManagerFactoryTest extends TestCase
{
/**
* @var null|ClaimCheckerManagerFactory
*/
private $claimCheckerManagerFactory;
/**
* @test
*/
public function theAliasListOfTheClaimCheckerManagerFactoryIsAvailable(): void
{
static::assertEquals(['exp', 'iat', 'nbf', 'aud'], $this->getClaimCheckerManagerFactory()->aliases());
}
/**
* @test
*/
public function theAliasDoesNotExist(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('The claim checker with the alias "foo" is not supported.');
$this->getClaimCheckerManagerFactory()->create(['foo']);
}
/**
* @test
*/
public function iCanCreateAClaimCheckerManager(): void
{
$manager = $this->getClaimCheckerManagerFactory()->create(['exp', 'iat', 'nbf', 'aud']);
static::assertCount(4, $manager->getCheckers());
}
/**
* @test
*/
public function iCanCheckValidPayloadClaims(): void
{
$payload = [
'exp' => time() + 3600,
'iat' => time() - 1000,
'nbf' => time() - 100,
'foo' => 'bar',
];
$expected = $payload;
unset($expected['foo']);
$manager = $this->getClaimCheckerManagerFactory()->create(['exp', 'iat', 'nbf', 'aud']);
$result = $manager->check($payload);
static::assertEquals($expected, $result);
}
/**
* @test
*/
public function theMandatoryClaimsAreNotSet(): void
{
$this->expectException(\Jose\Component\Checker\MissingMandatoryClaimException::class);
$this->expectExceptionMessage('The following claims are mandatory: bar.');
$payload = [
'exp' => time() + 3600,
'iat' => time() - 1000,
'nbf' => time() - 100,
'foo' => 'bar',
];
$expected = $payload;
unset($expected['foo']);
$manager = $this->getClaimCheckerManagerFactory()->create(['exp', 'iat', 'nbf', 'aud']);
$manager->check($payload, ['exp', 'foo', 'bar']);
}
private function getClaimCheckerManagerFactory(): ClaimCheckerManagerFactory
{
if (null === $this->claimCheckerManagerFactory) {
$this->claimCheckerManagerFactory = new ClaimCheckerManagerFactory();
$this->claimCheckerManagerFactory->add('exp', new ExpirationTimeChecker());
$this->claimCheckerManagerFactory->add('iat', new IssuedAtChecker());
$this->claimCheckerManagerFactory->add('nbf', new NotBeforeChecker());
$this->claimCheckerManagerFactory->add('aud', new AudienceChecker('My Service'));
}
return $this->claimCheckerManagerFactory;
}
}
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker\Tests;
use Jose\Component\Checker\AudienceChecker;
use Jose\Component\Checker\ClaimCheckerManager;
use PHPUnit\Framework\TestCase;
/**
* @group ClaimChecker
* @group unit
*
* @internal
*/
final class ClaimCheckerManagerTest extends TestCase
{
/**
* @covers \Jose\Component\Checker\AudienceChecker
* @covers \Jose\Component\Checker\ClaimCheckerManager
* @test
*/
public function getCheckers(): void
{
$checkers = [
new AudienceChecker('some-expected-audience'),
];
$expectedCheckers = [
'aud' => $checkers[0],
];
$sut = new ClaimCheckerManager($checkers);
static::assertEquals(
$expectedCheckers,
$sut->getCheckers()
);
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker\Tests;
use Jose\Component\Checker\ExpirationTimeChecker;
use Jose\Component\Checker\InvalidClaimException;
use PHPUnit\Framework\TestCase;
/**
* @group ClaimChecker
* @group functional
*
* @internal
*/
class ExpirationTimeClaimCheckerTest extends TestCase
{
/**
* @test
*/
public function theExpirationTimeClaimMustBeAnInteger(): void
{
$this->expectException(InvalidClaimException::class);
$this->expectExceptionMessage('"exp" must be an integer.');
$checker = new ExpirationTimeChecker();
$checker->checkClaim('foo');
}
/**
* @test
*/
public function theExpirationTimeIsInThePast(): void
{
$this->expectException(InvalidClaimException::class);
$this->expectExceptionMessage('The token expired.');
$checker = new ExpirationTimeChecker();
$checker->checkClaim(time() - 1);
}
/**
* @test
*/
public function theExpirationTimeIsInTheFutur(): void
{
$checker = new ExpirationTimeChecker();
$checker->checkClaim(time() + 3600);
static::assertEquals('exp', $checker->supportedClaim());
}
}
@@ -0,0 +1,183 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker\Tests;
use InvalidArgumentException;
use Jose\Component\Checker\AudienceChecker;
use Jose\Component\Checker\HeaderCheckerManagerFactory;
use Jose\Component\Checker\InvalidHeaderException;
use Jose\Component\Checker\IssuerChecker;
use Jose\Component\Checker\MissingMandatoryHeaderParameterException;
use Jose\Component\Checker\Tests\Stub\OtherToken;
use Jose\Component\Checker\Tests\Stub\Token;
use Jose\Component\Checker\Tests\Stub\TokenSupport;
use PHPUnit\Framework\TestCase;
/**
* @group HeaderChecker
* @group functional
*
* @internal
*/
class HeaderCheckerManagerFactoryTest extends TestCase
{
/**
* @var null|HeaderCheckerManagerFactory
*/
private $headerCheckerManagerFactory;
/**
* @test
*/
public function theAliasListOfTheHeaderCheckerManagerFactoryIsAvailable(): void
{
static::assertEquals(['aud', 'iss'], $this->getHeaderCheckerManagerFactory()->aliases());
}
/**
* @test
*/
public function aHeaderMustNotContainDuplicatedHeaderParameters(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('The header contains duplicated entries: alg.');
$headerCheckerManager = $this->getHeaderCheckerManagerFactory()->create(['aud', 'iss']);
$payload = [];
$protected = ['alg' => 'foo'];
$unprotected = ['alg' => 'foo'];
$token = new Token(json_encode($payload), $protected, $unprotected);
$headerCheckerManager->check($token, 0);
}
/**
* @test
*/
public function theTokenHasCriticalHeaderNotSatisfied(): void
{
$this->expectException(InvalidHeaderException::class);
$this->expectExceptionMessage('One or more header parameters are marked as critical, but they are missing or have not been checked: alg.');
$headerCheckerManager = $this->getHeaderCheckerManagerFactory()->create(['aud', 'iss']);
$payload = [];
$protected = ['crit' => ['alg']];
$unprotected = [];
$token = new Token(json_encode($payload), $protected, $unprotected);
$headerCheckerManager->check($token, 0);
}
/**
* @test
*/
public function theHeaderIsSuccessfullyChecked(): void
{
$headerCheckerManager = $this->getHeaderCheckerManagerFactory()->create(['aud', 'iss']);
$payload = [];
$protected = ['crit' => ['aud'], 'aud' => 'My Service'];
$unprotected = ['iss' => 'Another Service'];
$token = new Token(json_encode($payload), $protected, $unprotected);
$headerCheckerManager->check($token, 0);
}
/**
* @test
*/
public function theCriticalHeaderParameterMustBeProtected(): void
{
$this->expectException(InvalidHeaderException::class);
$this->expectExceptionMessage('The header parameter "crit" must be protected.');
$headerCheckerManager = $this->getHeaderCheckerManagerFactory()->create(['aud', 'iss']);
$payload = [];
$protected = ['aud' => 'My Service'];
$unprotected = ['crit' => ['aud']];
$token = new Token(json_encode($payload), $protected, $unprotected);
$headerCheckerManager->check($token, 0);
}
/**
* @test
*/
public function theCriticalHeaderParameterMustBeAListOfHeaderParameters(): void
{
$this->expectException(InvalidHeaderException::class);
$this->expectExceptionMessage('The header "crit" must be a list of header parameters.');
$headerCheckerManager = $this->getHeaderCheckerManagerFactory()->create(['aud', 'iss']);
$payload = [];
$protected = ['aud' => 'My Service', 'crit' => true];
$unprotected = [];
$token = new Token(json_encode($payload), $protected, $unprotected);
$headerCheckerManager->check($token, 0);
}
/**
* @test
*/
public function theHeaderContainsUnknownParametersAndIsSuccessfullyChecked(): void
{
$headerCheckerManager = $this->getHeaderCheckerManagerFactory()->create(['aud', 'iss']);
$payload = [];
$protected = ['foo' => 'bar', 'iss' => 'Another Service'];
$unprotected = [];
$token = new Token(json_encode($payload), $protected, $unprotected);
$headerCheckerManager->check($token, 0);
}
/**
* @test
*/
public function theHeaderDoesNotContainSomeMandatoryParameters(): void
{
$this->expectException(MissingMandatoryHeaderParameterException::class);
$this->expectExceptionMessage('The following header parameters are mandatory: mandatory.');
$headerCheckerManager = $this->getHeaderCheckerManagerFactory()->create(['aud', 'iss']);
$payload = [];
$protected = ['aud' => 'Audience', 'iss' => 'Another Service'];
$unprotected = ['foo' => 'bar'];
$token = new Token(json_encode($payload), $protected, $unprotected);
$headerCheckerManager->check($token, 0, ['aud', 'iss', 'mandatory']);
}
/**
* @test
*/
public function iTryToCheckATokenThatIsNotSupported(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Unsupported token type.');
$headerCheckerManager = $this->getHeaderCheckerManagerFactory()->create(['aud', 'iss']);
$payload = [];
$protected = ['foo' => 'bar'];
$unprotected = [];
$token = new OtherToken(json_encode($payload), $protected, $unprotected);
$headerCheckerManager->check($token, 0);
}
private function getHeaderCheckerManagerFactory(): HeaderCheckerManagerFactory
{
if (null === $this->headerCheckerManagerFactory) {
$this->headerCheckerManagerFactory = new HeaderCheckerManagerFactory();
$this->headerCheckerManagerFactory->add('aud', new AudienceChecker('My Service', true));
$this->headerCheckerManagerFactory->add('iss', new IssuerChecker(['Another Service']));
$this->headerCheckerManagerFactory->addTokenTypeSupport(new TokenSupport());
}
return $this->headerCheckerManagerFactory;
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker\Tests;
use Jose\Component\Checker\InvalidClaimException;
use Jose\Component\Checker\IssuedAtChecker;
use PHPUnit\Framework\TestCase;
/**
* @group ClaimChecker
* @group functional
*
* @internal
*/
class IssuedAtClaimCheckerTest extends TestCase
{
/**
* @test
*/
public function anIssuedAtClaimMustBeAnInteger(): void
{
$this->expectException(InvalidClaimException::class);
$this->expectExceptionMessage('"iat" must be an integer.');
$checker = new IssuedAtChecker();
$checker->checkClaim('foo');
}
/**
* @test
*/
public function theIssuedAtClaimIsInTheFutur(): void
{
$this->expectException(InvalidClaimException::class);
$this->expectExceptionMessage('The JWT is issued in the future.');
$checker = new IssuedAtChecker();
$checker->checkClaim(time() + 3600);
}
/**
* @test
*/
public function theIssuedAtClaimIsInThePast(): void
{
$checker = new IssuedAtChecker();
$checker->checkClaim(time() - 3600);
static::assertEquals('iat', $checker->supportedClaim());
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker\Tests;
use Jose\Component\Checker\NotBeforeChecker;
use PHPUnit\Framework\TestCase;
/**
* @group ClaimChecker
* @group functional
*
* @internal
*/
class NotBeforeClaimCheckerTest extends TestCase
{
/**
* @test
*/
public function theNotBeforeClaimMustBeAnInteger(): void
{
$this->expectException(\Jose\Component\Checker\InvalidClaimException::class);
$this->expectExceptionMessage('"nbf" must be an integer.');
$checker = new NotBeforeChecker();
$checker->checkClaim('foo');
}
/**
* @test
*/
public function theNotBeforeClaimIsInTheFutur(): void
{
$this->expectException(\Jose\Component\Checker\InvalidClaimException::class);
$this->expectExceptionMessage('The JWT can not be used yet.');
$checker = new NotBeforeChecker();
$checker->checkClaim(time() + 3600);
}
/**
* @test
*/
public function theNotBeforeClaimIsInThePast(): void
{
$checker = new NotBeforeChecker();
$checker->checkClaim(time() - 3600);
static::assertEquals('nbf', $checker->supportedClaim());
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker\Tests\Stub;
use Jose\Component\Core\JWT;
class OtherToken implements JWT
{
/**
* @var null|string
*/
private $payload;
/**
* @var array
*/
private $protectedHeader;
/**
* @var array
*/
private $unprotectedHeader;
public function __construct(?string $payload, array $protectedHeader, array $unprotectedHeader)
{
$this->payload = $payload;
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
}
public function getPayload(): ?string
{
return $this->payload;
}
public function getProtectedHeader(): array
{
return $this->protectedHeader;
}
public function getUnprotectedHeader(): array
{
return $this->unprotectedHeader;
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker\Tests\Stub;
use Jose\Component\Core\JWT;
class Token implements JWT
{
/**
* @var null|string
*/
private $payload;
/**
* @var array
*/
private $protectedHeader;
/**
* @var array
*/
private $unprotectedHeader;
public function __construct(?string $payload, array $protectedHeader, array $unprotectedHeader)
{
$this->payload = $payload;
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
}
public function getPayload(): ?string
{
return $this->payload;
}
public function getProtectedHeader(): array
{
return $this->protectedHeader;
}
public function getUnprotectedHeader(): array
{
return $this->unprotectedHeader;
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker\Tests\Stub;
use InvalidArgumentException;
use Jose\Component\Checker\TokenTypeSupport;
use Jose\Component\Core\JWT;
class TokenSupport implements TokenTypeSupport
{
/**
* @throws InvalidArgumentException if the token is not supported
*/
public function retrieveTokenHeaders(JWT $jwt, int $index, array &$protectedHeader, array &$unprotectedHeader): void
{
if (!$jwt instanceof Token) {
throw new InvalidArgumentException('Unsupported token.');
}
$protectedHeader = $jwt->getProtectedHeader();
$unprotectedHeader = $jwt->getUnprotectedHeader();
}
public function supports(JWT $jwt): bool
{
return $jwt instanceof Token;
}
}
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker\Tests;
use Jose\Component\Checker\UnencodedPayloadChecker;
use PHPUnit\Framework\TestCase;
/**
* @group HeaderChecker
* @group functional
*
* @internal
*/
class UnencodedPayloadHeaderCheckerTest extends TestCase
{
/**
* @test
*/
public function theB64HeaderMustBeAnBoolean(): void
{
$this->expectException(\Jose\Component\Checker\InvalidHeaderException::class);
$this->expectExceptionMessage('"b64" must be a boolean.');
$checker = new UnencodedPayloadChecker();
$checker->checkHeader('foo');
}
/**
* @test
*/
public function theB64HeaderIsABoolean(): void
{
$checker = new UnencodedPayloadChecker();
$checker->checkHeader(true);
$checker->checkHeader(false);
static::assertTrue($checker->protectedHeaderOnly());
static::assertEquals('b64', $checker->supportedHeader());
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use Jose\Component\Core\JWT;
interface TokenTypeSupport
{
/**
* This method will retrieve the protect and unprotected headers of the token for the given index.
* The index is useful when the token is serialized using the Json General Serialization mode.
* For example the JWE Json General Serialization Mode allows several recipients to be set.
* The unprotected headers correspond to the share unprotected header and the selected recipient header.
*/
public function retrieveTokenHeaders(JWT $jwt, int $index, array &$protectedHeader, array &$unprotectedHeader): void;
/**
* This method returns true if the token in argument is supported, otherwise false.
*/
public function supports(JWT $jwt): bool;
}
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Checker;
use function is_bool;
/**
* This class is a header parameter checker.
* When the "b64" is present, it will check if the value is a boolean or not.
*
* The use of this checker will allow the use of token with unencoded payload.
*/
final class UnencodedPayloadChecker implements HeaderChecker
{
private const HEADER_NAME = 'b64';
/**
* {@inheritdoc}
*
* @throws InvalidHeaderException if the header parameter "b64" is not a boolean
*/
public function checkHeader($value): void
{
if (!is_bool($value)) {
throw new InvalidHeaderException('"b64" must be a boolean.', self::HEADER_NAME, $value);
}
}
public function supportedHeader(): string
{
return self::HEADER_NAME;
}
public function protectedHeaderOnly(): bool
{
return true;
}
}
+41
View File
@@ -0,0 +1,41 @@
{
"name": "web-token/jwt-checker",
"description": "Checker component of the JWT Framework.",
"type": "library",
"license": "MIT",
"keywords": ["JWS", "JWT", "JWE", "JWA", "JWK", "JWKSet", "Jot", "Jose", "RFC7515", "RFC7516", "RFC7517", "RFC7518", "RFC7519", "RFC7520", "Bundle", "Symfony"],
"homepage": "https://github.com/web-token",
"authors": [
{
"name": "Florent Morselli",
"homepage": "https://github.com/Spomky"
},{
"name": "All contributors",
"homepage": "https://github.com/web-token/jwt-checker/contributors"
}
],
"autoload": {
"psr-4": {
"Jose\\Component\\Checker\\": ""
}
},
"require": {
"web-token/jwt-core": "^2.1"
},
"require-dev": {
"phpunit/phpunit": "^8.0"
},
"extra": {
"branch-alias": {
"v1.0": "1.0.x-dev",
"v1.1": "1.1.x-dev",
"v1.2": "1.2.x-dev",
"v1.3": "1.3.x-dev",
"v2.0": "2.0.x-dev",
"v2.1": "2.1.x-dev"
}
},
"config": {
"sort-packages": true
}
}
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
backupGlobals="false"
backupStaticAttributes="false"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="true"
bootstrap="vendor/autoload.php"
colors="true">
<testsuites>
<testsuite name="Test Suite">
<directory>./Tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">./</directory>
<exclude>
<directory>./vendor</directory>
<directory>./Tests</directory>
<directory suffix="Test.php">./src</directory>
</exclude>
</whitelist>
</filter>
</phpunit>
+4
View File
@@ -0,0 +1,4 @@
# Contributing
This repository is a sub repository of [the JWT Framework](https://github.com/web-token/jwt-framework) project and is READ ONLY.
Please do not submit any Pull Requests here. It will be automatically closed.
+1
View File
@@ -0,0 +1 @@
patreon: FlorentMorselli
@@ -0,0 +1,3 @@
Please do not submit any Pull Requests here. It will be automatically closed.
You should submit it here: https://github.com/web-token/jwt-framework/pulls
+29
View File
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core;
interface Algorithm
{
/**
* Returns the name of the algorithm.
*/
public function name(): string;
/**
* Returns the key types suitable for this algorithm (e.g. "oct", "RSA"...).
*
* @return string[]
*/
public function allowedKeyTypes(): array;
}
+80
View File
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core;
use function array_key_exists;
use InvalidArgumentException;
class AlgorithmManager
{
/**
* @var array
*/
private $algorithms = [];
/**
* @param Algorithm[] $algorithms
*/
public function __construct(array $algorithms)
{
foreach ($algorithms as $algorithm) {
$this->add($algorithm);
}
}
/**
* Returns true if the algorithm is supported.
*
* @param string $algorithm The algorithm
*/
public function has(string $algorithm): bool
{
return array_key_exists($algorithm, $this->algorithms);
}
/**
* Returns the list of names of supported algorithms.
*
* @return string[]
*/
public function list(): array
{
return array_keys($this->algorithms);
}
/**
* Returns the algorithm if supported, otherwise throw an exception.
*
* @param string $algorithm The algorithm
*
* @throws InvalidArgumentException if the algorithm is not supported
*/
public function get(string $algorithm): Algorithm
{
if (!$this->has($algorithm)) {
throw new InvalidArgumentException(sprintf('The algorithm "%s" is not supported.', $algorithm));
}
return $this->algorithms[$algorithm];
}
/**
* Adds an algorithm to the manager.
*/
public function add(Algorithm $algorithm): void
{
$name = $algorithm->name();
$this->algorithms[$name] = $algorithm;
}
}
+80
View File
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core;
use InvalidArgumentException;
use function is_string;
class AlgorithmManagerFactory
{
/**
* @var array
*/
private $algorithms = [];
/**
* Adds an algorithm.
*
* Each algorithm is identified by an alias hence it is allowed to have the same algorithm twice (or more).
* This can be helpful when an algorithm have several configuration options.
*/
public function add(string $alias, Algorithm $algorithm): void
{
$this->algorithms[$alias] = $algorithm;
}
/**
* Returns the list of aliases.
*
* @return string[]
*/
public function aliases(): array
{
return array_keys($this->algorithms);
}
/**
* Returns all algorithms supported by this factory.
* This is an associative array. Keys are the aliases of the algorithms.
*
* @return Algorithm[]
*/
public function all(): array
{
return $this->algorithms;
}
/**
* Create an algorithm manager using the given aliases.
*
* @param string[] $aliases
*
* @throws InvalidArgumentException if the alias is invalid or is not supported
*/
public function create(array $aliases): AlgorithmManager
{
$algorithms = [];
foreach ($aliases as $alias) {
if (!is_string($alias)) {
throw new InvalidArgumentException('Invalid alias');
}
if (!isset($this->algorithms[$alias])) {
throw new InvalidArgumentException(sprintf('The algorithm with the alias "%s" is not supported.', $alias));
}
$algorithms[] = $this->algorithms[$alias];
}
return new AlgorithmManager($algorithms);
}
}
+143
View File
@@ -0,0 +1,143 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core;
use function array_key_exists;
use Base64Url\Base64Url;
use function in_array;
use InvalidArgumentException;
use function is_array;
use JsonSerializable;
class JWK implements JsonSerializable
{
/**
* @var array
*/
private $values = [];
/**
* Creates a JWK object using the given values.
* The member "kty" is mandatory. Other members are NOT checked.
*
* @throws InvalidArgumentException if the key parameter "kty" is missing
*/
public function __construct(array $values)
{
if (!isset($values['kty'])) {
throw new InvalidArgumentException('The parameter "kty" is mandatory.');
}
$this->values = $values;
}
/**
* Creates a JWK object using the given Json string.
*
* @throws InvalidArgumentException if the data is not valid
*
* @return JWK
*/
public static function createFromJson(string $json): self
{
$data = json_decode($json, true);
if (!is_array($data)) {
throw new InvalidArgumentException('Invalid argument.');
}
return new self($data);
}
/**
* Returns the values to be serialized.
*/
public function jsonSerialize(): array
{
return $this->values;
}
/**
* Get the value with a specific key.
*
* @param string $key The key
*
* @throws InvalidArgumentException if the key does not exist
*
* @return null|mixed
*/
public function get(string $key)
{
if (!$this->has($key)) {
throw new InvalidArgumentException(sprintf('The value identified by "%s" does not exist.', $key));
}
return $this->values[$key];
}
/**
* Returns true if the JWK has the value identified by.
*
* @param string $key The key
*/
public function has(string $key): bool
{
return array_key_exists($key, $this->values);
}
/**
* Get all values stored in the JWK object.
*
* @return array Values of the JWK object
*/
public function all(): array
{
return $this->values;
}
/**
* Returns the thumbprint of the key.
*
* @see https://tools.ietf.org/html/rfc7638
*
* @throws InvalidArgumentException if the hashing function is not supported
*/
public function thumbprint(string $hash_algorithm): string
{
if (!in_array($hash_algorithm, hash_algos(), true)) {
throw new InvalidArgumentException(sprintf('The hash algorithm "%s" is not supported.', $hash_algorithm));
}
$values = array_intersect_key($this->values, array_flip(['kty', 'n', 'e', 'crv', 'x', 'y', 'k']));
ksort($values);
$input = json_encode($values, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
return Base64Url::encode(hash($hash_algorithm, $input, true));
}
/**
* Returns the associated public key.
* This method has no effect for:
* - public keys
* - shared keys
* - unknown keys.
*
* Known keys are "oct", "RSA", "EC" and "OKP".
*
* @return JWK
*/
public function toPublic(): self
{
$values = array_diff_key($this->values, array_flip(['p', 'd', 'q', 'dp', 'dq', 'qi']));
return new self($values);
}
}
+338
View File
@@ -0,0 +1,338 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core;
use function array_key_exists;
use ArrayIterator;
use function count;
use Countable;
use function in_array;
use InvalidArgumentException;
use function is_array;
use IteratorAggregate;
use JsonSerializable;
use Traversable;
class JWKSet implements Countable, IteratorAggregate, JsonSerializable
{
/**
* @var array
*/
private $keys = [];
/**
* @param JWK[] $keys
*
* @throws InvalidArgumentException if the list is invalid
*/
public function __construct(array $keys)
{
foreach ($keys as $k => $key) {
if (!$key instanceof JWK) {
throw new InvalidArgumentException('Invalid list. Should only contains JWK objects');
}
if ($key->has('kid')) {
unset($keys[$k]);
$this->keys[$key->get('kid')] = $key;
} else {
$this->keys[] = $key;
}
}
}
/**
* Creates a JWKSet object using the given values.
*
* @throws InvalidArgumentException if the keyset is not valid
*
* @return JWKSet
*/
public static function createFromKeyData(array $data): self
{
if (!isset($data['keys'])) {
throw new InvalidArgumentException('Invalid data.');
}
if (!is_array($data['keys'])) {
throw new InvalidArgumentException('Invalid data.');
}
$jwkset = new self([]);
foreach ($data['keys'] as $key) {
$jwk = new JWK($key);
if ($jwk->has('kid')) {
$jwkset->keys[$jwk->get('kid')] = $jwk;
} else {
$jwkset->keys[] = $jwk;
}
}
return $jwkset;
}
/**
* Creates a JWKSet object using the given Json string.
*
* @throws InvalidArgumentException if the data is not valid
*
* @return JWKSet
*/
public static function createFromJson(string $json): self
{
$data = json_decode($json, true);
if (!is_array($data)) {
throw new InvalidArgumentException('Invalid argument.');
}
return self::createFromKeyData($data);
}
/**
* Returns an array of keys stored in the key set.
*
* @return JWK[]
*/
public function all(): array
{
return $this->keys;
}
/**
* Add key to store in the key set.
* This method is immutable and will return a new object.
*
* @return JWKSet
*/
public function with(JWK $jwk): self
{
$clone = clone $this;
if ($jwk->has('kid')) {
$clone->keys[$jwk->get('kid')] = $jwk;
} else {
$clone->keys[] = $jwk;
}
return $clone;
}
/**
* Remove key from the key set.
* This method is immutable and will return a new object.
*
* @param int|string $key Key to remove from the key set
*
* @return JWKSet
*/
public function without($key): self
{
if (!$this->has($key)) {
return $this;
}
$clone = clone $this;
unset($clone->keys[$key]);
return $clone;
}
/**
* Returns true if the key set contains a key with the given index.
*
* @param int|string $index
*/
public function has($index): bool
{
return array_key_exists($index, $this->keys);
}
/**
* Returns the key with the given index. Throws an exception if the index is not present in the key store.
*
* @param int|string $index
*
* @throws InvalidArgumentException if the index is not defined
*/
public function get($index): JWK
{
if (!$this->has($index)) {
throw new InvalidArgumentException('Undefined index.');
}
return $this->keys[$index];
}
/**
* Returns the values to be serialized.
*/
public function jsonSerialize(): array
{
return ['keys' => array_values($this->keys)];
}
/**
* Returns the number of keys in the key set.
*
* @param int $mode
*/
public function count($mode = COUNT_NORMAL): int
{
return count($this->keys, $mode);
}
/**
* Try to find a key that fits on the selected requirements.
* Returns null if not found.
*
* @param string $type Must be 'sig' (signature) or 'enc' (encryption)
* @param null|Algorithm $algorithm Specifies the algorithm to be used
* @param array $restrictions More restrictions such as 'kid' or 'kty'
*
* @throws InvalidArgumentException if the key type is not valid (must be "sig" or "enc")
*/
public function selectKey(string $type, ?Algorithm $algorithm = null, array $restrictions = []): ?JWK
{
if (!in_array($type, ['enc', 'sig'], true)) {
throw new InvalidArgumentException('Allowed key types are "sig" or "enc".');
}
$result = [];
foreach ($this->keys as $key) {
$ind = 0;
$can_use = $this->canKeyBeUsedFor($type, $key);
if (false === $can_use) {
continue;
}
$ind += $can_use;
$alg = $this->canKeyBeUsedWithAlgorithm($algorithm, $key);
if (false === $alg) {
continue;
}
$ind += $alg;
if (false === $this->doesKeySatisfyRestrictions($restrictions, $key)) {
continue;
}
$result[] = ['key' => $key, 'ind' => $ind];
}
if (0 === count($result)) {
return null;
}
usort($result, [$this, 'sortKeys']);
return $result[0]['key'];
}
/**
* Internal method only. Should not be used.
*
* @internal
* @internal
*/
public static function sortKeys(array $a, array $b): int
{
if ($a['ind'] === $b['ind']) {
return 0;
}
return ($a['ind'] > $b['ind']) ? -1 : 1;
}
/**
* Internal method only. Should not be used.
*
* @internal
*/
public function getIterator(): Traversable
{
return new ArrayIterator($this->keys);
}
/**
* @throws InvalidArgumentException if the key does not fulfill with the "key_ops" constraint
*
* @return bool|int
*/
private function canKeyBeUsedFor(string $type, JWK $key)
{
if ($key->has('use')) {
return $type === $key->get('use') ? 1 : false;
}
if ($key->has('key_ops')) {
$key_ops = $key->get('key_ops');
if (!is_array($key_ops)) {
throw new InvalidArgumentException('Invalid key parameter "key_ops". Should be a list of key operations');
}
return $type === self::convertKeyOpsToKeyUse($key_ops) ? 1 : false;
}
return 0;
}
/**
* @return bool|int
*/
private function canKeyBeUsedWithAlgorithm(?Algorithm $algorithm, JWK $key)
{
if (null === $algorithm) {
return 0;
}
if (!in_array($key->get('kty'), $algorithm->allowedKeyTypes(), true)) {
return false;
}
if ($key->has('alg')) {
return $algorithm->name() === $key->get('alg') ? 2 : false;
}
return 1;
}
private function doesKeySatisfyRestrictions(array $restrictions, JWK $key): bool
{
foreach ($restrictions as $k => $v) {
if (!$key->has($k) || $v !== $key->get($k)) {
return false;
}
}
return true;
}
/**
* @throws InvalidArgumentException if the key operation is not supported
*/
private static function convertKeyOpsToKeyUse(array $key_ops): string
{
switch (true) {
case in_array('verify', $key_ops, true):
case in_array('sign', $key_ops, true):
return 'sig';
case in_array('encrypt', $key_ops, true):
case in_array('decrypt', $key_ops, true):
case in_array('wrapKey', $key_ops, true):
case in_array('unwrapKey', $key_ops, true):
case in_array('deriveKey', $key_ops, true):
case in_array('deriveBits', $key_ops, true):
return 'enc';
default:
throw new InvalidArgumentException(sprintf('Unsupported key operation value "%s"', $key_ops));
}
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core;
interface JWT
{
/**
* Returns the payload of the JWT.
* null is a valid payload (e.g. JWS with detached payload).
*/
public function getPayload(): ?string;
}
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2019 Spomky-Labs
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.
+15
View File
@@ -0,0 +1,15 @@
PHP JWT Core Component
======================
This repository is a sub repository of [the JWT Framework](https://github.com/web-token/jwt-framework) project and is READ ONLY.
**Please do not submit any Pull Request here.**
You should go to [the main repository](https://github.com/web-token/jwt-framework) instead.
# Documentation
The official documentation is available as https://web-token.spomky-labs.com/
# Licence
This software is release under [MIT licence](LICENSE).
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core\Tests;
use InvalidArgumentException;
use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Core\AlgorithmManagerFactory;
use PHPUnit\Framework\TestCase;
use TypeError;
/**
* @group unit
* @group JWAManager
*
* @internal
*/
class AlgorithmManagerFactoryTest extends TestCase
{
/**
* @var null|AlgorithmManagerFactory
*/
private $algorithmManagerFactory;
/**
* @test
* @covers \Jose\Component\Core\AlgorithmManagerFactory
*/
public function iCanListSupportedAliases(): void
{
static::assertEquals(['foo'], $this->getAlgorithmManagerFactory()->aliases());
static::assertEquals(['foo'], array_keys($this->getAlgorithmManagerFactory()->all()));
}
/**
* @test
* @covers \Jose\Component\Core\AlgorithmManager
*/
public function iCannotCreateAnAlgorithmManagerWithABadArgument(): void
{
$this->expectException(TypeError::class);
new AlgorithmManager(['foo']);
}
/**
* @test
* @covers \Jose\Component\Core\AlgorithmManager
*/
public function iCannotGetAnAlgorithmThatDoesNotExist(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('The algorithm "HS384" is not supported.');
$manager = new AlgorithmManager([new FooAlgorithm()]);
static::assertEquals(['foo'], $manager->list());
static::assertTrue($manager->has('foo'));
static::assertFalse($manager->has('HS384'));
$manager->get('HS384');
}
private function getAlgorithmManagerFactory(): AlgorithmManagerFactory
{
if (null === $this->algorithmManagerFactory) {
$this->algorithmManagerFactory = new AlgorithmManagerFactory();
$this->algorithmManagerFactory->add('foo', new FooAlgorithm());
}
return $this->algorithmManagerFactory;
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core\Tests;
use Jose\Component\Core\Algorithm;
class FooAlgorithm implements Algorithm
{
public function name(): string
{
return 'foo';
}
public function allowedKeyTypes(): array
{
return ['FOO'];
}
}
+286
View File
@@ -0,0 +1,286 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core\Tests;
use function count;
use InvalidArgumentException;
use Jose\Component\Core\JWK;
use Jose\Component\Core\JWKSet;
use PHPUnit\Framework\TestCase;
/**
* @group unit
* @group JWKSet
*
* @internal
*/
class JWKSetTest extends TestCase
{
/**
* @test
*/
public function iCanSelectAKeyInAKeySet(): void
{
$jwkset = $this->getPublicKeySet();
$jwk = $jwkset->selectKey('enc');
static::assertInstanceOf(JWK::class, $jwk);
}
/**
* @test
*/
public function iCannotSelectAKeyFromAKeySetWithUnsupportedUsageParameter(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Allowed key types are "sig" or "enc".');
$jwkset = $this->getPublicKeySet();
$jwkset->selectKey('foo');
}
/**
* @test
*/
public function iCannotCreateAKeySetWithBadArguments(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid data.');
JWKSet::createFromKeyData(['keys' => true]);
}
/**
* @test
*/
public function iCanGetAllKeysInAKeySet(): void
{
$jwkset = $this->getPublicKeySet();
static::assertEquals(3, count($jwkset->all()));
}
/**
* @test
*/
public function iCanAddKeysInAKeySet(): void
{
$jwkset = $this->getPublicKeySet();
$new_jwkset = $jwkset->with(new JWK(['kty' => 'none']));
static::assertEquals(4, count($new_jwkset->all()));
static::assertNotSame($jwkset, $new_jwkset);
}
/**
* @test
*/
public function iCanSelectAKeyWithAlgorithm(): void
{
$jwkset = $this->getPublicKeySet();
$jwk = $jwkset->selectKey('enc', new FooAlgorithm());
static::assertInstanceOf(JWK::class, $jwk);
static::assertEquals(
[
'kid' => '71ee230371d19630bc17fb90ccf20ae632ad8cf8',
'kty' => 'FOO',
'alg' => 'foo',
'use' => 'enc',
],
$jwk->all()
);
}
/**
* @test
*/
public function iCanSelectAKeyWithAlgorithmAndKeyId(): void
{
$jwkset = $this->getPublicKeySet();
$jwk = $jwkset->selectKey('sig', new FooAlgorithm(), ['kid' => '02491f945c951adf156f370788e8ccdabf8877a8']);
static::assertInstanceOf(JWK::class, $jwk);
static::assertEquals(
[
'kid' => '02491f945c951adf156f370788e8ccdabf8877a8',
'kty' => 'FOO',
'alg' => 'foo',
'use' => 'sig',
],
$jwk->all()
);
}
/**
* @test
*/
public function iCanSelectAKeyWithWithKeyId(): void
{
$jwkset = $this->getPublicKeySet();
$jwk = $jwkset->selectKey('sig', null, ['kid' => '02491f945c951adf156f370788e8ccdabf8877a8']);
static::assertInstanceOf(JWK::class, $jwk);
static::assertEquals(
[
'kid' => '02491f945c951adf156f370788e8ccdabf8877a8',
'kty' => 'FOO',
'alg' => 'foo',
'use' => 'sig',
],
$jwk->all()
);
}
/**
* @test
*/
public function theKeySetDoesNotContainsSuitableAKeyThatFitsOnTheRequirements(): void
{
$jwkset = $this->getPublicKeySet();
$jwk = $jwkset->selectKey('enc', null, ['kid' => '02491f945c951adf156f370788e8ccdabf8877a8']);
static::assertNull($jwk);
}
/**
* @test
*/
public function iCanCreateAKeySetUsingValues(): void
{
$values = ['keys' => [[
'kid' => '71ee230371d19630bc17fb90ccf20ae632ad8cf8',
'kty' => 'FOO',
'alg' => 'foo',
'use' => 'sig',
]]];
$jwkset = JWKSet::createFromKeyData($values);
static::assertEquals(1, count($jwkset));
static::assertTrue($jwkset->has('71ee230371d19630bc17fb90ccf20ae632ad8cf8'));
static::assertFalse($jwkset->has(0));
}
/**
* @test
*/
public function keySet(): void
{
$jwk1 = new JWK([
'kty' => 'EC',
'crv' => 'P-256',
'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU',
'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0',
'use' => 'sign',
'key_ops' => ['sign'],
'alg' => 'ES256',
'kid' => '0123456789',
]);
$jwk2 = new JWK([
'kty' => 'EC',
'crv' => 'P-256',
'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU',
'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0',
'd' => 'jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI',
'use' => 'sign',
'key_ops' => ['verify'],
'alg' => 'ES256',
'kid' => '9876543210',
]);
$jwkset = new JWKSet([$jwk1]);
$jwkset = $jwkset->with($jwk2);
static::assertEquals('{"keys":[{"kty":"EC","crv":"P-256","x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU","y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0","use":"sign","key_ops":["sign"],"alg":"ES256","kid":"0123456789"},{"kty":"EC","crv":"P-256","x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU","y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0","d":"jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI","use":"sign","key_ops":["verify"],"alg":"ES256","kid":"9876543210"}]}', json_encode($jwkset));
static::assertEquals(2, count($jwkset));
static::assertEquals(2, $jwkset->count());
static::assertTrue($jwkset->has('0123456789'));
static::assertTrue($jwkset->has('9876543210'));
static::assertFalse($jwkset->has(0));
foreach ($jwkset as $key) {
static::assertEquals('EC', $key->get('kty'));
}
static::assertEquals('9876543210', $jwkset->get('9876543210')->get('kid'));
$jwkset = $jwkset->without('9876543210');
$jwkset = $jwkset->without('9876543210');
static::assertEquals(1, count($jwkset));
static::assertEquals(1, $jwkset->count());
$jwkset = $jwkset->without('0123456789');
static::assertEquals(0, $jwkset->count());
}
/**
* @test
*/
public function keySet2(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Undefined index.');
$jwk1 = new JWK([
'kty' => 'EC',
'crv' => 'P-256',
'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU',
'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0',
'use' => 'sign',
'key_ops' => ['sign'],
'alg' => 'ES256',
'kid' => '0123456789',
]);
$jwk2 = new JWK([
'kty' => 'EC',
'crv' => 'P-256',
'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU',
'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0',
'd' => 'jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI',
'use' => 'sign',
'key_ops' => ['verify'],
'alg' => 'ES256',
'kid' => '9876543210',
]);
$jwkset = new JWKSet([$jwk1, $jwk2]);
$jwkset->get(2);
}
private function getPublicKeySet(): JWKSet
{
$keys = ['keys' => [
[
'kid' => '71ee230371d19630bc17fb90ccf20ae632ad8cf8',
'kty' => 'FOO',
'alg' => 'foo',
'use' => 'enc',
],
[
'kid' => '02491f945c951adf156f370788e8ccdabf8877a8',
'kty' => 'FOO',
'alg' => 'foo',
'use' => 'sig',
],
[
'kty' => 'EC',
'crv' => 'P-256',
'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU',
'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0',
],
]];
return JWKSet::createFromKeyData($keys);
}
}
+147
View File
@@ -0,0 +1,147 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core\Tests;
use InvalidArgumentException;
use Jose\Component\Core\JWK;
use PHPUnit\Framework\TestCase;
/**
* @group unit
* @group JWK
*
* @internal
*/
class JWKTest extends TestCase
{
/**
* @test
*/
public function aKeyContainsAllExpectedParameters(): void
{
$jwk = new JWK([
'kty' => 'EC',
'crv' => 'P-256',
'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU',
'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0',
'use' => 'sig',
'key_ops' => ['sign'],
'alg' => 'ES256',
'bar' => 'plic',
]);
static::assertEquals('EC', $jwk->get('kty'));
static::assertEquals('ES256', $jwk->get('alg'));
static::assertEquals('sig', $jwk->get('use'));
static::assertFalse($jwk->has('kid'));
static::assertEquals(['sign'], $jwk->get('key_ops'));
static::assertEquals('P-256', $jwk->get('crv'));
static::assertFalse($jwk->has('x5u'));
static::assertFalse($jwk->has('x5c'));
static::assertFalse($jwk->has('x5t'));
static::assertFalse($jwk->has('x5t#256'));
static::assertEquals('f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU', $jwk->get('x'));
static::assertEquals('x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0', $jwk->get('y'));
static::assertEquals('{"kty":"EC","crv":"P-256","x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU","y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0","use":"sig","key_ops":["sign"],"alg":"ES256","bar":"plic"}', json_encode($jwk));
static::assertEquals('oKIywvGUpTVTyxMQ3bwIIeQUudfr_CkLMjCE19ECD-U', $jwk->thumbprint('sha256'));
static::assertEquals('EMMMl6Rj75mqhcABihxxl_VCN9s', $jwk->thumbprint('sha1'));
static::assertEquals('dqwHnan4iJ1_eEll-o4Egw', $jwk->thumbprint('md5'));
}
/**
* @test
*/
public function iCannotGetTheThumbprintOfTheKeyWhenIUseAnUnsupportedHashingAlgorithm(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('The hash algorithm "foo" is not supported.');
$jwk = new JWK([
'kty' => 'EC',
'crv' => 'P-256',
'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU',
'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0',
'use' => 'sig',
'key_ops' => ['sign'],
'alg' => 'ES256',
'bar' => 'plic',
]);
$jwk->thumbprint('foo');
}
/**
* @test
*/
public function iMustSetAtLeastTheKtyParameter(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('The parameter "kty" is mandatory.');
new JWK([]);
}
/**
* @test
*/
public function iCannotGetAParameterThatDoesNotExist(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('The value identified by "ABCD" does not exist.');
$jwk = new JWK([
'kty' => 'EC',
'crv' => 'P-256',
'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU',
'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0',
'use' => 'sign',
'key_ops' => ['sign'],
'alg' => 'ES256',
'bar' => 'plic',
]);
$jwk->get('ABCD');
}
/**
* @test
*/
public function iCanConvertAPrivateKeyIntoPublicKey(): void
{
$private = new JWK([
'kty' => 'EC',
'crv' => 'P-256',
'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU',
'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0',
'd' => 'jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI',
'use' => 'sign',
'key_ops' => ['verify'],
'alg' => 'ES256',
'kid' => '9876543210',
]);
$public = $private->toPublic();
static::assertEquals(json_encode([
'kty' => 'EC',
'crv' => 'P-256',
'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU',
'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0',
'use' => 'sign',
'key_ops' => ['verify'],
'alg' => 'ES256',
'kid' => '9876543210',
]), json_encode($public));
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core\Tests;
use Jose\Component\Core\Util\JsonConverter;
use PHPUnit\Framework\TestCase;
/**
* @group unit
* @group JsonConverter
*
* @internal
*/
class JsonConverterTest extends TestCase
{
/**
* @test
*/
public function iCanConvertAnObjectIntoAJsonString(): void
{
static::assertEquals('{"foo":"BAR"}', JsonConverter::encode(['foo' => 'BAR']));
static::assertEquals(['foo' => 'BAR'], JsonConverter::decode('{"foo":"BAR"}'));
}
}
+223
View File
@@ -0,0 +1,223 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core\Util;
use Brick\Math\BigInteger as BrickBigInteger;
use function chr;
/**
* @internal
*/
class BigInteger
{
/**
* Holds the BigInteger's value.
*
* @var BrickBigInteger
*/
private $value;
private function __construct(BrickBigInteger $value)
{
$this->value = $value;
}
/**
* @return BigInteger
*/
public static function createFromBinaryString(string $value): self
{
$data = current(unpack('H*', $value));
return new self(BrickBigInteger::fromBase($data, 16));
}
/**
* @return BigInteger
*/
public static function createFromDecimal(int $value): self
{
return new self(BrickBigInteger::of($value));
}
/**
* @return BigInteger
*/
public static function createFromBigInteger(BrickBigInteger $value): self
{
return new self($value);
}
/**
* Converts a BigInteger to a binary string.
*/
public function toBytes(): string
{
if ($this->value->isEqualTo(BrickBigInteger::zero())) {
return '';
}
$temp = $this->value->toBase(16);
$temp = 0 !== (mb_strlen($temp, '8bit') & 1) ? '0'.$temp : $temp;
$temp = hex2bin($temp);
return ltrim($temp, chr(0));
}
/**
* Adds two BigIntegers.
*
* @param BigInteger $y
*
* @return BigInteger
*/
public function add(self $y): self
{
$value = $this->value->plus($y->value);
return new self($value);
}
/**
* Subtracts two BigIntegers.
*
* @param BigInteger $y
*
* @return BigInteger
*/
public function subtract(self $y): self
{
$value = $this->value->minus($y->value);
return new self($value);
}
/**
* Multiplies two BigIntegers.
*
* @param BigInteger $x
*
* @return BigInteger
*/
public function multiply(self $x): self
{
$value = $this->value->multipliedBy($x->value);
return new self($value);
}
/**
* Divides two BigIntegers.
*
* @param BigInteger $x
*
* @return BigInteger
*/
public function divide(self $x): self
{
$value = $this->value->dividedBy($x->value);
return new self($value);
}
/**
* Performs modular exponentiation.
*
* @param BigInteger $e
* @param BigInteger $n
*
* @return BigInteger
*/
public function modPow(self $e, self $n): self
{
$value = $this->value->modPow($e->value, $n->value);
return new self($value);
}
/**
* Performs modular exponentiation.
*
* @param BigInteger $d
*
* @return BigInteger
*/
public function mod(self $d): self
{
$value = $this->value->mod($d->value);
return new self($value);
}
public function modInverse(BigInteger $m): BigInteger
{
return new self($this->value->modInverse($m->value));
}
/**
* Compares two numbers.
*
* @param BigInteger $y
*/
public function compare(self $y): int
{
return $this->value->compareTo($y->value);
}
/**
* @param BigInteger $y
*/
public function equals(self $y): bool
{
return $this->value->isEqualTo($y->value);
}
/**
* @param BigInteger $y
*
* @return BigInteger
*/
public static function random(self $y): self
{
return new self(BrickBigInteger::randomRange(0, $y->value));
}
/**
* @param BigInteger $y
*
* @return BigInteger
*/
public function gcd(self $y): self
{
return new self($this->value->gcd($y->value));
}
/**
* @param BigInteger $y
*/
public function lowerThan(self $y): bool
{
return $this->value->isLessThan($y->value);
}
public function isEven(): bool
{
return $this->value->isEven();
}
public function get(): BrickBigInteger
{
return $this->value;
}
}
+335
View File
@@ -0,0 +1,335 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core\Util;
use Base64Url\Base64Url;
use function extension_loaded;
use InvalidArgumentException;
use Jose\Component\Core\JWK;
use RuntimeException;
/**
* @internal
*/
class ECKey
{
public static function convertToPEM(JWK $jwk): string
{
if ($jwk->has('d')) {
return self::convertPrivateKeyToPEM($jwk);
}
return self::convertPublicKeyToPEM($jwk);
}
/**
* @throws InvalidArgumentException if the curve is not supported
*/
public static function convertPublicKeyToPEM(JWK $jwk): string
{
switch ($jwk->get('crv')) {
case 'P-256':
$der = self::p256PublicKey();
break;
case 'secp256k1':
$der = self::p256KPublicKey();
break;
case 'P-384':
$der = self::p384PublicKey();
break;
case 'P-521':
$der = self::p521PublicKey();
break;
default:
throw new InvalidArgumentException('Unsupported curve.');
}
$der .= self::getKey($jwk);
$pem = '-----BEGIN PUBLIC KEY-----'.PHP_EOL;
$pem .= chunk_split(base64_encode($der), 64, PHP_EOL);
$pem .= '-----END PUBLIC KEY-----'.PHP_EOL;
return $pem;
}
/**
* @throws InvalidArgumentException if the curve is not supported
*/
public static function convertPrivateKeyToPEM(JWK $jwk): string
{
switch ($jwk->get('crv')) {
case 'P-256':
$der = self::p256PrivateKey($jwk);
break;
case 'secp256k1':
$der = self::p256KPrivateKey($jwk);
break;
case 'P-384':
$der = self::p384PrivateKey($jwk);
break;
case 'P-521':
$der = self::p521PrivateKey($jwk);
break;
default:
throw new InvalidArgumentException('Unsupported curve.');
}
$der .= self::getKey($jwk);
$pem = '-----BEGIN EC PRIVATE KEY-----'.PHP_EOL;
$pem .= chunk_split(base64_encode($der), 64, PHP_EOL);
$pem .= '-----END EC PRIVATE KEY-----'.PHP_EOL;
return $pem;
}
/**
* Creates a EC key with the given curve and additional values.
*
* @param string $curve The curve
* @param array $values values to configure the key
*/
public static function createECKey(string $curve, array $values = []): JWK
{
$jwk = self::createECKeyUsingOpenSSL($curve);
$values = array_merge($values, $jwk);
return new JWK($values);
}
/**
* @throws InvalidArgumentException if the curve is not supported
*/
private static function getNistCurveSize(string $curve): int
{
switch ($curve) {
case 'P-256':
case 'secp256k1':
return 256;
case 'P-384':
return 384;
case 'P-521':
return 521;
default:
throw new InvalidArgumentException(sprintf('The curve "%s" is not supported.', $curve));
}
}
/**
* @throws RuntimeException if the extension OpenSSL is not available
* @throws RuntimeException if the key cannot be created
*/
private static function createECKeyUsingOpenSSL(string $curve): array
{
if (!extension_loaded('openssl')) {
throw new RuntimeException('Please install the OpenSSL extension');
}
$key = openssl_pkey_new([
'curve_name' => self::getOpensslCurveName($curve),
'private_key_type' => OPENSSL_KEYTYPE_EC,
]);
if (false === $key) {
throw new RuntimeException('Unable to create the key');
}
$result = openssl_pkey_export($key, $out);
if (false === $result) {
throw new RuntimeException('Unable to create the key');
}
$res = openssl_pkey_get_private($out);
if (false === $res) {
throw new RuntimeException('Unable to create the key');
}
$details = openssl_pkey_get_details($res);
$nistCurveSize = self::getNistCurveSize($curve);
return [
'kty' => 'EC',
'crv' => $curve,
'd' => Base64Url::encode(str_pad($details['ec']['d'], (int) ceil($nistCurveSize / 8), "\0", STR_PAD_LEFT)),
'x' => Base64Url::encode(str_pad($details['ec']['x'], (int) ceil($nistCurveSize / 8), "\0", STR_PAD_LEFT)),
'y' => Base64Url::encode(str_pad($details['ec']['y'], (int) ceil($nistCurveSize / 8), "\0", STR_PAD_LEFT)),
];
}
/**
* @throws InvalidArgumentException if the curve is not supported
*/
private static function getOpensslCurveName(string $curve): string
{
switch ($curve) {
case 'P-256':
return 'prime256v1';
case 'secp256k1':
return 'secp256k1';
case 'P-384':
return 'secp384r1';
case 'P-521':
return 'secp521r1';
default:
throw new InvalidArgumentException(sprintf('The curve "%s" is not supported.', $curve));
}
}
private static function p256PublicKey(): string
{
return pack(
'H*',
'3059' // SEQUENCE, length 89
.'3013' // SEQUENCE, length 19
.'0607' // OID, length 7
.'2a8648ce3d0201' // 1.2.840.10045.2.1 = EC Public Key
.'0608' // OID, length 8
.'2a8648ce3d030107' // 1.2.840.10045.3.1.7 = P-256 Curve
.'0342' // BIT STRING, length 66
.'00' // prepend with NUL - pubkey will follow
);
}
private static function p256KPublicKey(): string
{
return pack(
'H*',
'3056' // SEQUENCE, length 86
.'3010' // SEQUENCE, length 16
.'0607' // OID, length 7
.'2a8648ce3d0201' // 1.2.840.10045.2.1 = EC Public Key
.'0605' // OID, length 8
.'2B8104000A' // 1.3.132.0.10 secp256k1
.'0342' // BIT STRING, length 66
.'00' // prepend with NUL - pubkey will follow
);
}
private static function p384PublicKey(): string
{
return pack(
'H*',
'3076' // SEQUENCE, length 118
.'3010' // SEQUENCE, length 16
.'0607' // OID, length 7
.'2a8648ce3d0201' // 1.2.840.10045.2.1 = EC Public Key
.'0605' // OID, length 5
.'2b81040022' // 1.3.132.0.34 = P-384 Curve
.'0362' // BIT STRING, length 98
.'00' // prepend with NUL - pubkey will follow
);
}
private static function p521PublicKey(): string
{
return pack(
'H*',
'30819b' // SEQUENCE, length 154
.'3010' // SEQUENCE, length 16
.'0607' // OID, length 7
.'2a8648ce3d0201' // 1.2.840.10045.2.1 = EC Public Key
.'0605' // OID, length 5
.'2b81040023' // 1.3.132.0.35 = P-521 Curve
.'038186' // BIT STRING, length 134
.'00' // prepend with NUL - pubkey will follow
);
}
private static function p256PrivateKey(JWK $jwk): string
{
$d = unpack('H*', str_pad(Base64Url::decode($jwk->get('d')), 32, "\0", STR_PAD_LEFT))[1];
return pack(
'H*',
'3077' // SEQUENCE, length 87+length($d)=32
.'020101' // INTEGER, 1
.'0420' // OCTET STRING, length($d) = 32
.$d
.'a00a' // TAGGED OBJECT #0, length 10
.'0608' // OID, length 8
.'2a8648ce3d030107' // 1.3.132.0.34 = P-256 Curve
.'a144' // TAGGED OBJECT #1, length 68
.'0342' // BIT STRING, length 66
.'00' // prepend with NUL - pubkey will follow
);
}
private static function p256KPrivateKey(JWK $jwk): string
{
$d = unpack('H*', str_pad(Base64Url::decode($jwk->get('d')), 32, "\0", STR_PAD_LEFT))[1];
return pack(
'H*',
'3074' // SEQUENCE, length 84+length($d)=32
.'020101' // INTEGER, 1
.'0420' // OCTET STRING, length($d) = 32
.$d
.'a007' // TAGGED OBJECT #0, length 7
.'0605' // OID, length 5
.'2b8104000a' // 1.3.132.0.10 secp256k1
.'a144' // TAGGED OBJECT #1, length 68
.'0342' // BIT STRING, length 66
.'00' // prepend with NUL - pubkey will follow
);
}
private static function p384PrivateKey(JWK $jwk): string
{
$d = unpack('H*', str_pad(Base64Url::decode($jwk->get('d')), 48, "\0", STR_PAD_LEFT))[1];
return pack(
'H*',
'3081a4' // SEQUENCE, length 116 + length($d)=48
.'020101' // INTEGER, 1
.'0430' // OCTET STRING, length($d) = 30
.$d
.'a007' // TAGGED OBJECT #0, length 7
.'0605' // OID, length 5
.'2b81040022' // 1.3.132.0.34 = P-384 Curve
.'a164' // TAGGED OBJECT #1, length 100
.'0362' // BIT STRING, length 98
.'00' // prepend with NUL - pubkey will follow
);
}
private static function p521PrivateKey(JWK $jwk): string
{
$d = unpack('H*', str_pad(Base64Url::decode($jwk->get('d')), 66, "\0", STR_PAD_LEFT))[1];
return pack(
'H*',
'3081dc' // SEQUENCE, length 154 + length($d)=66
.'020101' // INTEGER, 1
.'0442' // OCTET STRING, length(d) = 66
.$d
.'a007' // TAGGED OBJECT #0, length 7
.'0605' // OID, length 5
.'2b81040023' // 1.3.132.0.35 = P-521 Curve
.'a18189' // TAGGED OBJECT #1, length 137
.'038186' // BIT STRING, length 134
.'00' // prepend with NUL - pubkey will follow
);
}
private static function getKey(JWK $jwk): string
{
$nistCurveSize = self::getNistCurveSize($jwk->get('crv'));
$length = (int) ceil($nistCurveSize / 8);
return
"\04"
.str_pad(Base64Url::decode($jwk->get('x')), $length, "\0", STR_PAD_LEFT)
.str_pad(Base64Url::decode($jwk->get('y')), $length, "\0", STR_PAD_LEFT);
}
}
+132
View File
@@ -0,0 +1,132 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core\Util;
use InvalidArgumentException;
use const STR_PAD_LEFT;
/**
* @internal
*/
final class ECSignature
{
private const ASN1_SEQUENCE = '30';
private const ASN1_INTEGER = '02';
private const ASN1_MAX_SINGLE_BYTE = 128;
private const ASN1_LENGTH_2BYTES = '81';
private const ASN1_BIG_INTEGER_LIMIT = '7f';
private const ASN1_NEGATIVE_INTEGER = '00';
private const BYTE_SIZE = 2;
/**
* @throws InvalidArgumentException if the length of the signature is invalid
*/
public static function toAsn1(string $signature, int $length): string
{
$signature = bin2hex($signature);
if (self::octetLength($signature) !== $length) {
throw new InvalidArgumentException('Invalid signature length.');
}
$pointR = self::preparePositiveInteger(mb_substr($signature, 0, $length, '8bit'));
$pointS = self::preparePositiveInteger(mb_substr($signature, $length, null, '8bit'));
$lengthR = self::octetLength($pointR);
$lengthS = self::octetLength($pointS);
$totalLength = $lengthR + $lengthS + self::BYTE_SIZE + self::BYTE_SIZE;
$lengthPrefix = $totalLength > self::ASN1_MAX_SINGLE_BYTE ? self::ASN1_LENGTH_2BYTES : '';
return hex2bin(
self::ASN1_SEQUENCE
.$lengthPrefix.dechex($totalLength)
.self::ASN1_INTEGER.dechex($lengthR).$pointR
.self::ASN1_INTEGER.dechex($lengthS).$pointS
);
}
/**
* @throws InvalidArgumentException if the signature is not an ASN.1 sequence
*/
public static function fromAsn1(string $signature, int $length): string
{
$message = bin2hex($signature);
$position = 0;
if (self::ASN1_SEQUENCE !== self::readAsn1Content($message, $position, self::BYTE_SIZE)) {
throw new InvalidArgumentException('Invalid data. Should start with a sequence.');
}
if (self::ASN1_LENGTH_2BYTES === self::readAsn1Content($message, $position, self::BYTE_SIZE)) {
$position += self::BYTE_SIZE;
}
$pointR = self::retrievePositiveInteger(self::readAsn1Integer($message, $position));
$pointS = self::retrievePositiveInteger(self::readAsn1Integer($message, $position));
return hex2bin(str_pad($pointR, $length, '0', STR_PAD_LEFT).str_pad($pointS, $length, '0', STR_PAD_LEFT));
}
private static function octetLength(string $data): int
{
return (int) (mb_strlen($data, '8bit') / self::BYTE_SIZE);
}
private static function preparePositiveInteger(string $data): string
{
if (mb_substr($data, 0, self::BYTE_SIZE, '8bit') > self::ASN1_BIG_INTEGER_LIMIT) {
return self::ASN1_NEGATIVE_INTEGER.$data;
}
while (0 === mb_strpos($data, self::ASN1_NEGATIVE_INTEGER, 0, '8bit')
&& mb_substr($data, 2, self::BYTE_SIZE, '8bit') <= self::ASN1_BIG_INTEGER_LIMIT) {
$data = mb_substr($data, 2, null, '8bit');
}
return $data;
}
private static function readAsn1Content(string $message, int &$position, int $length): string
{
$content = mb_substr($message, $position, $length, '8bit');
$position += $length;
return $content;
}
/**
* @throws InvalidArgumentException if the data is not an integer
*/
private static function readAsn1Integer(string $message, int &$position): string
{
if (self::ASN1_INTEGER !== self::readAsn1Content($message, $position, self::BYTE_SIZE)) {
throw new InvalidArgumentException('Invalid data. Should contain an integer.');
}
$length = (int) hexdec(self::readAsn1Content($message, $position, self::BYTE_SIZE));
return self::readAsn1Content($message, $position, $length * self::BYTE_SIZE);
}
private static function retrievePositiveInteger(string $data): string
{
while (0 === mb_strpos($data, self::ASN1_NEGATIVE_INTEGER, 0, '8bit')
&& mb_substr($data, 2, self::BYTE_SIZE, '8bit') > self::ASN1_BIG_INTEGER_LIMIT) {
$data = mb_substr($data, 2, null, '8bit');
}
return $data;
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core\Util;
/**
* @internal
*/
class Hash
{
/**
* Hash Parameter.
*
* @var string
*/
private $hash;
/**
* DER encoding T.
*
* @var string
*/
private $t;
/**
* Hash Length.
*
* @var int
*/
private $length;
private function __construct(string $hash, int $length, string $t)
{
$this->hash = $hash;
$this->length = $length;
$this->t = $t;
}
/**
* @return Hash
*/
public static function sha1(): self
{
return new self('sha1', 20, "\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14");
}
/**
* @return Hash
*/
public static function sha256(): self
{
return new self('sha256', 32, "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20");
}
/**
* @return Hash
*/
public static function sha384(): self
{
return new self('sha384', 48, "\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30");
}
/**
* @return Hash
*/
public static function sha512(): self
{
return new self('sha512', 64, "\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40");
}
public function getLength(): int
{
return $this->length;
}
/**
* Compute the HMAC.
*/
public function hash(string $text): string
{
return hash($this->hash, $text, true);
}
public function name(): string
{
return $this->hash;
}
public function t(): string
{
return $this->t;
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core\Util;
use RuntimeException;
use Throwable;
final class JsonConverter
{
/**
* @param mixed $payload
*
* @throws RuntimeException if the payload cannot be encoded
*/
public static function encode($payload): string
{
try {
return json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
} catch (Throwable $throwable) {
throw new RuntimeException('Invalid content.', $throwable->getCode(), $throwable);
}
}
/**
* @throws RuntimeException if the payload cannot be decoded
*
* @return mixed
*/
public static function decode(string $payload)
{
try {
return json_decode($payload, true, 512, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
} catch (Throwable $throwable) {
throw new RuntimeException('Invalid content.', $throwable->getCode(), $throwable);
}
}
}
+113
View File
@@ -0,0 +1,113 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core\Util;
use function in_array;
use InvalidArgumentException;
use function is_array;
use Jose\Component\Core\JWK;
/**
* @internal
*/
class KeyChecker
{
public static function checkKeyUsage(JWK $key, string $usage): void
{
if ($key->has('use')) {
self::checkUsage($key, $usage);
}
if ($key->has('key_ops')) {
self::checkOperation($key, $usage);
}
}
/**
* @throws InvalidArgumentException if the key is not suitable for the selected algorithm
*/
public static function checkKeyAlgorithm(JWK $key, string $algorithm): void
{
if (!$key->has('alg')) {
return;
}
if ($key->get('alg') !== $algorithm) {
throw new InvalidArgumentException(sprintf('Key is only allowed for algorithm "%s".', $key->get('alg')));
}
}
/**
* @throws InvalidArgumentException if the key is not suitable for the selected operation
*/
private static function checkOperation(JWK $key, string $usage): void
{
$ops = $key->get('key_ops');
if (!is_array($ops)) {
throw new InvalidArgumentException('Invalid key parameter "key_ops". Should be a list of key operations');
}
switch ($usage) {
case 'verification':
if (!in_array('verify', $ops, true)) {
throw new InvalidArgumentException('Key cannot be used to verify a signature');
}
break;
case 'signature':
if (!in_array('sign', $ops, true)) {
throw new InvalidArgumentException('Key cannot be used to sign');
}
break;
case 'encryption':
if (!in_array('encrypt', $ops, true) && !in_array('wrapKey', $ops, true) && !in_array('deriveKey', $ops, true)) {
throw new InvalidArgumentException('Key cannot be used to encrypt');
}
break;
case 'decryption':
if (!in_array('decrypt', $ops, true) && !in_array('unwrapKey', $ops, true) && !in_array('deriveBits', $ops, true)) {
throw new InvalidArgumentException('Key cannot be used to decrypt');
}
break;
default:
throw new InvalidArgumentException('Unsupported key usage.');
}
}
/**
* @throws InvalidArgumentException if the key is not suitable for the selected operation
*/
private static function checkUsage(JWK $key, string $usage): void
{
$use = $key->get('use');
switch ($usage) {
case 'verification':
case 'signature':
if ('sig' !== $use) {
throw new InvalidArgumentException('Key cannot be used to sign or verify a signature.');
}
break;
case 'encryption':
case 'decryption':
if ('enc' !== $use) {
throw new InvalidArgumentException('Key cannot be used to encrypt or decrypt.');
}
break;
default:
throw new InvalidArgumentException('Unsupported key usage.');
}
}
}
+310
View File
@@ -0,0 +1,310 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Core\Util;
use function array_key_exists;
use Base64Url\Base64Url;
use function count;
use FG\ASN1\Universal\BitString;
use FG\ASN1\Universal\Integer;
use FG\ASN1\Universal\NullObject;
use FG\ASN1\Universal\ObjectIdentifier;
use FG\ASN1\Universal\OctetString;
use FG\ASN1\Universal\Sequence;
use Jose\Component\Core\JWK;
use RuntimeException;
/**
* @internal
*/
class RSAKey
{
/**
* @var Sequence
*/
private $sequence;
/**
* @var bool
*/
private $private;
/**
* @var array
*/
private $values;
/**
* @var BigInteger
*/
private $modulus;
/**
* @var int
*/
private $modulus_length;
/**
* @var BigInteger
*/
private $public_exponent;
/**
* @var null|BigInteger
*/
private $private_exponent;
/**
* @var BigInteger[]
*/
private $primes = [];
/**
* @var BigInteger[]
*/
private $exponents = [];
/**
* @var null|BigInteger
*/
private $coefficient;
private function __construct(JWK $data)
{
$this->values = $data->all();
$this->populateBigIntegers();
$this->private = array_key_exists('d', $this->values);
}
/**
* @return RSAKey
*/
public static function createFromJWK(JWK $jwk): self
{
return new self($jwk);
}
public function getModulus(): BigInteger
{
return $this->modulus;
}
public function getModulusLength(): int
{
return $this->modulus_length;
}
public function getExponent(): BigInteger
{
$d = $this->getPrivateExponent();
if (null !== $d) {
return $d;
}
return $this->getPublicExponent();
}
public function getPublicExponent(): BigInteger
{
return $this->public_exponent;
}
public function getPrivateExponent(): ?BigInteger
{
return $this->private_exponent;
}
/**
* @return BigInteger[]
*/
public function getPrimes(): array
{
return $this->primes;
}
/**
* @return BigInteger[]
*/
public function getExponents(): array
{
return $this->exponents;
}
public function getCoefficient(): ?BigInteger
{
return $this->coefficient;
}
public function isPublic(): bool
{
return !array_key_exists('d', $this->values);
}
/**
* @param RSAKey $private
*
* @return RSAKey
*/
public static function toPublic(self $private): self
{
$data = $private->toArray();
$keys = ['p', 'd', 'q', 'dp', 'dq', 'qi'];
foreach ($keys as $key) {
if (array_key_exists($key, $data)) {
unset($data[$key]);
}
}
return new self(new JWK($data));
}
public function toArray(): array
{
return $this->values;
}
public function toPEM(): string
{
if (null === $this->sequence) {
$this->sequence = new Sequence();
if (array_key_exists('d', $this->values)) {
$this->initPrivateKey();
} else {
$this->initPublicKey();
}
}
$result = '-----BEGIN '.($this->private ? 'RSA PRIVATE' : 'PUBLIC').' KEY-----'.PHP_EOL;
$result .= chunk_split(base64_encode($this->sequence->getBinary()), 64, PHP_EOL);
$result .= '-----END '.($this->private ? 'RSA PRIVATE' : 'PUBLIC').' KEY-----'.PHP_EOL;
return $result;
}
/**
* Exponentiate with or without Chinese Remainder Theorem.
* Operation with primes 'p' and 'q' is appox. 2x faster.
*
* @param RSAKey $key
*
* @throws RuntimeException if the exponentiation cannot be achieved
*/
public static function exponentiate(self $key, BigInteger $c): BigInteger
{
if ($c->compare(BigInteger::createFromDecimal(0)) < 0 || $c->compare($key->getModulus()) > 0) {
throw new RuntimeException();
}
if ($key->isPublic() || null === $key->getCoefficient() || 0 === count($key->getPrimes()) || 0 === count($key->getExponents())) {
return $c->modPow($key->getExponent(), $key->getModulus());
}
$p = $key->getPrimes()[0];
$q = $key->getPrimes()[1];
$dP = $key->getExponents()[0];
$dQ = $key->getExponents()[1];
$qInv = $key->getCoefficient();
$m1 = $c->modPow($dP, $p);
$m2 = $c->modPow($dQ, $q);
$h = $qInv->multiply($m1->subtract($m2)->add($p))->mod($p);
return $m2->add($h->multiply($q));
}
private function populateBigIntegers(): void
{
$this->modulus = $this->convertBase64StringToBigInteger($this->values['n']);
$this->modulus_length = mb_strlen($this->getModulus()->toBytes(), '8bit');
$this->public_exponent = $this->convertBase64StringToBigInteger($this->values['e']);
if (!$this->isPublic()) {
$this->private_exponent = $this->convertBase64StringToBigInteger($this->values['d']);
if (array_key_exists('p', $this->values) && array_key_exists('q', $this->values)) {
$this->primes = [
$this->convertBase64StringToBigInteger($this->values['p']),
$this->convertBase64StringToBigInteger($this->values['q']),
];
if (array_key_exists('dp', $this->values) && array_key_exists('dq', $this->values) && array_key_exists('qi', $this->values)) {
$this->exponents = [
$this->convertBase64StringToBigInteger($this->values['dp']),
$this->convertBase64StringToBigInteger($this->values['dq']),
];
$this->coefficient = $this->convertBase64StringToBigInteger($this->values['qi']);
}
}
}
}
private function convertBase64StringToBigInteger(string $value): BigInteger
{
return BigInteger::createFromBinaryString(Base64Url::decode($value));
}
private function initPublicKey(): void
{
$oid_sequence = new Sequence();
$oid_sequence->addChild(new ObjectIdentifier('1.2.840.113549.1.1.1'));
$oid_sequence->addChild(new NullObject());
$this->sequence->addChild($oid_sequence);
$n = new Integer($this->fromBase64ToInteger($this->values['n']));
$e = new Integer($this->fromBase64ToInteger($this->values['e']));
$key_sequence = new Sequence();
$key_sequence->addChild($n);
$key_sequence->addChild($e);
$key_bit_string = new BitString(bin2hex($key_sequence->getBinary()));
$this->sequence->addChild($key_bit_string);
}
private function initPrivateKey(): void
{
$this->sequence->addChild(new Integer(0));
$oid_sequence = new Sequence();
$oid_sequence->addChild(new ObjectIdentifier('1.2.840.113549.1.1.1'));
$oid_sequence->addChild(new NullObject());
$this->sequence->addChild($oid_sequence);
$v = new Integer(0);
$n = new Integer($this->fromBase64ToInteger($this->values['n']));
$e = new Integer($this->fromBase64ToInteger($this->values['e']));
$d = new Integer($this->fromBase64ToInteger($this->values['d']));
$p = new Integer($this->fromBase64ToInteger($this->values['p']));
$q = new Integer($this->fromBase64ToInteger($this->values['q']));
$dp = array_key_exists('dp', $this->values) ? new Integer($this->fromBase64ToInteger($this->values['dp'])) : new Integer(0);
$dq = array_key_exists('dq', $this->values) ? new Integer($this->fromBase64ToInteger($this->values['dq'])) : new Integer(0);
$qi = array_key_exists('qi', $this->values) ? new Integer($this->fromBase64ToInteger($this->values['qi'])) : new Integer(0);
$key_sequence = new Sequence();
$key_sequence->addChild($v);
$key_sequence->addChild($n);
$key_sequence->addChild($e);
$key_sequence->addChild($d);
$key_sequence->addChild($p);
$key_sequence->addChild($q);
$key_sequence->addChild($dp);
$key_sequence->addChild($dq);
$key_sequence->addChild($qi);
$key_octet_string = new OctetString(bin2hex($key_sequence->getBinary()));
$this->sequence->addChild($key_octet_string);
}
/**
* @param string $value
*
* @return string
*/
private function fromBase64ToInteger($value)
{
$hex = current(unpack('H*', Base64Url::decode($value)));
return \Brick\Math\BigInteger::fromBase($hex, 16)->toBase(10);
}
}
+49
View File
@@ -0,0 +1,49 @@
{
"name": "web-token/jwt-core",
"description": "Core component of the JWT Framework.",
"type": "library",
"license": "MIT",
"keywords": ["JWS", "JWT", "JWE", "JWA", "JWK", "JWKSet", "Jot", "Jose", "RFC7515", "RFC7516", "RFC7517", "RFC7518", "RFC7519", "RFC7520", "Bundle", "Symfony"],
"homepage": "https://github.com/web-token",
"authors": [
{
"name": "Florent Morselli",
"homepage": "https://github.com/Spomky"
},{
"name": "All contributors",
"homepage": "https://github.com/web-token/jwt-framework/contributors"
}
],
"autoload": {
"psr-4": {
"Jose\\Component\\Core\\": ""
}
},
"require": {
"php": ">=7.2",
"ext-json": "*",
"ext-mbstring": "*",
"brick/math": "^0.8.17|^0.9",
"fgrosse/phpasn1": "^2.0",
"spomky-labs/base64url": "^1.0|^2.0"
},
"require-dev": {
"phpunit/phpunit": "^8.0"
},
"conflict": {
"spomky-labs/jose": "*"
},
"extra": {
"branch-alias": {
"v1.0": "1.0.x-dev",
"v1.1": "1.1.x-dev",
"v1.2": "1.2.x-dev",
"v1.3": "1.3.x-dev",
"v2.0": "2.0.x-dev",
"v2.1": "2.1.x-dev"
}
},
"config": {
"sort-packages": true
}
}
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
backupGlobals="false"
backupStaticAttributes="false"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="true"
bootstrap="vendor/autoload.php"
colors="true">
<testsuites>
<testsuite name="Test Suite">
<directory>./Tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">./</directory>
<exclude>
<directory>./vendor</directory>
<directory>./Tests</directory>
<directory suffix="Test.php">./src</directory>
</exclude>
</whitelist>
</filter>
</phpunit>
+4
View File
@@ -0,0 +1,4 @@
# Contributing
This repository is a sub repository of [the JWT Framework](https://github.com/web-token/jwt-framework) project and is READ ONLY.
Please do not submit any Pull Requests here. It will be automatically closed.
+1
View File
@@ -0,0 +1 @@
patreon: FlorentMorselli
@@ -0,0 +1,3 @@
Please do not submit any Pull Requests here. It will be automatically closed.
You should submit it here: https://github.com/web-token/jwt-framework/pulls
+157
View File
@@ -0,0 +1,157 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy;
use InvalidArgumentException;
use function is_string;
use Jose\Component\Core\Algorithm as JoseAlgorithm;
use Jose\Component\Signature\Algorithm;
abstract class AbstractBuilder
{
/**
* @var JWT
*/
protected $jwt;
/**
* @var JoseAlgorithm[]
*/
protected $algorithms = [];
public function __construct()
{
$this->jwt = new JWT();
$this->algorithms = (new AlgorithmProvider($this->getAlgorithmMap()))
->getAvailableAlgorithms()
;
}
public function payload(array $payload): self
{
$clone = clone $this;
$clone->jwt->claims->replace($payload);
return $clone;
}
public function iss(string $iss, bool $inHeader = false): self
{
return $this->claim('iss', $iss, $inHeader);
}
public function sub(string $sub, bool $inHeader = false): self
{
return $this->claim('sub', $sub, $inHeader);
}
public function aud(string $aud, bool $inHeader = false): self
{
$audience = $this->jwt->claims->has('aud') ? $this->jwt->claims->get('aud') : [];
$audience[] = $aud;
return $this->claim('aud', $audience, $inHeader);
}
public function jti(string $jti, bool $inHeader = false): self
{
return $this->claim('jti', $jti, $inHeader);
}
public function exp(int $exp, bool $inHeader = false): self
{
return $this->claim('exp', $exp, $inHeader);
}
public function iat(?int $iat = null, bool $inHeader = false): self
{
$iat = $iat ?? time();
return $this->claim('iat', $iat, $inHeader);
}
public function nbf(?int $nbf = null, bool $inHeader = false): self
{
$nbf = $nbf ?? time();
return $this->claim('nbf', $nbf, $inHeader);
}
/**
* @param Algorithm\SignatureAlgorithm|string $alg
*
* @throws InvalidArgumentException if the algorithm is not a string or an instance of Jose\Component\Core\Algorithm
*/
public function alg($alg): self
{
$clone = clone $this;
switch (true) {
case $alg instanceof JoseAlgorithm:
$clone->algorithms[] = $alg;
$clone->jwt->header->set('alg', $alg->name());
break;
case is_string($alg):
$clone->jwt->header->set('alg', $alg);
break;
default:
throw new InvalidArgumentException('Invalid parameter "alg". Shall be a string or an algorithm instance.');
}
return $clone;
}
public function cty(string $cty): self
{
return $this->header('cty', $cty);
}
public function typ(string $typ): self
{
return $this->header('typ', $typ);
}
public function crit(array $crit): self
{
return $this->header('crit', $crit);
}
/**
* @param mixed $value
*/
public function claim(string $key, $value, bool $inHeader = false): self
{
$clone = clone $this;
$clone->jwt->claims->set($key, $value);
if ($inHeader) {
$clone->jwt->header->set($key, $value);
}
return $clone;
}
/**
* @param mixed $value
*/
public function header(string $key, $value): self
{
$clone = clone $this;
$clone->jwt->header->set($key, $value);
return $clone;
}
abstract protected function getAlgorithmMap(): array;
}
+287
View File
@@ -0,0 +1,287 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy;
use function in_array;
use InvalidArgumentException;
use function is_array;
use function is_callable;
use function is_int;
use function is_string;
use Jose\Component\Checker;
use Jose\Component\Core\Algorithm;
use Jose\Component\Core\JWK;
use Jose\Component\Core\JWKSet;
abstract class AbstractLoader
{
/**
* @var string
*/
protected $token;
/**
* @var JWKSet
*/
protected $jwkset;
/**
* @var Checker\HeaderChecker[]
*/
protected $headerCheckers = [];
/**
* @var Checker\ClaimChecker[]
*/
protected $claimCheckers = [];
/**
* @var string[]
*/
protected $allowedAlgorithms = [];
/**
* @var Algorithm[]
*/
protected $algorithms = [];
/**
* @var string[]
*/
protected $mandatoryClaims = [];
protected function __construct(string $token)
{
$this->token = $token;
$this->jwkset = new JWKSet([]);
$this->claimCheckers = [];
$this->algorithms = (new AlgorithmProvider($this->getAlgorithmMap()))
->getAvailableAlgorithms()
;
}
/**
* @param string[] $mandatoryClaims
*/
public function mandatory(array $mandatoryClaims): self
{
$clone = clone $this;
$clone->mandatoryClaims = $mandatoryClaims;
return $clone;
}
public function aud(string $aud, bool $inHeader = false): self
{
return $this->claim('aud', new Checker\AudienceChecker($aud, true), $inHeader);
}
public function iss(string $iss, bool $inHeader = false): self
{
return $this->claim('iss', new Checker\IssuerChecker([$iss], true), $inHeader);
}
public function jti(string $jti, bool $inHeader = false): self
{
return $this->claim('jti', $jti, $inHeader);
}
public function sub(string $sub, bool $inHeader = false): self
{
return $this->claim('sub', $sub, $inHeader);
}
/**
* @param null|array|callable|Checker\ClaimChecker $checker
*/
public function claim(string $key, $checker, bool $inHeader = false): self
{
$clone = clone $this;
if (false === $checker) {
unset($clone->claimCheckers[$key]);
return $clone;
}
switch (true) {
case $checker instanceof Checker\ClaimChecker:
break;
case is_callable($checker):
$checker = new CallableChecker($key, $checker);
break;
case is_array($checker):
$checker = new CallableChecker($key, static function ($value) use ($checker) {return in_array($value, $checker, true); });
break;
default:
$checker = new CallableChecker($key, static function ($value) use ($checker) {return $value === $checker; });
}
$clone->claimCheckers[$key] = $checker;
if ($inHeader) {
return $clone->header($key, $checker);
}
return $clone;
}
/**
* @param false|int $leeway
*
* @throws InvalidArgumentException if the leeway is negative, not an integer or not false
*/
public function exp($leeway = 0, bool $inHeader = false): self
{
if (false === $leeway) {
$clone = clone $this;
unset($clone->claimCheckers['exp']);
return $clone;
}
if (!is_int($leeway) or $leeway < 0) {
throw new InvalidArgumentException('First parameter for "exp" claim is invalid. Set false to disable or a positive integer.');
}
return $this->claim('exp', new Checker\ExpirationTimeChecker($leeway), $inHeader);
}
/**
* @param false|int $leeway
*
* @throws InvalidArgumentException if the leeway is negative, not an integer or not false
*/
public function nbf($leeway = 0, bool $inHeader = false): self
{
if (false === $leeway) {
$clone = clone $this;
unset($clone->claimCheckers['nbf']);
return $clone;
}
if (!is_int($leeway) or $leeway < 0) {
throw new InvalidArgumentException('First parameter for "nbf" claim is invalid. Set false to disable or a positive integer.');
}
return $this->claim('nbf', new Checker\NotBeforeChecker($leeway, true), $inHeader);
}
/**
* @param false|int $leeway
*
* @throws InvalidArgumentException if the leeway is negative, not an integer or not false
*/
public function iat($leeway = 0, bool $inHeader = false): self
{
if (false === $leeway) {
$clone = clone $this;
unset($clone->claimCheckers['iat']);
return $clone;
}
if (!is_int($leeway) or $leeway < 0) {
throw new InvalidArgumentException('First parameter for "iat" claim is invalid. Set false to disable or a positive integer.');
}
return $this->claim('iat', new Checker\IssuedAtChecker($leeway, true), $inHeader);
}
/**
* @param Algorithm|string $alg
*
* @throws InvalidArgumentException if the algorithm is not a string or an instance of Jose\Component\Core\Algorithm
*/
public function alg($alg): self
{
$clone = clone $this;
switch (true) {
case is_string($alg):
$clone->allowedAlgorithms[] = $alg;
return $clone;
case $alg instanceof Algorithm:
$clone->algorithms[$alg->name()] = $alg;
$clone->allowedAlgorithms[] = $alg->name();
return $clone;
default:
throw new InvalidArgumentException('Invalid parameter "alg". Shall be a string or an algorithm instance.');
}
}
/**
* @param Algorithm[]|string[] $algs
*/
public function algs($algs): self
{
$clone = clone $this;
foreach ($algs as $alg) {
$clone = $clone->alg($alg);
}
return $clone;
}
/**
* @param array|callable|Checker\HeaderChecker|false|mixed $checker
*/
public function header(string $key, $checker): self
{
$clone = clone $this;
if (false === $checker) {
unset($clone->headerCheckers[$key]);
return $clone;
}
switch (true) {
case $checker instanceof Checker\HeaderChecker:
break;
case is_callable($checker):
$checker = new CallableChecker($key, $checker);
break;
case is_array($checker):
$checker = new CallableChecker($key, static function ($value) use ($checker) {return in_array($value, $checker, true); });
break;
default:
$checker = new CallableChecker($key, static function ($value) use ($checker) {return $value === $checker; });
}
$clone->headerCheckers[$key] = $checker;
return $clone;
}
public function key(JWK $jwk): self
{
$clone = clone $this;
$jwkset = $this->jwkset->with($jwk);
$clone->jwkset = $jwkset;
return $clone;
}
public function keyset(JWKSet $jwkset): self
{
$clone = clone $this;
$clone->jwkset = $jwkset;
return $clone;
}
abstract protected function getAlgorithmMap(): array;
}
+59
View File
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy;
use Jose\Component\Core\Algorithm;
use Throwable;
final class AlgorithmProvider
{
/**
* @var string[]
*/
private $algorithmClasses;
/**
* @var Algorithm[]
*/
private $algorithms = [];
public function __construct(array $algorithmClasses)
{
$this->algorithmClasses = $algorithmClasses;
foreach ($algorithmClasses as $algorithmClass) {
$this->addClass($algorithmClass);
}
}
public function getAlgorithmClasses(): array
{
return $this->algorithmClasses;
}
public function getAvailableAlgorithms(): array
{
return $this->algorithms;
}
private function addClass(string $algorithmClass): void
{
if (class_exists($algorithmClass)) {
try {
$this->algorithms[] = new $algorithmClass();
} catch (Throwable $throwable) {
//does nothing
}
}
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy;
class Build
{
public static function jws(): JWSBuilder
{
return new JWSBuilder();
}
public static function jwe(): JWEBuilder
{
return new JWEBuilder();
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy;
use Jose\Component\Checker\ClaimChecker;
use Jose\Component\Checker\HeaderChecker;
use Jose\Component\Checker\InvalidClaimException;
use Jose\Component\Checker\InvalidHeaderException;
final class CallableChecker implements ClaimChecker, HeaderChecker
{
/**
* @var string
*/
private $key;
/**
* @var callable
*/
private $callable;
public function __construct(string $key, callable $callable)
{
$this->key = $key;
$this->callable = $callable;
}
/**
* @param mixed $value
*
* @throws InvalidClaimException if the claim is invalid
*/
public function checkClaim($value): void
{
$callable = $this->callable;
$isValid = $callable($value);
if (!$isValid) {
throw new InvalidClaimException(sprintf('Invalid claim "%s"', $this->key), $this->key, $value);
}
}
public function supportedClaim(): string
{
return $this->key;
}
/**
* {@inheritdoc}
*/
public function checkHeader($value): void
{
$callable = $this->callable;
$isValid = $callable($value);
if (!$isValid) {
throw new InvalidHeaderException(sprintf('Invalid header "%s"', $this->key), $this->key, $value);
}
}
public function supportedHeader(): string
{
return $this->key;
}
public function protectedHeaderOnly(): bool
{
return true;
}
}
@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy;
use function in_array;
use function is_string;
use Jose\Component\Checker\HeaderChecker;
use Jose\Component\Checker\InvalidHeaderException;
/**
* This class is a header parameter checker.
* When the "enc" header parameter is present, it will check if the value is within the allowed ones.
*/
final class ContentEncryptionAlgorithmChecker implements HeaderChecker
{
private const HEADER_NAME = 'enc';
/**
* @var bool
*/
private $protectedHeader = false;
/**
* @var string[]
*/
private $supportedAlgorithms;
/**
* @param string[] $supportedAlgorithms
*/
public function __construct(array $supportedAlgorithms, bool $protectedHeader = false)
{
$this->supportedAlgorithms = $supportedAlgorithms;
$this->protectedHeader = $protectedHeader;
}
/**
* {@inheritdoc}
*
* @throws InvalidHeaderException if the header is invalid
*/
public function checkHeader($value): void
{
if (!is_string($value)) {
throw new InvalidHeaderException('"enc" must be a string.', self::HEADER_NAME, $value);
}
if (!in_array($value, $this->supportedAlgorithms, true)) {
throw new InvalidHeaderException('Unsupported algorithm.', self::HEADER_NAME, $value);
}
}
public function supportedHeader(): string
{
return self::HEADER_NAME;
}
public function protectedHeaderOnly(): bool
{
return $this->protectedHeader;
}
}
+149
View File
@@ -0,0 +1,149 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy;
use function count;
use InvalidArgumentException;
use function is_string;
use Jose\Component\Checker;
use Jose\Component\Core\Algorithm;
use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Core\Util\JsonConverter;
use Jose\Component\Encryption\Algorithm\ContentEncryption;
use Jose\Component\Encryption\Algorithm\KeyEncryption;
use Jose\Component\Encryption\Compression\CompressionMethod;
use Jose\Component\Encryption\Compression\CompressionMethodManager;
use Jose\Component\Encryption\Compression\Deflate;
use Jose\Component\Encryption\JWEDecrypter;
use Jose\Component\Encryption\JWETokenSupport;
use Jose\Component\Encryption\Serializer\CompactSerializer;
class Decrypt extends AbstractLoader
{
/**
* @var string[]
*/
protected $allowedContentEncryptionAlgorithms = [];
/**
* @var CompressionMethod[]
*/
private $compressionMethods;
private function __construct(string $token)
{
parent::__construct($token);
$this->compressionMethods = [
new Deflate(),
];
}
public static function token(string $token): self
{
return new self($token);
}
/**
* @param Algorithm|string $enc
*
* @throws InvalidArgumentException if the encryption algorithm is invalid
*/
public function enc($enc): self
{
$clone = clone $this;
switch (true) {
case is_string($enc):
$clone->allowedContentEncryptionAlgorithms[] = $enc;
return $clone;
case $enc instanceof Algorithm:
$clone->algorithms[$enc->name()] = $enc;
$clone->allowedContentEncryptionAlgorithms[] = $enc->name();
return $clone;
default:
throw new InvalidArgumentException('Invalid parameter "enc". Shall be a string or an algorithm instance.');
}
}
/**
* @param Algorithm[]|string[] $encs
*/
public function encs($encs): self
{
$clone = clone $this;
foreach ($encs as $enc) {
$clone = $clone->enc($enc);
}
return $clone;
}
public function run(): JWT
{
if (0 !== count($this->allowedAlgorithms)) {
$this->headerCheckers[] = new Checker\AlgorithmChecker($this->allowedAlgorithms, true);
}
if (0 !== count($this->allowedContentEncryptionAlgorithms)) {
$this->headerCheckers[] = new ContentEncryptionAlgorithmChecker($this->allowedContentEncryptionAlgorithms, true);
}
$jwe = (new CompactSerializer())->unserialize($this->token);
$headerChecker = new Checker\HeaderCheckerManager($this->headerCheckers, [new JWETokenSupport()]);
$headerChecker->check($jwe, 0);
$verifier = new JWEDecrypter(
new AlgorithmManager($this->algorithms),
new AlgorithmManager($this->algorithms),
new CompressionMethodManager($this->compressionMethods)
);
$verifier->decryptUsingKeySet($jwe, $this->jwkset, 0);
$jwt = new JWT();
$jwt->header->replace($jwe->getSharedProtectedHeader());
$jwt->claims->replace(JsonConverter::decode($jwe->getPayload()));
$claimChecker = new Checker\ClaimCheckerManager($this->claimCheckers);
$claimChecker->check($jwt->claims->all(), $this->mandatoryClaims);
return $jwt;
}
protected function getAlgorithmMap(): array
{
return [
KeyEncryption\A128GCMKW::class,
KeyEncryption\A192GCMKW::class,
KeyEncryption\A256GCMKW::class,
KeyEncryption\A128KW::class,
KeyEncryption\A192KW::class,
KeyEncryption\A256KW::class,
KeyEncryption\Dir::class,
KeyEncryption\ECDHES::class,
KeyEncryption\ECDHESA128KW::class,
KeyEncryption\ECDHESA192KW::class,
KeyEncryption\ECDHESA256KW::class,
KeyEncryption\PBES2HS256A128KW::class,
KeyEncryption\PBES2HS384A192KW::class,
KeyEncryption\PBES2HS512A256KW::class,
KeyEncryption\RSA15::class,
KeyEncryption\RSAOAEP::class,
KeyEncryption\RSAOAEP256::class,
ContentEncryption\A128GCM::class,
ContentEncryption\A192GCM::class,
ContentEncryption\A256GCM::class,
ContentEncryption\A128CBCHS256::class,
ContentEncryption\A192CBCHS384::class,
ContentEncryption\A256CBCHS512::class,
];
}
}
+141
View File
@@ -0,0 +1,141 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy;
use InvalidArgumentException;
use function is_string;
use Jose\Component\Core\Algorithm;
use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Core\JWK;
use Jose\Component\Core\Util\JsonConverter;
use Jose\Component\Encryption\Algorithm\ContentEncryption;
use Jose\Component\Encryption\Algorithm\KeyEncryption;
use Jose\Component\Encryption\Compression\CompressionMethod;
use Jose\Component\Encryption\Compression\CompressionMethodManager;
use Jose\Component\Encryption\Compression\Deflate;
use Jose\Component\Encryption\JWEBuilder as JoseBuilder;
use Jose\Component\Encryption\Serializer\CompactSerializer;
class JWEBuilder extends AbstractBuilder
{
/**
* @var CompressionMethod[]
*/
private $compressionMethods;
public function __construct()
{
parent::__construct();
$this->compressionMethods = [
new Deflate(),
];
}
/**
* @param Algorithm|string $enc
*
* @throws InvalidArgumentException if the header parameter "enc" is invalid
*/
public function enc($enc): self
{
$clone = clone $this;
switch (true) {
case $enc instanceof Algorithm:
$clone->algorithms[] = $enc;
$clone->jwt->header->set('enc', $enc->name());
break;
case is_string($enc):
$clone->jwt->header->set('enc', $enc);
break;
default:
throw new InvalidArgumentException('Invalid algorithm');
}
return $clone;
}
/**
* @param CompressionMethod|string $zip
*
* @throws InvalidArgumentException if the header parameter "zip" is invalid
*/
public function zip($zip): self
{
$clone = clone $this;
switch (true) {
case $zip instanceof CompressionMethod:
$clone->compressionMethods[] = $zip;
$clone->jwt->header->set('zip', $zip->name());
break;
case is_string($zip):
$clone->jwt->header->set('zip', $zip);
break;
default:
throw new InvalidArgumentException('Invalid compression method');
}
return $clone;
}
public function encrypt(JWK $jwk): string
{
$builder = new JoseBuilder(
new AlgorithmManager($this->algorithms),
new AlgorithmManager($this->algorithms),
new CompressionMethodManager($this->compressionMethods)
);
$jwe = $builder
->create()
->withPayload(JsonConverter::encode($this->jwt->claims->all()))
->withSharedProtectedHeader($this->jwt->header->all())
->addRecipient($jwk)
->build()
;
return (new CompactSerializer())->serialize($jwe);
}
protected function getAlgorithmMap(): array
{
return [
KeyEncryption\A128GCMKW::class,
KeyEncryption\A192GCMKW::class,
KeyEncryption\A256GCMKW::class,
KeyEncryption\A128KW::class,
KeyEncryption\A192KW::class,
KeyEncryption\A256KW::class,
KeyEncryption\Dir::class,
KeyEncryption\ECDHES::class,
KeyEncryption\ECDHESA128KW::class,
KeyEncryption\ECDHESA192KW::class,
KeyEncryption\ECDHESA256KW::class,
KeyEncryption\PBES2HS256A128KW::class,
KeyEncryption\PBES2HS384A192KW::class,
KeyEncryption\PBES2HS512A256KW::class,
KeyEncryption\RSA15::class,
KeyEncryption\RSAOAEP::class,
KeyEncryption\RSAOAEP256::class,
ContentEncryption\A128GCM::class,
ContentEncryption\A192GCM::class,
ContentEncryption\A256GCM::class,
ContentEncryption\A128CBCHS256::class,
ContentEncryption\A192CBCHS384::class,
ContentEncryption\A256CBCHS512::class,
];
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy;
use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Core\JWK;
use Jose\Component\Core\Util\JsonConverter;
use Jose\Component\Signature\Algorithm;
use Jose\Component\Signature\JWSBuilder as JoseBuilder;
use Jose\Component\Signature\Serializer\CompactSerializer;
class JWSBuilder extends AbstractBuilder
{
public function sign(JWK $jwk): string
{
$builder = new JoseBuilder(new AlgorithmManager($this->algorithms));
$jws = $builder
->create()
->withPayload(JsonConverter::encode($this->jwt->claims->all()))
->addSignature($jwk, $this->jwt->header->all())
->build()
;
return (new CompactSerializer())->serialize($jws);
}
protected function getAlgorithmMap(): array
{
return [
Algorithm\HS256::class,
Algorithm\HS384::class,
Algorithm\HS512::class,
Algorithm\RS256::class,
Algorithm\RS384::class,
Algorithm\RS512::class,
Algorithm\PS256::class,
Algorithm\PS384::class,
Algorithm\PS512::class,
Algorithm\ES256::class,
Algorithm\ES384::class,
Algorithm\ES512::class,
Algorithm\EdDSA::class,
];
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy;
final class JWT
{
/**
* @var ParameterBag
*/
public $claims;
/**
* @var ParameterBag
*/
public $header;
public function __construct()
{
$this->claims = new ParameterBag();
$this->header = new ParameterBag();
}
}
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2019 Spomky-Labs
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.
+27
View File
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy;
class Load
{
public static function jws(string $jws): Validate
{
return Validate::token($jws);
}
public static function jwe(string $jwe): Decrypt
{
return Decrypt::token($jwe);
}
}
+116
View File
@@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy;
use function array_key_exists;
use ArrayIterator;
use function call_user_func_array;
use function count;
use Countable;
use InvalidArgumentException;
use IteratorAggregate;
class ParameterBag implements IteratorAggregate, Countable
{
/**
* @var array
*/
private $parameters = [];
/**
* @return mixed
*/
public function __call(string $name, array $arguments)
{
if (method_exists($this, $name)) {
return call_user_func_array([$this, $name], $arguments);
}
if (0 === count($arguments)) {
return $this->get($name);
}
array_unshift($arguments, $name);
return call_user_func_array([$this, 'set'], $arguments);
}
public function all(): array
{
return $this->parameters;
}
public function keys(): array
{
return array_keys($this->parameters);
}
public function replace(array $parameters): void
{
$this->parameters = $parameters;
}
/**
* @throws InvalidArgumentException if the parameters are invalid
*/
public function add(array $parameters): void
{
$replaced = array_replace($this->parameters, $parameters);
if (null === $replaced) {
throw new InvalidArgumentException('Invalid parameters');
}
$this->parameters = $replaced;
}
/**
* @throws InvalidArgumentException if the selected parameter is missing
*
* @return mixed
*/
public function get(string $key)
{
if (!array_key_exists($key, $this->parameters)) {
throw new InvalidArgumentException(sprintf('Parameter "%s" is missing', $key));
}
return $this->parameters[$key];
}
/**
* @param mixed $value The value
*/
public function set(string $key, $value): void
{
$this->parameters[$key] = $value;
}
public function has(string $key): bool
{
return array_key_exists($key, $this->parameters);
}
public function remove(string $key): void
{
unset($this->parameters[$key]);
}
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->parameters);
}
public function count(): int
{
return count($this->parameters);
}
}
+15
View File
@@ -0,0 +1,15 @@
Easy Toolset For JWT-Framework
===============================
This repository is a sub repository of [the JWT Framework](https://github.com/web-token/jwt-framework) project and is READ ONLY.
**Please do not submit any Pull Request here.**
You should go to [the main repository](https://github.com/web-token/jwt-framework) instead.
# Documentation
The official documentation is available as https://web-token.spomky-labs.com/
# Licence
This software is release under [MIT licence](LICENSE).
@@ -0,0 +1,168 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy\Tests;
use BadFunctionCallException;
use function get_class;
use Jose\Component\Core\JWK;
use Jose\Component\Encryption\Algorithm\ContentEncryption;
use Jose\Component\Encryption\Algorithm\KeyEncryption;
use Jose\Component\Signature\Algorithm;
use Jose\Easy\AlgorithmProvider;
use PHPUnit\Framework\Exception;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestCase;
/**
* @group easy
*
* @internal
* @covers \Jose\Easy\AlgorithmProvider
*/
final class AlgorithmProviderTest extends TestCase
{
private const ALL_ALGORITHMS = [
Algorithm\HS256::class,
Algorithm\HS384::class,
Algorithm\HS512::class,
Algorithm\RS256::class,
Algorithm\RS384::class,
Algorithm\RS512::class,
Algorithm\PS256::class,
Algorithm\PS384::class,
Algorithm\PS512::class,
Algorithm\ES256::class,
Algorithm\ES384::class,
Algorithm\ES512::class,
Algorithm\EdDSA::class,
KeyEncryption\A128GCMKW::class,
KeyEncryption\A192GCMKW::class,
KeyEncryption\A256GCMKW::class,
KeyEncryption\A128KW::class,
KeyEncryption\A192KW::class,
KeyEncryption\A256KW::class,
KeyEncryption\Dir::class,
KeyEncryption\ECDHES::class,
KeyEncryption\ECDHESA128KW::class,
KeyEncryption\ECDHESA192KW::class,
KeyEncryption\ECDHESA256KW::class,
KeyEncryption\PBES2HS256A128KW::class,
KeyEncryption\PBES2HS384A192KW::class,
KeyEncryption\PBES2HS512A256KW::class,
KeyEncryption\RSA15::class,
KeyEncryption\RSAOAEP::class,
KeyEncryption\RSAOAEP256::class,
ContentEncryption\A128GCM::class,
ContentEncryption\A192GCM::class,
ContentEncryption\A256GCM::class,
ContentEncryption\A128CBCHS256::class,
ContentEncryption\A192CBCHS384::class,
ContentEncryption\A256CBCHS512::class,
];
/**
* @test
*
* @throws ExpectationFailedException
*/
public function itReturnsAllAlgorithmClasses(): void
{
$algorithmProvider = new AlgorithmProvider(self::ALL_ALGORITHMS);
static::assertSame(self::ALL_ALGORITHMS, $algorithmProvider->getAlgorithmClasses());
}
/**
* @test
*
* @throws Exception
* @throws ExpectationFailedException
*/
public function itReturnsTheAvailableAlgorithms(): void
{
$algorithmProvider = new AlgorithmProvider(self::ALL_ALGORITHMS);
foreach ($algorithmProvider->getAvailableAlgorithms() as $algorithm) {
static::assertContains(get_class($algorithm), self::ALL_ALGORITHMS);
}
}
/**
* @test
*
* @throws ExpectationFailedException
* @throws \Exception
*/
public function itAllowsNonExistingClasses(): void
{
$nonExistingClassName = 'NonExistingClass'.bin2hex(random_bytes(31));
$algorithmProvider = new AlgorithmProvider([$nonExistingClassName]);
static::assertSame([$nonExistingClassName], $algorithmProvider->getAlgorithmClasses());
static::assertSame([], $algorithmProvider->getAvailableAlgorithms());
}
/**
* @test
*
* @throws ExpectationFailedException
*/
public function itCanHandleClassesWithExceptions(): void
{
$test = [$this->createAlgorithmClassWithExceptionMock()];
$algorithmProvider = new AlgorithmProvider($test);
static::assertSame($test, $algorithmProvider->getAlgorithmClasses());
static::assertSame([], $algorithmProvider->getAvailableAlgorithms());
}
private function createAlgorithmClassWithExceptionMock(): string
{
$mockClass = new class() implements Algorithm\SignatureAlgorithm {
/** @var bool */
private static $throw;
public function __construct()
{
if (null === self::$throw) {
self::$throw = true;
return;
}
throw new BadFunctionCallException('should not be called');
}
public function name(): string
{
throw new BadFunctionCallException('should not be called');
}
public function allowedKeyTypes(): array
{
throw new BadFunctionCallException('should not be called');
}
public function sign(JWK $key, string $input): string
{
throw new BadFunctionCallException('should not be called');
}
public function verify(JWK $key, string $input, string $signature): bool
{
throw new BadFunctionCallException('should not be called');
}
};
return get_class($mockClass);
}
}
+141
View File
@@ -0,0 +1,141 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy\Tests;
use Jose\Component\Core\JWK;
use Jose\Component\Encryption\Algorithm\ContentEncryption\A256CCM_16_128;
use Jose\Component\Encryption\Algorithm\KeyEncryption\RSAOAEP512;
use Jose\Easy\Build;
use Jose\Easy\Load;
use PHPUnit\Framework\TestCase;
/**
* @group easy
*
* @internal
* @covers \Jose\Easy\Build
* @covers \Jose\Easy\JWEBuilder
* @covers \Jose\Easy\JWT
*/
class EncryptionTest extends TestCase
{
/**
* @test
*/
public function jweCanBeCreated(): void
{
$time = time();
$jwe = Build::jwe()
->exp($time + 3600)
->iat($time)
->nbf($time)
->jti('0123456789', true)
->iss('issuer')
->aud('audience1')
->aud('audience2')
->sub('subject')
->alg('RSA-OAEP-256')
->enc('A256GCM')
->zip('DEF')
->claim('is_root', true)
->claim('roles', ['ROLE1' => true, 'ROLE2' => 0.007])
->crit(['alg', 'enc'])
->encrypt($this->rsaKey())
;
$jwt = Load::jwe($jwe)
->algs(['RSA-OAEP', 'RSA-OAEP-256'])
->encs(['A128GCM', 'A256GCM'])
->exp()
->iat()
->nbf()
->aud('audience1')
->iss('issuer')
->sub('subject')
->jti('0123456789')
->key($this->rsaKey())
->run()
;
static::assertEquals($time, $jwt->claims->iat());
static::assertEquals($time, $jwt->claims->nbf());
static::assertEquals($time + 3600, $jwt->claims->exp());
static::assertEquals('0123456789', $jwt->claims->jti());
static::assertEquals('issuer', $jwt->claims->iss());
static::assertEquals('subject', $jwt->claims->sub());
static::assertEquals(['audience1', 'audience2'], $jwt->claims->aud());
static::assertEquals(true, $jwt->claims->is_root());
static::assertEquals(['ROLE1' => true, 'ROLE2' => 0.007], $jwt->claims->roles());
static::assertEquals(['jti' => '0123456789', 'alg' => 'RSA-OAEP-256', 'enc' => 'A256GCM', 'crit' => ['alg', 'enc'], 'zip' => 'DEF'], $jwt->header->all());
static::assertEquals('RSA-OAEP-256', $jwt->header->alg());
static::assertEquals('A256GCM', $jwt->header->enc());
static::assertEquals('0123456789', $jwt->header->jti());
}
/**
* @test
*/
public function jweCanBeCreatedWithCustomAlgorithm(): void
{
$time = time();
$jwe = Build::jwe()
->exp($time + 3600)
->iat($time)
->nbf($time)
->jti('0123456789')
->alg(new RSAOAEP512())
->enc(new A256CCM_16_128())
->encrypt($this->rsaKey())
;
$jwt = Load::jwe($jwe)
->algs(['RSA-OAEP', new RSAOAEP512()])
->encs(['A128GCM', new A256CCM_16_128()])
->exp()
->iat()
->nbf()
->aud('audience1')
->iss('issuer')
->sub('subject')
->jti('0123456789')
->key($this->rsaKey())
->run()
;
static::assertEquals($time, $jwt->claims->iat());
static::assertEquals($time, $jwt->claims->nbf());
static::assertEquals($time + 3600, $jwt->claims->exp());
static::assertEquals('0123456789', $jwt->claims->jti());
static::assertEquals('RSA-OAEP-512', $jwt->header->alg());
static::assertEquals('A256CCM-16-128', $jwt->header->enc());
}
private function rsaKey(): JWK
{
return new JWK([
'kty' => 'RSA',
'kid' => 'bilbo.baggins@hobbiton.example',
'use' => 'enc',
'n' => 'n4EPtAOCc9AlkeQHPzHStgAbgs7bTZLwUBZdR8_KuKPEHLd4rHVTeT-O-XV2jRojdNhxJWTDvNd7nqQ0VEiZQHz_AJmSCpMaJMRBSFKrKb2wqVwGU_NsYOYL-QtiWN2lbzcEe6XC0dApr5ydQLrHqkHHig3RBordaZ6Aj-oBHqFEHYpPe7Tpe-OfVfHd1E6cS6M1FZcD1NNLYD5lFHpPI9bTwJlsde3uhGqC0ZCuEHg8lhzwOHrtIQbS0FVbb9k3-tVTU4fg_3L_vniUFAKwuCLqKnS2BYwdq_mzSnbLY7h_qixoR7jig3__kRhuaxwUkRz5iaiQkqgc5gHdrNP5zw',
'e' => 'AQAB',
'd' => 'bWUC9B-EFRIo8kpGfh0ZuyGPvMNKvYWNtB_ikiH9k20eT-O1q_I78eiZkpXxXQ0UTEs2LsNRS-8uJbvQ-A1irkwMSMkK1J3XTGgdrhCku9gRldY7sNA_AKZGh-Q661_42rINLRCe8W-nZ34ui_qOfkLnK9QWDDqpaIsA-bMwWWSDFu2MUBYwkHTMEzLYGqOe04noqeq1hExBTHBOBdkMXiuFhUq1BU6l-DqEiWxqg82sXt2h-LMnT3046AOYJoRioz75tSUQfGCshWTBnP5uDjd18kKhyv07lhfSJdrPdM5Plyl21hsFf4L_mHCuoFau7gdsPfHPxxjVOcOpBrQzwQ',
'p' => '3Slxg_DwTXJcb6095RoXygQCAZ5RnAvZlno1yhHtnUex_fp7AZ_9nRaO7HX_-SFfGQeutao2TDjDAWU4Vupk8rw9JR0AzZ0N2fvuIAmr_WCsmGpeNqQnev1T7IyEsnh8UMt-n5CafhkikzhEsrmndH6LxOrvRJlsPp6Zv8bUq0k',
'q' => 'uKE2dh-cTf6ERF4k4e_jy78GfPYUIaUyoSSJuBzp3Cubk3OCqs6grT8bR_cu0Dm1MZwWmtdqDyI95HrUeq3MP15vMMON8lHTeZu2lmKvwqW7anV5UzhM1iZ7z4yMkuUwFWoBvyY898EXvRD-hdqRxHlSqAZ192zB3pVFJ0s7pFc',
'dp' => 'B8PVvXkvJrj2L-GYQ7v3y9r6Kw5g9SahXBwsWUzp19TVlgI-YV85q1NIb1rxQtD-IsXXR3-TanevuRPRt5OBOdiMGQp8pbt26gljYfKU_E9xn-RULHz0-ed9E9gXLKD4VGngpz-PfQ_q29pk5xWHoJp009Qf1HvChixRX59ehik',
'dq' => 'CLDmDGduhylc9o7r84rEUVn7pzQ6PF83Y-iBZx5NT-TpnOZKF1pErAMVeKzFEl41DlHHqqBLSM0W1sOFbwTxYWZDm6sI6og5iTbwQGIC3gnJKbi_7k_vJgGHwHxgPaX2PnvP-zyEkDERuf-ry4c_Z11Cq9AqC2yeL6kdKT1cYF8',
'qi' => '3PiqvXQN0zwMeE-sBvZgi289XP9XCQF3VWqPzMKnIgQp7_Tugo6-NZBKCQsMf3HaEGBjTVJs_jcK8-TRXvaKe-7ZMaQj8VfBdYkssbu0NKDDhjJ-GtiseaDVWt7dcH0cfwxgFUHpQh7FoCrjFJ6h6ZEpMF6xmujs4qMpPz8aaI4',
]);
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy\Tests;
use Jose\Easy\ParameterBag;
use PHPUnit\Framework\TestCase;
/**
* @group easy
*
* @internal
* @covers \Jose\Easy\ParameterBag
*/
class ParameterBagTest extends TestCase
{
/**
* @test
*/
public function basicCalls(): void
{
$bag = new ParameterBag();
$bag->iss('iss');
$bag->alg('alg');
$bag->aud(['aud']);
static::assertEquals(['aud'], $bag->aud());
static::assertEquals('iss', $bag->get('iss'));
static::assertEquals('alg', $bag->get('alg'));
}
}
+268
View File
@@ -0,0 +1,268 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy\Tests;
use Exception;
use InvalidArgumentException;
use Jose\Component\Checker\InvalidClaimException;
use Jose\Component\Core\JWK;
use Jose\Component\Signature\Algorithm\HS1;
use Jose\Easy\Build;
use Jose\Easy\Load;
use PHPUnit\Framework\TestCase;
/**
* @group easy
*
* @covers \Jose\Easy\Build
* @covers \Jose\Easy\JWSBuilder
* @covers \Jose\Easy\JWT
* @covers \Jose\Easy\Validate
*
* @internal
*/
class SignatureTest extends TestCase
{
/**
* @test
*/
public function jwsCanBeCreated(): void
{
$time = time();
$jws = Build::jws()
->exp($time + 3600)
->iat($time)
->nbf($time)
->jti('0123456789', true)
->alg('RS512')
->iss('issuer')
->aud('audience1')
->aud('audience2')
->sub('subject')
->claim('is_root', true)
->claim('roles', ['ROLE1' => true, 'ROLE2' => 0.007])
->crit(['alg'])
->sign($this->rsaKey())
;
$jwt = Load::jws($jws)
->algs(['RS256', 'RS512'])
->exp()
->iat()
->nbf()
->aud('audience1')
->iss('issuer')
->sub('subject')
->jti('0123456789')
->key($this->rsaKey())
->run()
;
static::assertEquals($time, $jwt->claims->iat());
static::assertEquals($time, $jwt->claims->nbf());
static::assertEquals($time + 3600, $jwt->claims->exp());
static::assertEquals('0123456789', $jwt->claims->jti());
static::assertEquals('issuer', $jwt->claims->iss());
static::assertEquals('subject', $jwt->claims->sub());
static::assertEquals(['audience1', 'audience2'], $jwt->claims->aud());
static::assertEquals(true, $jwt->claims->is_root());
static::assertEquals(['ROLE1' => true, 'ROLE2' => 0.007], $jwt->claims->roles());
static::assertEquals(['jti' => '0123456789', 'alg' => 'RS512', 'crit' => ['alg']], $jwt->header->all());
static::assertEquals('RS512', $jwt->header->alg());
static::assertEquals('0123456789', $jwt->header->jti());
}
/**
* @test
*/
public function invalidSignatureRejectsTheToken(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('Invalid signature');
$time = time();
$jws = Build::jws()
->exp($time + 3600)
->iat($time)
->nbf($time)
->jti('0123456789', true)
->alg('HS256')
->iss('issuer')
->aud('audience1')
->aud('audience2')
->sub('subject')
->claim('is_root', true)
->claim('roles', ['ROLE1' => true, 'ROLE2' => 0.007])
->crit(['alg'])
->sign(new JWK(['kty' => 'oct', 'k' => 'foofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoo']))
;
Load::jws($jws)
->algs(['HS256'])
->exp()
->iat()
->nbf()
->aud('audience1')
->iss('issuer')
->sub('subject')
->jti('0123456789')
->key(new JWK(['kty' => 'oct', 'k' => 'BARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBAR']))
->run()
;
}
/**
* @test
*/
public function algorithmIsNotAllowed(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('The algorithm "none" is not supported.');
$time = time();
$jws = Build::jws()
->exp($time + 3600)
->iat($time)
->nbf($time)
->jti('0123456789', true)
->alg('none')
->iss('issuer')
->aud('audience1')
->aud('audience2')
->sub('subject')
->claim('is_root', true)
->claim('roles', ['ROLE1' => true, 'ROLE2' => 0.007])
->crit(['alg'])
->sign($this->noneKey())
;
Load::jws($jws)
->algs(['HS256'])
->exp()
->iat()
->nbf()
->aud('audience1')
->iss('issuer')
->sub('subject')
->jti('0123456789')
->key(new JWK(['kty' => 'oct', 'k' => 'BARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBARBAR']))
->run()
;
}
/**
* @test
*/
public function tokenExpired(): void
{
$this->expectException(InvalidClaimException::class);
$this->expectExceptionMessage('The token expired.');
$time = time();
$jws = Build::jws()
->exp($time - 1)
->iat($time)
->nbf($time)
->jti('0123456789', true)
->alg('RS256')
->iss('issuer')
->aud('audience1')
->aud('audience2')
->sub('subject')
->claim('is_root', true)
->claim('roles', ['ROLE1' => true, 'ROLE2' => 0.007])
->crit(['alg'])
->sign($this->rsaKey())
;
Load::jws($jws)
->algs(['RS256'])
->exp()
->iat()
->nbf()
->aud('audience1')
->iss('issuer')
->sub('subject')
->jti('0123456789')
->key($this->rsaKey())
->run()
;
}
/**
* @test
*/
public function jwsCanBeCreatedWithCustomAlgorithm(): void
{
$time = time();
$jws = Build::jws()
->exp($time + 3600)
->iat($time)
->nbf($time)
->jti('0123456789')
->alg(new HS1())
->sign($this->octKey())
;
$jwt = Load::jws($jws)
->algs(['RS256', new HS1()])
->exp()
->iat()
->nbf()
->aud('audience1')
->iss('issuer')
->sub('subject')
->jti('0123456789')
->key($this->octKey())
->run()
;
static::assertEquals($time, $jwt->claims->iat());
static::assertEquals($time, $jwt->claims->nbf());
static::assertEquals($time + 3600, $jwt->claims->exp());
static::assertEquals('0123456789', $jwt->claims->jti());
static::assertEquals('HS1', $jwt->header->alg());
}
private function rsaKey(): JWK
{
return new JWK([
'kty' => 'RSA',
'kid' => 'bilbo.baggins@hobbiton.example',
'use' => 'sig',
'n' => 'n4EPtAOCc9AlkeQHPzHStgAbgs7bTZLwUBZdR8_KuKPEHLd4rHVTeT-O-XV2jRojdNhxJWTDvNd7nqQ0VEiZQHz_AJmSCpMaJMRBSFKrKb2wqVwGU_NsYOYL-QtiWN2lbzcEe6XC0dApr5ydQLrHqkHHig3RBordaZ6Aj-oBHqFEHYpPe7Tpe-OfVfHd1E6cS6M1FZcD1NNLYD5lFHpPI9bTwJlsde3uhGqC0ZCuEHg8lhzwOHrtIQbS0FVbb9k3-tVTU4fg_3L_vniUFAKwuCLqKnS2BYwdq_mzSnbLY7h_qixoR7jig3__kRhuaxwUkRz5iaiQkqgc5gHdrNP5zw',
'e' => 'AQAB',
'd' => 'bWUC9B-EFRIo8kpGfh0ZuyGPvMNKvYWNtB_ikiH9k20eT-O1q_I78eiZkpXxXQ0UTEs2LsNRS-8uJbvQ-A1irkwMSMkK1J3XTGgdrhCku9gRldY7sNA_AKZGh-Q661_42rINLRCe8W-nZ34ui_qOfkLnK9QWDDqpaIsA-bMwWWSDFu2MUBYwkHTMEzLYGqOe04noqeq1hExBTHBOBdkMXiuFhUq1BU6l-DqEiWxqg82sXt2h-LMnT3046AOYJoRioz75tSUQfGCshWTBnP5uDjd18kKhyv07lhfSJdrPdM5Plyl21hsFf4L_mHCuoFau7gdsPfHPxxjVOcOpBrQzwQ',
'p' => '3Slxg_DwTXJcb6095RoXygQCAZ5RnAvZlno1yhHtnUex_fp7AZ_9nRaO7HX_-SFfGQeutao2TDjDAWU4Vupk8rw9JR0AzZ0N2fvuIAmr_WCsmGpeNqQnev1T7IyEsnh8UMt-n5CafhkikzhEsrmndH6LxOrvRJlsPp6Zv8bUq0k',
'q' => 'uKE2dh-cTf6ERF4k4e_jy78GfPYUIaUyoSSJuBzp3Cubk3OCqs6grT8bR_cu0Dm1MZwWmtdqDyI95HrUeq3MP15vMMON8lHTeZu2lmKvwqW7anV5UzhM1iZ7z4yMkuUwFWoBvyY898EXvRD-hdqRxHlSqAZ192zB3pVFJ0s7pFc',
'dp' => 'B8PVvXkvJrj2L-GYQ7v3y9r6Kw5g9SahXBwsWUzp19TVlgI-YV85q1NIb1rxQtD-IsXXR3-TanevuRPRt5OBOdiMGQp8pbt26gljYfKU_E9xn-RULHz0-ed9E9gXLKD4VGngpz-PfQ_q29pk5xWHoJp009Qf1HvChixRX59ehik',
'dq' => 'CLDmDGduhylc9o7r84rEUVn7pzQ6PF83Y-iBZx5NT-TpnOZKF1pErAMVeKzFEl41DlHHqqBLSM0W1sOFbwTxYWZDm6sI6og5iTbwQGIC3gnJKbi_7k_vJgGHwHxgPaX2PnvP-zyEkDERuf-ry4c_Z11Cq9AqC2yeL6kdKT1cYF8',
'qi' => '3PiqvXQN0zwMeE-sBvZgi289XP9XCQF3VWqPzMKnIgQp7_Tugo6-NZBKCQsMf3HaEGBjTVJs_jcK8-TRXvaKe-7ZMaQj8VfBdYkssbu0NKDDhjJ-GtiseaDVWt7dcH0cfwxgFUHpQh7FoCrjFJ6h6ZEpMF6xmujs4qMpPz8aaI4',
]);
}
private function octKey(): JWK
{
return new JWK([
'kty' => 'oct',
'k' => 'foofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoo',
]);
}
private function noneKey(): JWK
{
return new JWK([
'kty' => 'none',
]);
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Easy;
use function count;
use Exception;
use Jose\Component\Checker;
use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Core\Util\JsonConverter;
use Jose\Component\Signature\Algorithm;
use Jose\Component\Signature\JWSTokenSupport;
use Jose\Component\Signature\JWSVerifier;
use Jose\Component\Signature\Serializer\CompactSerializer;
class Validate extends AbstractLoader
{
public static function token(string $token): self
{
return new self($token);
}
public function run(): JWT
{
if (0 !== count($this->allowedAlgorithms)) {
$this->headerCheckers[] = new Checker\AlgorithmChecker($this->allowedAlgorithms, true);
}
$jws = (new CompactSerializer())->unserialize($this->token);
$headerChecker = new Checker\HeaderCheckerManager($this->headerCheckers, [new JWSTokenSupport()]);
$headerChecker->check($jws, 0);
$verifier = new JWSVerifier(new AlgorithmManager($this->algorithms));
if (!$verifier->verifyWithKeySet($jws, $this->jwkset, 0)) {
throw new Exception('Invalid signature');
}
$jwt = new JWT();
$jwt->header->replace($jws->getSignature(0)->getProtectedHeader());
$jwt->claims->replace(JsonConverter::decode($jws->getPayload()));
$claimChecker = new Checker\ClaimCheckerManager($this->claimCheckers);
$claimChecker->check($jwt->claims->all(), $this->mandatoryClaims);
return $jwt;
}
protected function getAlgorithmMap(): array
{
return [
Algorithm\HS256::class,
Algorithm\HS384::class,
Algorithm\HS512::class,
Algorithm\RS256::class,
Algorithm\RS384::class,
Algorithm\RS512::class,
Algorithm\PS256::class,
Algorithm\PS384::class,
Algorithm\PS512::class,
Algorithm\ES256::class,
Algorithm\ES384::class,
Algorithm\ES512::class,
Algorithm\EdDSA::class,
];
}
}
+57
View File
@@ -0,0 +1,57 @@
{
"name": "web-token/jwt-easy",
"description": "Easy toolset to use the JWT Framework.",
"type": "library",
"license": "MIT",
"keywords": ["JWS", "JWT", "JWE", "JWA", "JWK", "JWKSet", "Jot", "Jose", "RFC7515", "RFC7516", "RFC7517", "RFC7518", "RFC7519", "RFC7520", "Bundle", "Symfony"],
"homepage": "https://github.com/web-token",
"authors": [
{
"name": "Florent Morselli",
"homepage": "https://github.com/Spomky"
},{
"name": "All contributors",
"homepage": "https://github.com/web-token/jwt-framework/contributors"
}
],
"autoload": {
"psr-4": {
"Jose\\Easy\\": ""
}
},
"require": {
"web-token/jwt-encryption": "^2.1",
"web-token/jwt-signature": "^2.1",
"web-token/jwt-checker": "^2.1"
},
"suggest": {
"web-token/jwt-encryption-algorithm-aescbc": "Adds AES-CBC based encryption algorithms",
"web-token/jwt-encryption-algorithm-aesgcm": "Adds AES-GCM based encryption algorithms",
"web-token/jwt-encryption-algorithm-aesgcmkw": "Adds AES-GCM Key Wrapping based encryption algorithms",
"web-token/jwt-encryption-algorithm-aeskw": "Adds AES Key Wrapping based encryption algorithms",
"web-token/jwt-encryption-algorithm-dir": "Adds Direct encryption algorithm",
"web-token/jwt-encryption-algorithm-ecdh-es": "Adds ECDH-ES based encryption algorithms",
"web-token/jwt-encryption-algorithm-pbes2": "Adds PBES2 based encryption algorithms",
"web-token/jwt-encryption-algorithm-rsa": "Adds RSA based encryption algorithms",
"web-token/jwt-signature-algorithm-ecdsa": "Adds ECDSA based signature algorithms",
"web-token/jwt-signature-algorithm-eddsa": "Adds EdDSA based signature algorithms",
"web-token/jwt-signature-algorithm-none": "Adds none signature algorithms",
"web-token/jwt-signature-algorithm-hmac": "Adds HMAC based signature algorithms",
"web-token/jwt-signature-algorithm-rsa": "Adds RSA based signature algorithms"
},
"require-dev": {
"phpunit/phpunit": "^8.0"
},
"extra": {
"branch-alias": {
"v1.0": "1.0.x-dev",
"v1.1": "1.1.x-dev",
"v1.2": "1.2.x-dev",
"v1.3": "1.3.x-dev",
"v2.0": "2.0.x-dev"
}
},
"config": {
"sort-packages": true
}
}
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
backupGlobals="false"
backupStaticAttributes="false"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="true"
bootstrap="vendor/autoload.php"
colors="true">
<testsuites>
<testsuite name="Test Suite">
<directory>./Tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">./</directory>
<exclude>
<directory>./vendor</directory>
<directory>./Tests</directory>
<directory suffix="Test.php">./src</directory>
</exclude>
</whitelist>
</filter>
</phpunit>
@@ -0,0 +1,4 @@
# Contributing
This repository is a sub repository of [the JWT Framework](https://github.com/web-token/jwt-framework) project and is READ ONLY.
Please do not submit any Pull Requests here. It will be automatically closed.
+1
View File
@@ -0,0 +1 @@
patreon: FlorentMorselli
@@ -0,0 +1,3 @@
Please do not submit any Pull Requests here. It will be automatically closed.
You should submit it here: https://github.com/web-token/jwt-framework/pulls
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Encryption\Algorithm;
use Jose\Component\Core\Algorithm;
interface ContentEncryptionAlgorithm extends Algorithm
{
/**
* This method encrypts the data using the given CEK, IV, AAD and protected header.
* The variable $tag is populated on success.
*
* @param string $data The data to encrypt
* @param string $cek The content encryption key
* @param string $iv The Initialization Vector
* @param null|string $aad Additional Additional Authenticated Data
* @param string $encoded_protected_header The Protected Header encoded in Base64Url
* @param string $tag Tag
*/
public function encryptContent(string $data, string $cek, string $iv, ?string $aad, string $encoded_protected_header, ?string &$tag = null): string;
/**
* This method tries to decrypt the data using the given CEK, IV, AAD, protected header and tag.
*
* @param string $data The data to decrypt
* @param string $cek The content encryption key
* @param string $iv The Initialization Vector
* @param null|string $aad Additional Additional Authenticated Data
* @param string $encoded_protected_header The Protected Header encoded in Base64Url
* @param string $tag Tag
*/
public function decryptContent(string $data, string $cek, string $iv, ?string $aad, string $encoded_protected_header, string $tag): string;
/**
* Returns the size of the IV used by this encryption method.
*/
public function getIVSize(): int;
/**
* Returns the size of the CEK used by this encryption method.
*/
public function getCEKSize(): int;
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Encryption\Algorithm\KeyEncryption;
use Jose\Component\Core\JWK;
use Jose\Component\Encryption\Algorithm\KeyEncryptionAlgorithm;
interface DirectEncryption extends KeyEncryptionAlgorithm
{
/**
* Returns the CEK.
*
* @param JWK $key The key used to get the CEK
*/
public function getCEK(JWK $key): string;
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Encryption\Algorithm\KeyEncryption;
use Jose\Component\Core\JWK;
use Jose\Component\Encryption\Algorithm\KeyEncryptionAlgorithm;
interface KeyAgreement extends KeyEncryptionAlgorithm
{
/**
* Computes the agreement key.
*/
public function getAgreementKey(int $encryptionKeyLength, string $algorithm, JWK $recipientKey, ?JWK $senderKey, array $completeHeader = [], array &$additionalHeaderValues = []): string;
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Encryption\Algorithm\KeyEncryption;
use Jose\Component\Core\JWK;
use Jose\Component\Encryption\Algorithm\KeyEncryptionAlgorithm;
interface KeyAgreementWithKeyWrapping extends KeyEncryptionAlgorithm
{
/**
* Compute and wrap the agreement key.
*
* @param JWK $recipientKey The receiver's key
* @param string $cek The CEK to wrap
* @param int $encryption_key_length Size of the key expected for the algorithm used for data encryption
* @param array $complete_header The complete header of the JWT
* @param array $additional_header_values Set additional header values if needed
*/
public function wrapAgreementKey(JWK $recipientKey, ?JWK $senderKey, string $cek, int $encryption_key_length, array $complete_header, array &$additional_header_values): string;
/**
* Unwrap and compute the agreement key.
*
* @param JWK $recipientKey The receiver's key
* @param string $encrypted_cek The encrypted CEK
* @param int $encryption_key_length Size of the key expected for the algorithm used for data encryption
* @param array $complete_header The complete header of the JWT
*
* @return string The decrypted CEK
*/
public function unwrapAgreementKey(JWK $recipientKey, ?JWK $senderKey, string $encrypted_cek, int $encryption_key_length, array $complete_header): string;
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Encryption\Algorithm\KeyEncryption;
use Jose\Component\Core\JWK;
use Jose\Component\Encryption\Algorithm\KeyEncryptionAlgorithm;
interface KeyEncryption extends KeyEncryptionAlgorithm
{
/**
* Encrypt the CEK.
*
* @param JWK $key The key used to wrap the CEK
* @param string $cek The CEK to encrypt
* @param array $completeHeader The complete header of the JWT
* @param array $additionalHeader Additional header
*/
public function encryptKey(JWK $key, string $cek, array $completeHeader, array &$additionalHeader): string;
/**
* Decrypt de CEK.
*
* @param JWK $key The key used to wrap the CEK
* @param string $encrypted_cek The CEK to decrypt
* @param array $header The complete header of the JWT
*/
public function decryptKey(JWK $key, string $encrypted_cek, array $header): string;
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Encryption\Algorithm\KeyEncryption;
use Jose\Component\Core\JWK;
use Jose\Component\Encryption\Algorithm\KeyEncryptionAlgorithm;
interface KeyWrapping extends KeyEncryptionAlgorithm
{
/**
* Encrypt the CEK.
*
* @param \Jose\Component\Core\JWK $key The key used to wrap the CEK
* @param string $cek The CEK to encrypt
* @param array $completeHeader The complete header of the JWT
* @param array $additionalHeader The complete header of the JWT
*/
public function wrapKey(JWK $key, string $cek, array $completeHeader, array &$additionalHeader): string;
/**
* Decrypt de CEK.
*
* @param \Jose\Component\Core\JWK $key The key used to wrap the CEK
* @param string $encrypted_cek The CEK to decrypt
* @param array $completeHeader The complete header of the JWT
*/
public function unwrapKey(JWK $key, string $encrypted_cek, array $completeHeader): string;
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Encryption\Algorithm;
use Jose\Component\Core\Algorithm;
interface KeyEncryptionAlgorithm extends Algorithm
{
public const MODE_DIRECT = 'dir';
public const MODE_ENCRYPT = 'enc';
public const MODE_WRAP = 'wrap';
public const MODE_AGREEMENT = 'agree';
/**
* Returns the key management mode used by the key encryption algorithm.
*/
public function getKeyManagementMode(): string;
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Encryption\Compression;
interface CompressionMethod
{
/**
* Returns the name of the method.
*/
public function name(): string;
/**
* Compress the data.
* Throws an exception in case of failure.
*
* @param string $data The data to compress
*/
public function compress(string $data): string;
/**
* Uncompress the data.
* Throws an exception in case of failure.
*
* @param string $data The data to uncompress
*/
public function uncompress(string $data): string;
}
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 Spomky-Labs
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Jose\Component\Encryption\Compression;
use function array_key_exists;
use InvalidArgumentException;
class CompressionMethodManager
{
/**
* @var CompressionMethod[]
*/
private $compressionMethods = [];
public function __construct(array $methods = [])
{
foreach ($methods as $method) {
$this->add($method);
}
}
/**
* Returns true if the givn compression method is supported.
*/
public function has(string $name): bool
{
return array_key_exists($name, $this->compressionMethods);
}
/**
* This method returns the compression method with the given name.
* Throws an exception if the method is not supported.
*
* @param string $name The name of the compression method
*
* @throws InvalidArgumentException if the compression method is not supported
*/
public function get(string $name): CompressionMethod
{
if (!$this->has($name)) {
throw new InvalidArgumentException(sprintf('The compression method "%s" is not supported.', $name));
}
return $this->compressionMethods[$name];
}
/**
* Returns the list of compression method names supported by the manager.
*
* @return string[]
*/
public function list(): array
{
return array_keys($this->compressionMethods);
}
/**
* Add the given compression method to the manager.
*/
protected function add(CompressionMethod $compressionMethod): void
{
$name = $compressionMethod->name();
$this->compressionMethods[$name] = $compressionMethod;
}
}

Some files were not shown because too many files have changed in this diff Show More