From 45c2ed601d6826f831de6567ca3ba925e16fe041 Mon Sep 17 00:00:00 2001 From: ErickSkrauch Date: Thu, 1 Aug 2019 12:17:12 +0300 Subject: [PATCH 1/7] Replace emarref/jwt with lcobucci/jwt Refactor all JWT-related components Replace RS256 with ES256 as a preferred JWT algorithm --- .../Tokens/AlgorithmIsNotDefinedException.php | 12 + .../Tokens/Algorithms/AlgorithmInterface.php | 19 ++ api/components/Tokens/Algorithms/ES256.php | 74 ++++++ api/components/Tokens/Algorithms/HS256.php | 50 +++++ api/components/Tokens/AlgorithmsManager.php | 42 ++++ api/components/Tokens/Component.php | 96 ++++++++ api/components/Tokens/TokensFactory.php | 31 +++ api/components/User/AuthenticationResult.php | 60 ----- api/components/User/Component.php | 211 ++---------------- api/components/User/IdentityFactory.php | 26 +++ api/components/User/Jwt.php | 23 -- api/components/User/JwtIdentity.php | 72 +++--- .../User/{Identity.php => Oauth2Identity.php} | 18 +- api/components/User/ScopesClaim.php | 30 --- api/components/User/SubjectPrefixVerifier.php | 28 --- api/config/config-test.php | 7 +- api/config/config.php | 10 +- api/controllers/AuthenticationController.php | 12 +- api/controllers/SignupController.php | 2 +- .../authentication/AuthenticationResult.php | 47 ++++ .../authentication/ConfirmEmailForm.php | 14 +- api/models/authentication/LoginForm.php | 20 +- .../authentication/RecoverPasswordForm.php | 13 +- .../authentication/RefreshTokenForm.php | 42 ++-- api/tests/_data/certs/private.pem | 5 + api/tests/_data/certs/public.pem | 4 + api/tests/_support/FunctionalTester.php | 14 +- .../unit/components/Tokens/ComponentTest.php | 92 ++++++++ .../components/Tokens/TokensFactoryTest.php | 35 +++ .../unit/components/User/ComponentTest.php | 36 +-- .../User/JwtAuthenticationResultTest.php | 63 ------ .../AuthenticationResultTest.php | 40 ++++ .../authentication/ConfirmEmailFormTest.php | 8 +- .../models/authentication/LoginFormTest.php | 7 +- .../models/authentication/LogoutFormTest.php | 4 +- .../RecoverPasswordFormTest.php | 7 +- .../authentication/RefreshTokenFormTest.php | 5 +- .../models/ChangePasswordFormTest.php | 6 +- .../models/EnableTwoFactorAuthFormTest.php | 4 +- autocompletion.php | 1 + common/config/config-test.php | 3 + composer.json | 1 + composer.lock | 79 ++++++- data/certs/private.key | 28 --- data/certs/private.pem | 5 + data/certs/public.crt | 16 -- data/certs/public.pem | 4 + 47 files changed, 805 insertions(+), 621 deletions(-) create mode 100644 api/components/Tokens/AlgorithmIsNotDefinedException.php create mode 100644 api/components/Tokens/Algorithms/AlgorithmInterface.php create mode 100644 api/components/Tokens/Algorithms/ES256.php create mode 100644 api/components/Tokens/Algorithms/HS256.php create mode 100644 api/components/Tokens/AlgorithmsManager.php create mode 100644 api/components/Tokens/Component.php create mode 100644 api/components/Tokens/TokensFactory.php delete mode 100644 api/components/User/AuthenticationResult.php create mode 100644 api/components/User/IdentityFactory.php delete mode 100644 api/components/User/Jwt.php rename api/components/User/{Identity.php => Oauth2Identity.php} (81%) delete mode 100644 api/components/User/ScopesClaim.php delete mode 100644 api/components/User/SubjectPrefixVerifier.php create mode 100644 api/models/authentication/AuthenticationResult.php create mode 100644 api/tests/_data/certs/private.pem create mode 100644 api/tests/_data/certs/public.pem create mode 100644 api/tests/unit/components/Tokens/ComponentTest.php create mode 100644 api/tests/unit/components/Tokens/TokensFactoryTest.php delete mode 100644 api/tests/unit/components/User/JwtAuthenticationResultTest.php create mode 100644 api/tests/unit/models/authentication/AuthenticationResultTest.php delete mode 100644 data/certs/private.key create mode 100644 data/certs/private.pem delete mode 100644 data/certs/public.crt create mode 100644 data/certs/public.pem diff --git a/api/components/Tokens/AlgorithmIsNotDefinedException.php b/api/components/Tokens/AlgorithmIsNotDefinedException.php new file mode 100644 index 0000000..740ca13 --- /dev/null +++ b/api/components/Tokens/AlgorithmIsNotDefinedException.php @@ -0,0 +1,12 @@ +privateKey = $privateKey; + $this->privateKeyPass = $privateKeyPass; + $this->publicKey = $publicKey; + } + + public function getAlgorithmId(): string { + return 'ES256'; + } + + public function getSigner(): Signer { + return new Sha256(); + } + + public function getPrivateKey(): Key { + if ($this->loadedPrivateKey === null) { + $this->loadedPrivateKey = new Key($this->privateKey, $this->privateKeyPass); + } + + return $this->loadedPrivateKey; + } + + public function getPublicKey(): Key { + if ($this->loadedPublicKey === null) { + $this->loadedPublicKey = new Key($this->publicKey); + } + + return $this->loadedPublicKey; + } + +} diff --git a/api/components/Tokens/Algorithms/HS256.php b/api/components/Tokens/Algorithms/HS256.php new file mode 100644 index 0000000..2bc7e66 --- /dev/null +++ b/api/components/Tokens/Algorithms/HS256.php @@ -0,0 +1,50 @@ +key = $key; + } + + public function getAlgorithmId(): string { + return 'HS256'; + } + + public function getSigner(): Signer { + return new Sha256(); + } + + public function getPrivateKey(): Key { + return $this->loadKey(); + } + + public function getPublicKey(): Key { + return $this->loadKey(); + } + + private function loadKey(): Key { + if ($this->loadedKey === null) { + $this->loadedKey = new Key($this->key); + } + + return $this->loadedKey; + } + +} diff --git a/api/components/Tokens/AlgorithmsManager.php b/api/components/Tokens/AlgorithmsManager.php new file mode 100644 index 0000000..af9d074 --- /dev/null +++ b/api/components/Tokens/AlgorithmsManager.php @@ -0,0 +1,42 @@ +getAlgorithmId(); + Assert::keyNotExists($this->algorithms, $id, 'passed algorithm is already exists'); + $this->algorithms[$algorithm->getSigner()->getAlgorithmId()] = $algorithm; + + return $this; + } + + /** + * @param string $algorithmId + * + * @return AlgorithmInterface + * @throws AlgorithmIsNotDefinedException + */ + public function get(string $algorithmId): AlgorithmInterface { + if (!isset($this->algorithms[$algorithmId])) { + throw new AlgorithmIsNotDefinedException($algorithmId); + } + + return $this->algorithms[$algorithmId]; + } + +} diff --git a/api/components/Tokens/Component.php b/api/components/Tokens/Component.php new file mode 100644 index 0000000..a16cea4 --- /dev/null +++ b/api/components/Tokens/Component.php @@ -0,0 +1,96 @@ +issuedAt($time) + ->expiresAt($time + self::EXPIRATION_TIMEOUT); + foreach ($payloads as $claim => $value) { + $builder->withClaim($claim, $value); + } + + foreach ($headers as $claim => $value) { + $builder->withHeader($claim, $value); + } + + /** @noinspection PhpUnhandledExceptionInspection */ + $algorithm = $this->getAlgorithmManager()->get(self::PREFERRED_ALGORITHM); + + return $builder->getToken($algorithm->getSigner(), $algorithm->getPrivateKey()); + } + + /** + * @param string $jwt + * + * @return Token + * @throws \InvalidArgumentException + */ + public function parse(string $jwt): Token { + return (new Parser())->parse($jwt); + } + + public function verify(Token $token): bool { + try { + $algorithm = $this->getAlgorithmManager()->get($token->getHeader('alg')); + return $token->verify($algorithm->getSigner(), $algorithm->getPublicKey()); + } catch (Exception $e) { + return false; + } + } + + private function getAlgorithmManager(): AlgorithmsManager { + if ($this->algorithmManager === null) { + $this->algorithmManager = new AlgorithmsManager([ + new Algorithms\HS256($this->hmacKey), + new Algorithms\ES256( + "file://{$this->privateKeyPath}", + $this->privateKeyPass, + "file://{$this->publicKeyPath}" + ), + ]); + } + + return $this->algorithmManager; + } + +} diff --git a/api/components/Tokens/TokensFactory.php b/api/components/Tokens/TokensFactory.php new file mode 100644 index 0000000..e92446a --- /dev/null +++ b/api/components/Tokens/TokensFactory.php @@ -0,0 +1,31 @@ + 'accounts_web_user', + 'sub' => self::SUB_ACCOUNT_PREFIX . $account->id, + ]; + if ($session === null) { + // If we don't remember a session, the token should live longer + // so that the session doesn't end while working with the account + $payloads['exp'] = time() + 60 * 60 * 24 * 7; // 7d + } else { + $payloads['jti'] = $session->id; + } + + return Yii::$app->tokens->create($payloads); + } + +} diff --git a/api/components/User/AuthenticationResult.php b/api/components/User/AuthenticationResult.php deleted file mode 100644 index 3cc0010..0000000 --- a/api/components/User/AuthenticationResult.php +++ /dev/null @@ -1,60 +0,0 @@ -account = $account; - $this->jwt = $jwt; - $this->session = $session; - } - - public function getAccount(): Account { - return $this->account; - } - - public function getJwt(): string { - return $this->jwt; - } - - public function getSession(): ?AccountSession { - return $this->session; - } - - public function getAsResponse() { - $token = (new Jwt())->deserialize($this->getJwt()); - - /** @noinspection NullPointerExceptionInspection */ - $response = [ - 'access_token' => $this->getJwt(), - 'expires_in' => $token->getPayload()->findClaimByName(Expiration::NAME)->getValue() - time(), - ]; - - $session = $this->getSession(); - if ($session !== null) { - $response['refresh_token'] = $session->refresh_token; - } - - return $response; - } - -} diff --git a/api/components/User/Component.php b/api/components/User/Component.php index 10d2acf..955a857 100644 --- a/api/components/User/Component.php +++ b/api/components/User/Component.php @@ -3,28 +3,11 @@ declare(strict_types=1); namespace api\components\User; -use api\exceptions\ThisShouldNotHappenException; use common\models\Account; use common\models\AccountSession; -use common\rbac\Roles as R; -use DateInterval; -use DateTime; -use Emarref\Jwt\Algorithm\AlgorithmInterface; -use Emarref\Jwt\Algorithm\Hs256; -use Emarref\Jwt\Algorithm\Rs256; -use Emarref\Jwt\Claim; -use Emarref\Jwt\Encryption\Asymmetric as AsymmetricEncryption; -use Emarref\Jwt\Encryption\EncryptionInterface; -use Emarref\Jwt\Encryption\Factory as EncryptionFactory; -use Emarref\Jwt\Exception\VerificationException; -use Emarref\Jwt\HeaderParameter\Custom; -use Emarref\Jwt\Token; -use Emarref\Jwt\Verification\Context as VerificationContext; use Exception; use InvalidArgumentException; -use Webmozart\Assert\Assert; use Yii; -use yii\base\InvalidConfigException; use yii\web\UnauthorizedHttpException; use yii\web\User as YiiUserComponent; @@ -41,52 +24,29 @@ class Component extends YiiUserComponent { public const KEEP_SITE_SESSIONS = 2; public const KEEP_CURRENT_SESSION = 4; - public const JWT_SUBJECT_PREFIX = 'ely|'; - - private const LATEST_JWT_VERSION = 1; - public $enableSession = false; public $loginUrl = null; - public $identityClass = Identity::class; - - public $secret; - - public $publicKeyPath; - - public $privateKeyPath; - - public $expirationTimeout = 'PT1H'; - - public $sessionTimeout = 'P7D'; - - private $publicKey; - - private $privateKey; - /** - * @var Token[] + * We don't use the standard web authorization mechanism via cookies. + * Therefore, only one static method findIdentityByAccessToken is used from + * the whole IdentityInterface interface, which is implemented in the factory. + * The method only used from loginByAccessToken from base class. + * + * @var string */ - private static $parsedTokensCache = []; - - public function init() { - parent::init(); - Assert::notEmpty($this->secret, 'secret must be specified'); - Assert::notEmpty($this->publicKeyPath, 'public key path must be specified'); - Assert::notEmpty($this->privateKeyPath, 'private key path must be specified'); - } + public $identityClass = IdentityFactory::class; public function findIdentityByAccessToken($accessToken): ?IdentityInterface { if (empty($accessToken)) { return null; } - /** @var \api\components\User\IdentityInterface|string $identityClass */ - $identityClass = $this->identityClass; try { - return $identityClass::findIdentityByAccessToken($accessToken); + return IdentityFactory::findIdentityByAccessToken($accessToken); } catch (UnauthorizedHttpException $e) { + // TODO: if this exception is catched there, how it forms "Token expired" exception? // Do nothing. It's okay to catch this. } catch (Exception $e) { Yii::error($e); @@ -95,77 +55,6 @@ class Component extends YiiUserComponent { return null; } - public function createJwtAuthenticationToken(Account $account, AccountSession $session = null): Token { - $token = $this->createToken($account); - if ($session !== null) { - $token->addClaim(new Claim\JwtId($session->id)); - } else { - // If we don't remember a session, the token should live longer - // so that the session doesn't end while working with the account - $token->addClaim(new Claim\Expiration((new DateTime())->add(new DateInterval($this->sessionTimeout)))); - } - - return $token; - } - - public function renewJwtAuthenticationToken(AccountSession $session): AuthenticationResult { - $transaction = Yii::$app->db->beginTransaction(); - - $account = $session->account; - $token = $this->createToken($account); - $token->addClaim(new Claim\JwtId($session->id)); - $jwt = $this->serializeToken($token); - - $result = new AuthenticationResult($account, $jwt, $session); - - $session->setIp(Yii::$app->request->userIP); - $session->last_refreshed_at = time(); - if (!$session->save()) { - throw new ThisShouldNotHappenException('Cannot update session info'); - } - - $transaction->commit(); - - return $result; - } - - public function serializeToken(Token $token): string { - $encryption = $this->getEncryptionForVersion(self::LATEST_JWT_VERSION); - $this->prepareEncryptionForEncoding($encryption); - - return (new Jwt())->serialize($token, $encryption); - } - - /** - * @param string $jwtString - * @return Token - * @throws VerificationException in case when some Claim not pass the validation - */ - public function parseToken(string $jwtString): Token { - $token = &self::$parsedTokensCache[$jwtString]; - if ($token === null) { - $jwt = new Jwt(); - try { - $notVerifiedToken = $jwt->deserialize($jwtString); - } catch (Exception $e) { - throw new VerificationException('Incorrect token encoding', 0, $e); - } - - $versionHeader = $notVerifiedToken->getHeader()->findParameterByName('v'); - $version = $versionHeader ? $versionHeader->getValue() : 0; - $encryption = $this->getEncryptionForVersion($version); - $this->prepareEncryptionForDecoding($encryption); - - $context = new VerificationContext($encryption); - $context->setSubject(self::JWT_SUBJECT_PREFIX); - $jwt->verify($notVerifiedToken, $context); - - $token = $notVerifiedToken; - } - - return $token; - } - /** * The method searches AccountSession model, which one has been used to create current JWT token. * null will be returned in case when any of the following situations occurred: @@ -188,17 +77,17 @@ class Component extends YiiUserComponent { } try { - $token = $this->parseToken($bearer); - } catch (VerificationException $e) { + $token = Yii::$app->tokens->parse($bearer); + } catch (InvalidArgumentException $e) { return null; } - $sessionId = $token->getPayload()->findClaimByName(Claim\JwtId::NAME); - if ($sessionId === null) { + $sessionId = $token->getClaim('jti', false); + if ($sessionId === false) { return null; } - return AccountSession::findOne($sessionId->getValue()); + return AccountSession::findOne($sessionId); } public function terminateSessions(Account $account, int $mode = 0): void { @@ -222,66 +111,6 @@ class Component extends YiiUserComponent { } } - private function getPublicKey() { - if (empty($this->publicKey)) { - if (!($this->publicKey = file_get_contents($this->publicKeyPath))) { - throw new InvalidConfigException('invalid public key path'); - } - } - - return $this->publicKey; - } - - private function getPrivateKey() { - if (empty($this->privateKey)) { - if (!($this->privateKey = file_get_contents($this->privateKeyPath))) { - throw new InvalidConfigException('invalid private key path'); - } - } - - return $this->privateKey; - } - - private function createToken(Account $account): Token { - $token = new Token(); - $token->addHeader(new Custom('v', 1)); - foreach ($this->getClaims($account) as $claim) { - $token->addClaim($claim); - } - - return $token; - } - - /** - * @param Account $account - * @return Claim\AbstractClaim[] - */ - private function getClaims(Account $account): array { - $currentTime = new DateTime(); - - return [ - new ScopesClaim([R::ACCOUNTS_WEB_USER]), - new Claim\IssuedAt($currentTime), - new Claim\Expiration($currentTime->add(new DateInterval($this->expirationTimeout))), - new Claim\Subject(self::JWT_SUBJECT_PREFIX . $account->id), - ]; - } - - private function getEncryptionForVersion(int $version): EncryptionInterface { - return EncryptionFactory::create($this->getAlgorithm($version ?? 0)); - } - - private function getAlgorithm(int $version): AlgorithmInterface { - switch ($version) { - case 0: - return new Hs256($this->secret); - case 1: - return new Rs256(); - } - - throw new InvalidArgumentException('Unsupported token version'); - } - private function getBearerToken(): ?string { $authHeader = Yii::$app->request->getHeaders()->get('Authorization'); if ($authHeader === null || !preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) { @@ -291,16 +120,4 @@ class Component extends YiiUserComponent { return $matches[1]; } - private function prepareEncryptionForEncoding(EncryptionInterface $encryption): void { - if ($encryption instanceof AsymmetricEncryption) { - $encryption->setPrivateKey($this->getPrivateKey()); - } - } - - private function prepareEncryptionForDecoding(EncryptionInterface $encryption) { - if ($encryption instanceof AsymmetricEncryption) { - $encryption->setPublicKey($this->getPublicKey()); - } - } - } diff --git a/api/components/User/IdentityFactory.php b/api/components/User/IdentityFactory.php new file mode 100644 index 0000000..f38f47e --- /dev/null +++ b/api/components/User/IdentityFactory.php @@ -0,0 +1,26 @@ + $verifier) { - if (!$verifier instanceof SubjectVerifier) { - continue; - } - - $verifiers[$i] = new SubjectPrefixVerifier($context->getSubject()); - break; - } - - return $verifiers; - } - -} diff --git a/api/components/User/JwtIdentity.php b/api/components/User/JwtIdentity.php index 71b41e1..479351f 100644 --- a/api/components/User/JwtIdentity.php +++ b/api/components/User/JwtIdentity.php @@ -1,82 +1,80 @@ rawToken = $rawToken; + private function __construct(Token $token) { $this->token = $token; } public static function findIdentityByAccessToken($rawToken, $type = null): IdentityInterface { - /** @var \api\components\User\Component $component */ - $component = Yii::$app->user; try { - $token = $component->parseToken($rawToken); - } catch (ExpiredException $e) { - throw new UnauthorizedHttpException('Token expired'); + $token = Yii::$app->tokens->parse($rawToken); } catch (Exception $e) { Yii::error($e); throw new UnauthorizedHttpException('Incorrect token'); } - return new self($rawToken, $token); + if (!Yii::$app->tokens->verify($token)) { + throw new UnauthorizedHttpException('Incorrect token'); + } + + if ($token->isExpired()) { + throw new UnauthorizedHttpException('Token expired'); + } + + if (!$token->validate(new ValidationData())) { + throw new UnauthorizedHttpException('Incorrect token'); + } + + $sub = $token->getClaim('sub', false); + if ($sub !== false && strpos($sub, TokensFactory::SUB_ACCOUNT_PREFIX) !== 0) { + throw new UnauthorizedHttpException('Incorrect token'); + } + + return new self($token); } public function getAccount(): ?Account { - /** @var Subject $subject */ - $subject = $this->token->getPayload()->findClaimByName(Subject::NAME); - if ($subject === null) { + $subject = $this->token->getClaim('sub', false); + if ($subject === false) { return null; } - $value = $subject->getValue(); - if (!StringHelper::startsWith($value, Component::JWT_SUBJECT_PREFIX)) { - Yii::warning('Unknown jwt subject: ' . $value); - return null; - } + Assert::startsWith($subject, TokensFactory::SUB_ACCOUNT_PREFIX); + $accountId = (int)mb_substr($subject, mb_strlen(TokensFactory::SUB_ACCOUNT_PREFIX)); - $accountId = (int)mb_substr($value, mb_strlen(Component::JWT_SUBJECT_PREFIX)); - $account = Account::findOne($accountId); - if ($account === null) { - return null; - } - - return $account; + return Account::findOne(['id' => $accountId]); } public function getAssignedPermissions(): array { - /** @var Subject $scopesClaim */ - $scopesClaim = $this->token->getPayload()->findClaimByName(ScopesClaim::NAME); - if ($scopesClaim === null) { + $scopesClaim = $this->token->getClaim('ely-scopes', false); + if ($scopesClaim === false) { return []; } - return explode(',', $scopesClaim->getValue()); + return explode(',', $scopesClaim); } public function getId(): string { - return $this->rawToken; + return (string)$this->token; } public function getAuthKey() { diff --git a/api/components/User/Identity.php b/api/components/User/Oauth2Identity.php similarity index 81% rename from api/components/User/Identity.php rename to api/components/User/Oauth2Identity.php index 0220eb2..8a9001a 100644 --- a/api/components/User/Identity.php +++ b/api/components/User/Oauth2Identity.php @@ -1,4 +1,6 @@ oauth->getAccessTokenStorage()->get($token); if ($model === null) { diff --git a/api/components/User/ScopesClaim.php b/api/components/User/ScopesClaim.php deleted file mode 100644 index d89c76b..0000000 --- a/api/components/User/ScopesClaim.php +++ /dev/null @@ -1,30 +0,0 @@ -subjectPrefix = $subjectPrefix; - } - - public function verify(Token $token): void { - /** @var Subject $subjectClaim */ - $subjectClaim = $token->getPayload()->findClaimByName(Subject::NAME); - $subject = ($subjectClaim === null) ? null : $subjectClaim->getValue(); - - if (!StringHelper::startsWith($subject, $this->subjectPrefix)) { - throw new InvalidSubjectException(); - } - } - -} diff --git a/api/config/config-test.php b/api/config/config-test.php index 02ad46e..8f0952d 100644 --- a/api/config/config-test.php +++ b/api/config/config-test.php @@ -1,8 +1,11 @@ [ - 'user' => [ - 'secret' => 'tests-secret-key', + 'tokens' => [ + 'hmacKey' => 'tests-secret-key', + 'privateKeyPath' => codecept_data_dir('certs/private.pem'), + 'privateKeyPass' => null, + 'publicKeyPath' => codecept_data_dir('certs/public.pem'), ], 'reCaptcha' => [ 'public' => 'public-key', diff --git a/api/config/config.php b/api/config/config.php index 8fdec47..1a9ffc2 100644 --- a/api/config/config.php +++ b/api/config/config.php @@ -10,9 +10,13 @@ return [ 'components' => [ 'user' => [ 'class' => api\components\User\Component::class, - 'secret' => getenv('JWT_USER_SECRET'), - 'publicKeyPath' => getenv('JWT_PUBLIC_KEY') ?: 'data/certs/public.crt', - 'privateKeyPath' => getenv('JWT_PRIVATE_KEY') ?: 'data/certs/private.key', + ], + 'tokens' => [ + 'class' => api\components\Tokens\Component::class, + 'hmacKey' => getenv('JWT_USER_SECRET'), + 'privateKeyPath' => getenv('JWT_PRIVATE_KEY_PATH') ?: __DIR__ . '/../../data/certs/private.pem', + 'privateKeyPass' => getenv('JWT_PRIVATE_KEY_PASS') ?: null, + 'publicKeyPath' => getenv('JWT_PUBLIC_KEY_PATH') ?: __DIR__ . '/../../data/certs/public.pem', ], 'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, diff --git a/api/controllers/AuthenticationController.php b/api/controllers/AuthenticationController.php index 27f1995..ee8c000 100644 --- a/api/controllers/AuthenticationController.php +++ b/api/controllers/AuthenticationController.php @@ -51,7 +51,7 @@ class AuthenticationController extends Controller { public function actionLogin() { $model = new LoginForm(); $model->load(Yii::$app->request->post()); - if (($result = $model->login()) === false) { + if (($result = $model->login()) === null) { $data = [ 'success' => false, 'errors' => $model->getFirstErrors(), @@ -66,7 +66,7 @@ class AuthenticationController extends Controller { return array_merge([ 'success' => true, - ], $result->getAsResponse()); + ], $result->formatAsOAuth2Response()); } public function actionLogout() { @@ -117,7 +117,7 @@ class AuthenticationController extends Controller { public function actionRecoverPassword() { $model = new RecoverPasswordForm(); $model->load(Yii::$app->request->post()); - if (($result = $model->recoverPassword()) === false) { + if (($result = $model->recoverPassword()) === null) { return [ 'success' => false, 'errors' => $model->getFirstErrors(), @@ -126,20 +126,20 @@ class AuthenticationController extends Controller { return array_merge([ 'success' => true, - ], $result->getAsResponse()); + ], $result->formatAsOAuth2Response()); } public function actionRefreshToken() { $model = new RefreshTokenForm(); $model->load(Yii::$app->request->post()); - if (($result = $model->renew()) === false) { + if (($result = $model->renew()) === null) { return [ 'success' => false, 'errors' => $model->getFirstErrors(), ]; } - $response = $result->getAsResponse(); + $response = $result->formatAsOAuth2Response(); unset($response['refresh_token']); return array_merge([ diff --git a/api/controllers/SignupController.php b/api/controllers/SignupController.php index 3634dc7..4f209f0 100644 --- a/api/controllers/SignupController.php +++ b/api/controllers/SignupController.php @@ -89,7 +89,7 @@ class SignupController extends Controller { return array_merge([ 'success' => true, - ], $result->getAsResponse()); + ], $result->formatAsOAuth2Response()); } } diff --git a/api/models/authentication/AuthenticationResult.php b/api/models/authentication/AuthenticationResult.php new file mode 100644 index 0000000..5e1db23 --- /dev/null +++ b/api/models/authentication/AuthenticationResult.php @@ -0,0 +1,47 @@ +token = $token; + $this->refreshToken = $refreshToken; + } + + public function getToken(): Token { + return $this->token; + } + + public function getRefreshToken(): ?string { + return $this->refreshToken; + } + + public function formatAsOAuth2Response(): array { + $response = [ + 'access_token' => (string)$this->token, + 'expires_in' => $this->token->getClaim('exp') - time(), + ]; + + $refreshToken = $this->refreshToken; + if ($refreshToken !== null) { + $response['refresh_token'] = $refreshToken; + } + + return $response; + } + +} diff --git a/api/models/authentication/ConfirmEmailForm.php b/api/models/authentication/ConfirmEmailForm.php index 9738bd2..60c6608 100644 --- a/api/models/authentication/ConfirmEmailForm.php +++ b/api/models/authentication/ConfirmEmailForm.php @@ -4,7 +4,7 @@ declare(strict_types=1); namespace api\models\authentication; use api\aop\annotations\CollectModelMetrics; -use api\components\User\AuthenticationResult; +use api\components\Tokens\TokensFactory; use api\models\base\ApiForm; use api\validators\EmailActivationKeyValidator; use common\models\Account; @@ -25,12 +25,10 @@ class ConfirmEmailForm extends ApiForm { /** * @CollectModelMetrics(prefix="signup.confirmEmail") - * @return AuthenticationResult|bool - * @throws \Throwable */ - public function confirm() { + public function confirm(): ?AuthenticationResult { if (!$this->validate()) { - return false; + return null; } $transaction = Yii::$app->db->beginTransaction(); @@ -39,6 +37,7 @@ class ConfirmEmailForm extends ApiForm { $confirmModel = $this->key; $account = $confirmModel->account; $account->status = Account::STATUS_ACTIVE; + /** @noinspection PhpUnhandledExceptionInspection */ Assert::notSame($confirmModel->delete(), false, 'Unable remove activation key.'); Assert::true($account->save(), 'Unable activate user account.'); @@ -49,12 +48,11 @@ class ConfirmEmailForm extends ApiForm { $session->generateRefreshToken(); Assert::true($session->save(), 'Cannot save account session model'); - $token = Yii::$app->user->createJwtAuthenticationToken($account, $session); - $jwt = Yii::$app->user->serializeToken($token); + $token = TokensFactory::createForAccount($account, $session); $transaction->commit(); - return new AuthenticationResult($account, $jwt, $session); + return new AuthenticationResult($token, $session->refresh_token); } } diff --git a/api/models/authentication/LoginForm.php b/api/models/authentication/LoginForm.php index 9925a7f..88c86ed 100644 --- a/api/models/authentication/LoginForm.php +++ b/api/models/authentication/LoginForm.php @@ -4,7 +4,7 @@ declare(strict_types=1); namespace api\models\authentication; use api\aop\annotations\CollectModelMetrics; -use api\components\User\AuthenticationResult; +use api\components\Tokens\TokensFactory; use api\models\base\ApiForm; use api\traits\AccountFinder; use api\validators\TotpValidator; @@ -30,12 +30,12 @@ class LoginForm extends ApiForm { ['login', 'required', 'message' => E::LOGIN_REQUIRED], ['login', 'validateLogin'], - ['password', 'required', 'when' => function(self $model) { + ['password', 'required', 'when' => function(self $model): bool { return !$model->hasErrors(); }, 'message' => E::PASSWORD_REQUIRED], ['password', 'validatePassword'], - ['totp', 'required', 'when' => function(self $model) { + ['totp', 'required', 'when' => function(self $model): bool { return !$model->hasErrors() && $model->getAccount()->is_otp_enabled; }, 'message' => E::TOTP_REQUIRED], ['totp', 'validateTotp'], @@ -97,11 +97,10 @@ class LoginForm extends ApiForm { /** * @CollectModelMetrics(prefix="authentication.login") - * @return AuthenticationResult|bool */ - public function login() { + public function login(): ?AuthenticationResult { if (!$this->validate()) { - return false; + return null; } $transaction = Yii::$app->db->beginTransaction(); @@ -113,21 +112,22 @@ class LoginForm extends ApiForm { Assert::true($account->save(), 'Unable to upgrade user\'s password'); } - $session = null; + $refreshToken = null; if ($this->rememberMe) { $session = new AccountSession(); $session->account_id = $account->id; $session->setIp(Yii::$app->request->userIP); $session->generateRefreshToken(); Assert::true($session->save(), 'Cannot save account session model'); + + $refreshToken = $session->refresh_token; } - $token = Yii::$app->user->createJwtAuthenticationToken($account, $session); - $jwt = Yii::$app->user->serializeToken($token); + $token = TokensFactory::createForAccount($account, $session); $transaction->commit(); - return new AuthenticationResult($account, $jwt, $session); + return new AuthenticationResult($token, $refreshToken); } } diff --git a/api/models/authentication/RecoverPasswordForm.php b/api/models/authentication/RecoverPasswordForm.php index 6f0e186..957c1ec 100644 --- a/api/models/authentication/RecoverPasswordForm.php +++ b/api/models/authentication/RecoverPasswordForm.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace api\models\authentication; use api\aop\annotations\CollectModelMetrics; +use api\components\Tokens\TokensFactory; use api\models\base\ApiForm; use api\validators\EmailActivationKeyValidator; use common\helpers\Error as E; @@ -38,12 +39,10 @@ class RecoverPasswordForm extends ApiForm { /** * @CollectModelMetrics(prefix="authentication.recoverPassword") - * @return \api\components\User\AuthenticationResult|bool - * @throws \Throwable */ - public function recoverPassword() { + public function recoverPassword(): ?AuthenticationResult { if (!$this->validate()) { - return false; + return null; } $transaction = Yii::$app->db->beginTransaction(); @@ -52,16 +51,16 @@ class RecoverPasswordForm extends ApiForm { $confirmModel = $this->key; $account = $confirmModel->account; $account->password = $this->newPassword; + /** @noinspection PhpUnhandledExceptionInspection */ Assert::notSame($confirmModel->delete(), false, 'Unable remove activation key.'); Assert::true($account->save(), 'Unable activate user account.'); - $token = Yii::$app->user->createJwtAuthenticationToken($account); - $jwt = Yii::$app->user->serializeToken($token); + $token = TokensFactory::createForAccount($account); $transaction->commit(); - return new \api\components\User\AuthenticationResult($account, $jwt, null); + return new AuthenticationResult($token); } } diff --git a/api/models/authentication/RefreshTokenForm.php b/api/models/authentication/RefreshTokenForm.php index 378f3af..92cd72c 100644 --- a/api/models/authentication/RefreshTokenForm.php +++ b/api/models/authentication/RefreshTokenForm.php @@ -1,10 +1,14 @@ E::REFRESH_TOKEN_REQUIRED], ['refresh_token', 'validateRefreshToken'], ]; } - public function validateRefreshToken() { - if (!$this->hasErrors()) { - /** @var AccountSession|null $token */ - if ($this->getSession() === null) { - $this->addError('refresh_token', E::REFRESH_TOKEN_NOT_EXISTS); - } + public function validateRefreshToken(): void { + if (!$this->hasErrors() && $this->findSession() === null) { + $this->addError('refresh_token', E::REFRESH_TOKEN_NOT_EXISTS); } } /** * @CollectModelMetrics(prefix="authentication.renew") - * @return \api\components\User\AuthenticationResult|bool */ - public function renew() { + public function renew(): ?AuthenticationResult { if (!$this->validate()) { - return false; + return null; } - /** @var \api\components\User\Component $component */ - $component = Yii::$app->user; + /** @var AccountSession $session */ + $session = $this->findSession(); + $account = $session->account; - return $component->renewJwtAuthenticationToken($this->getSession()); + $transaction = Yii::$app->db->beginTransaction(); + + $token = TokensFactory::createForAccount($account, $session); + + $session->setIp(Yii::$app->request->userIP); + $session->touch('last_refreshed_at'); + Assert::true($session->save(), 'Cannot update session info'); + + $transaction->commit(); + + return new AuthenticationResult($token, $session->refresh_token); } - /** - * @return AccountSession|null - */ - public function getSession() { + private function findSession(): ?AccountSession { if ($this->session === null) { $this->session = AccountSession::findOne(['refresh_token' => $this->refresh_token]); } diff --git a/api/tests/_data/certs/private.pem b/api/tests/_data/certs/private.pem new file mode 100644 index 0000000..fde4474 --- /dev/null +++ b/api/tests/_data/certs/private.pem @@ -0,0 +1,5 @@ +-----BEGIN EC PRIVATE KEY----- +MHcCAQEEIKrv4e6B9XP7l8F94ZMJotA+7FtjK7k9/olQi7Eb2tgmoAoGCCqGSM49 +AwEHoUQDQgAES2Pyq9r0CyyviLaWwq0ki5uy8hr/ZbNO++3j4XP43uLD9/GYkrKG +IRl+Hu5HT+LwZvrFcEaVhPk5CvtV4zlYJg== +-----END EC PRIVATE KEY----- diff --git a/api/tests/_data/certs/public.pem b/api/tests/_data/certs/public.pem new file mode 100644 index 0000000..684c55a --- /dev/null +++ b/api/tests/_data/certs/public.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAES2Pyq9r0CyyviLaWwq0ki5uy8hr/ +ZbNO++3j4XP43uLD9/GYkrKGIRl+Hu5HT+LwZvrFcEaVhPk5CvtV4zlYJg== +-----END PUBLIC KEY----- diff --git a/api/tests/_support/FunctionalTester.php b/api/tests/_support/FunctionalTester.php index f1d66f6..5061011 100644 --- a/api/tests/_support/FunctionalTester.php +++ b/api/tests/_support/FunctionalTester.php @@ -3,6 +3,7 @@ declare(strict_types=1); namespace api\tests; +use api\components\Tokens\TokensFactory; use api\tests\_generated\FunctionalTesterActions; use Codeception\Actor; use common\models\Account; @@ -12,16 +13,15 @@ use Yii; class FunctionalTester extends Actor { use FunctionalTesterActions; - public function amAuthenticated(string $asUsername = 'admin') { + public function amAuthenticated(string $asUsername = 'admin'): int { /** @var Account $account */ $account = Account::findOne(['username' => $asUsername]); if ($account === null) { - throw new InvalidArgumentException("Cannot find account for username \"{$asUsername}\""); + throw new InvalidArgumentException("Cannot find account with username \"{$asUsername}\""); } - $token = Yii::$app->user->createJwtAuthenticationToken($account); - $jwt = Yii::$app->user->serializeToken($token); - $this->amBearerAuthenticated($jwt); + $token = TokensFactory::createForAccount($account); + $this->amBearerAuthenticated((string)$token); return $account->id; } @@ -31,10 +31,10 @@ class FunctionalTester extends Actor { Yii::$app->user->logout(); } - public function canSeeAuthCredentials($expectRefresh = false): void { + public function canSeeAuthCredentials($expectRefreshToken = false): void { $this->canSeeResponseJsonMatchesJsonPath('$.access_token'); $this->canSeeResponseJsonMatchesJsonPath('$.expires_in'); - if ($expectRefresh) { + if ($expectRefreshToken) { $this->canSeeResponseJsonMatchesJsonPath('$.refresh_token'); } else { $this->cantSeeResponseJsonMatchesJsonPath('$.refresh_token'); diff --git a/api/tests/unit/components/Tokens/ComponentTest.php b/api/tests/unit/components/Tokens/ComponentTest.php new file mode 100644 index 0000000..8792eeb --- /dev/null +++ b/api/tests/unit/components/Tokens/ComponentTest.php @@ -0,0 +1,92 @@ +component = Yii::$app->tokens; + } + + public function testCreate() { + // Run without any arguments + $token = $this->component->create(); + $this->assertSame('ES256', $token->getHeader('alg')); + $this->assertEmpty(array_diff(array_keys($token->getClaims()), ['iat', 'exp'])); + $this->assertEqualsWithDelta(time(), $token->getClaim('iat'), 1); + $this->assertEqualsWithDelta(time() + 3600, $token->getClaim('exp'), 2); + + // Pass custom payloads + $token = $this->component->create(['find' => 'me']); + $this->assertArrayHasKey('find', $token->getClaims()); + $this->assertSame('me', $token->getClaim('find')); + + // Pass custom headers + $token = $this->component->create([], ['find' => 'me']); + $this->assertArrayHasKey('find', $token->getHeaders()); + $this->assertSame('me', $token->getHeader('find')); + } + + public function testParse() { + // Valid token signed with HS256 + $token = $this->component->parse('eyJhbGciOiJIUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.ixapBbhaUCejbcPTnFi5nqk75XKd1_lQJd1ZPgGTLEc'); + $this->assertValidParsedToken($token, 'HS256'); + + // Valid token signed with ES256 + $token = $this->component->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.M8Kam9bv0BXui3k7Posq_vc0I95Kb_Tw7L2vPdEPlwsHqh1VJHoWtlQc32_SlsotttL7j6RYbffBkRFX2wDGFQ'); + $this->assertValidParsedToken($token, 'ES256'); + + // Valid token signed with ES256, but the signature is invalid + $token = $this->component->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.xxx'); + $this->assertValidParsedToken($token, 'ES256'); + + // Completely invalid token + $this->expectException(InvalidArgumentException::class); + $this->component->parse('How do you tame a horse in Minecraft?'); + } + + /** + * @dataProvider getVerifyCases + */ + public function testVerify(Token $token, bool $shouldBeValid) { + $this->assertSame($shouldBeValid, $this->component->verify($token)); + } + + public function getVerifyCases() { + yield 'HS256' => [ + (new Parser())->parse('eyJhbGciOiJIUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.ixapBbhaUCejbcPTnFi5nqk75XKd1_lQJd1ZPgGTLEc'), + true, + ]; + yield 'ES256' => [ + (new Parser())->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.M8Kam9bv0BXui3k7Posq_vc0I95Kb_Tw7L2vPdEPlwsHqh1VJHoWtlQc32_SlsotttL7j6RYbffBkRFX2wDGFQ'), + true, + ]; + yield 'ES256 with an invalid signature' => [ + (new Parser())->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.xxx'), + false, + ]; + } + + private function assertValidParsedToken(Token $token, string $expectedAlg) { + $this->assertSame($expectedAlg, $token->getHeader('alg')); + $this->assertSame(1564527476, $token->getClaim('iat')); + $this->assertSame(1564531076, $token->getClaim('exp')); + $this->assertSame('ely|1', $token->getClaim('sub')); + $this->assertSame(3069592, $token->getClaim('jti')); + $this->assertSame('accounts_web_user', $token->getClaim('ely-scopes')); + } + +} diff --git a/api/tests/unit/components/Tokens/TokensFactoryTest.php b/api/tests/unit/components/Tokens/TokensFactoryTest.php new file mode 100644 index 0000000..cd54c00 --- /dev/null +++ b/api/tests/unit/components/Tokens/TokensFactoryTest.php @@ -0,0 +1,35 @@ +id = 1; + + $token = TokensFactory::createForAccount($account); + $this->assertEqualsWithDelta(time(), $token->getClaim('iat'), 1); + $this->assertEqualsWithDelta(time() + 60 * 60 * 24 * 7, $token->getClaim('exp'), 2); + $this->assertSame('ely|1', $token->getClaim('sub')); + $this->assertSame('accounts_web_user', $token->getClaim('ely-scopes')); + $this->assertArrayNotHasKey('jti', $token->getClaims()); + + $session = new AccountSession(); + $session->id = 2; + + $token = TokensFactory::createForAccount($account, $session); + $this->assertEqualsWithDelta(time(), $token->getClaim('iat'), 1); + $this->assertEqualsWithDelta(time() + 3600, $token->getClaim('exp'), 2); + $this->assertSame('ely|1', $token->getClaim('sub')); + $this->assertSame('accounts_web_user', $token->getClaim('ely-scopes')); + $this->assertSame(2, $token->getClaim('jti')); + } + +} diff --git a/api/tests/unit/components/User/ComponentTest.php b/api/tests/unit/components/User/ComponentTest.php index a22fced..6dd371b 100644 --- a/api/tests/unit/components/User/ComponentTest.php +++ b/api/tests/unit/components/User/ComponentTest.php @@ -4,7 +4,7 @@ declare(strict_types=1); namespace codeception\api\unit\components\User; use api\components\User\Component; -use api\components\User\Identity; +use api\components\User\IdentityFactory; use api\tests\unit\TestCase; use common\models\Account; use common\models\AccountSession; @@ -36,29 +36,7 @@ class ComponentTest extends TestCase { ]; } - public function testCreateJwtAuthenticationToken() { - $this->mockRequest(); - - // Token without session - $account = new Account(['id' => 1]); - $token = $this->component->createJwtAuthenticationToken($account); - $payloads = $token->getPayload(); - $this->assertEqualsWithDelta(time(), $payloads->findClaimByName('iat')->getValue(), 3); - $this->assertEqualsWithDelta(time() + 60 * 60 * 24 * 7, $payloads->findClaimByName('exp')->getValue(), 3); - $this->assertSame('ely|1', $payloads->findClaimByName('sub')->getValue()); - $this->assertSame('accounts_web_user', $payloads->findClaimByName('ely-scopes')->getValue()); - $this->assertNull($payloads->findClaimByName('jti')); - - $session = new AccountSession(['id' => 2]); - $token = $this->component->createJwtAuthenticationToken($account, $session); - $payloads = $token->getPayload(); - $this->assertEqualsWithDelta(time(), $payloads->findClaimByName('iat')->getValue(), 3); - $this->assertEqualsWithDelta(time() + 3600, $payloads->findClaimByName('exp')->getValue(), 3); - $this->assertSame('ely|1', $payloads->findClaimByName('sub')->getValue()); - $this->assertSame('accounts_web_user', $payloads->findClaimByName('ely-scopes')->getValue()); - $this->assertSame(2, $payloads->findClaimByName('jti')->getValue()); - } - + // TODO: move test to refresh token form public function testRenewJwtAuthenticationToken() { $userIP = '192.168.0.1'; $this->mockRequest($userIP); @@ -83,14 +61,6 @@ class ComponentTest extends TestCase { $this->assertSame($session->id, $payloads->findClaimByName('jti')->getValue(), 'session has not changed'); } - public function testParseToken() { - $this->mockRequest(); - $account = new Account(['id' => 1]); - $token = $this->component->createJwtAuthenticationToken($account); - $jwt = $this->component->serializeToken($token); - $this->component->parseToken($jwt); - } - public function testGetActiveSession() { /** @var Account $account */ $account = $this->tester->grabFixture('accounts', 'admin'); @@ -172,7 +142,7 @@ class ComponentTest extends TestCase { private function getComponentConfig() { return [ - 'identityClass' => Identity::class, + 'identityClass' => IdentityFactory::class, 'enableSession' => false, 'loginUrl' => null, 'secret' => 'secret', diff --git a/api/tests/unit/components/User/JwtAuthenticationResultTest.php b/api/tests/unit/components/User/JwtAuthenticationResultTest.php deleted file mode 100644 index 29c636d..0000000 --- a/api/tests/unit/components/User/JwtAuthenticationResultTest.php +++ /dev/null @@ -1,63 +0,0 @@ -id = 123; - $model = new AuthenticationResult($account, '', null); - $this->assertSame($account, $model->getAccount()); - } - - public function testGetJwt() { - $model = new AuthenticationResult(new Account(), 'mocked jwt', null); - $this->assertSame('mocked jwt', $model->getJwt()); - } - - public function testGetSession() { - $model = new AuthenticationResult(new Account(), '', null); - $this->assertNull($model->getSession()); - - $session = new AccountSession(); - $session->id = 321; - $model = new AuthenticationResult(new Account(), '', $session); - $this->assertSame($session, $model->getSession()); - } - - public function testGetAsResponse() { - $jwtToken = $this->createJwtToken(time() + 3600); - $model = new AuthenticationResult(new Account(), $jwtToken, null); - $result = $model->getAsResponse(); - $this->assertSame($jwtToken, $result['access_token']); - $this->assertSame(3600, $result['expires_in']); - - /** @noinspection SummerTimeUnsafeTimeManipulationInspection */ - $jwtToken = $this->createJwtToken(time() + 86400); - $session = new AccountSession(); - $session->refresh_token = 'refresh token'; - $model = new AuthenticationResult(new Account(), $jwtToken, $session); - $result = $model->getAsResponse(); - $this->assertSame($jwtToken, $result['access_token']); - $this->assertSame('refresh token', $result['refresh_token']); - $this->assertSame(86400, $result['expires_in']); - } - - private function createJwtToken(int $expires): string { - $token = new Token(); - $token->addClaim(new Expiration($expires)); - - return (new Jwt())->serialize($token, EncryptionFactory::create(new Hs256('123'))); - } - -} diff --git a/api/tests/unit/models/authentication/AuthenticationResultTest.php b/api/tests/unit/models/authentication/AuthenticationResultTest.php new file mode 100644 index 0000000..0945b98 --- /dev/null +++ b/api/tests/unit/models/authentication/AuthenticationResultTest.php @@ -0,0 +1,40 @@ +assertSame($token, $model->getToken()); + $this->assertNull($model->getRefreshToken()); + + $model = new AuthenticationResult($token, 'refresh_token'); + $this->assertSame('refresh_token', $model->getRefreshToken()); + } + + public function testGetAsResponse() { + $token = Yii::$app->tokens->create(); + $jwt = (string)$token; + + $model = new AuthenticationResult($token); + $result = $model->formatAsOAuth2Response(); + $this->assertSame($jwt, $result['access_token']); + $this->assertEqualsWithDelta(3600, $result['expires_in'], 1); + $this->assertArrayNotHasKey('refresh_token', $result); + + $model = new AuthenticationResult($token, 'refresh_token'); + $result = $model->formatAsOAuth2Response(); + $this->assertSame($jwt, $result['access_token']); + $this->assertEqualsWithDelta(3600, $result['expires_in'], 1); + $this->assertSame('refresh_token', $result['refresh_token']); + } + +} diff --git a/api/tests/unit/models/authentication/ConfirmEmailFormTest.php b/api/tests/unit/models/authentication/ConfirmEmailFormTest.php index 8b38e17..ef7971c 100644 --- a/api/tests/unit/models/authentication/ConfirmEmailFormTest.php +++ b/api/tests/unit/models/authentication/ConfirmEmailFormTest.php @@ -1,11 +1,11 @@ tester->grabFixture('emailActivations', 'freshRegistrationConfirmation'); $model = $this->createModel($fixture['key']); $result = $model->confirm(); - $this->assertInstanceOf(AuthenticationResult::class, $result); - $this->assertInstanceOf(AccountSession::class, $result->getSession(), 'session was generated'); + $this->assertNotNull($result); + $this->assertNotNull($result->getRefreshToken(), 'session was generated'); $activationExists = EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists(); $this->assertFalse($activationExists, 'email activation key is not exist'); /** @var Account $account */ diff --git a/api/tests/unit/models/authentication/LoginFormTest.php b/api/tests/unit/models/authentication/LoginFormTest.php index 5f4675f..35e7615 100644 --- a/api/tests/unit/models/authentication/LoginFormTest.php +++ b/api/tests/unit/models/authentication/LoginFormTest.php @@ -1,7 +1,8 @@ Account::STATUS_ACTIVE, ]), ]); - $this->assertInstanceOf(AuthenticationResult::class, $model->login(), 'model should login user'); + $this->assertNotNull($model->login(), 'model should login user'); $this->assertEmpty($model->getErrors(), 'error message should not be set'); } @@ -144,7 +145,7 @@ class LoginFormTest extends TestCase { 'login' => $this->tester->grabFixture('accounts', 'user-with-old-password-type')['username'], 'password' => '12345678', ]); - $this->assertInstanceOf(AuthenticationResult::class, $model->login()); + $this->assertNotNull($model->login()); $this->assertEmpty($model->getErrors()); $this->assertSame( Account::PASS_HASH_STRATEGY_YII2, diff --git a/api/tests/unit/models/authentication/LogoutFormTest.php b/api/tests/unit/models/authentication/LogoutFormTest.php index b13124d..e5426f9 100644 --- a/api/tests/unit/models/authentication/LogoutFormTest.php +++ b/api/tests/unit/models/authentication/LogoutFormTest.php @@ -2,7 +2,7 @@ namespace api\tests\_support\models\authentication; use api\components\User\Component; -use api\components\User\Identity; +use api\components\User\IdentityFactory; use api\models\authentication\LogoutForm; use api\tests\unit\TestCase; use Codeception\Specify; @@ -59,7 +59,7 @@ class LogoutFormTest extends TestCase { private function getComponentArgs() { return [ - 'identityClass' => Identity::class, + 'identityClass' => IdentityFactory::class, 'enableSession' => false, 'loginUrl' => null, 'secret' => 'secret', diff --git a/api/tests/unit/models/authentication/RecoverPasswordFormTest.php b/api/tests/unit/models/authentication/RecoverPasswordFormTest.php index c7d6da5..b3d19d9 100644 --- a/api/tests/unit/models/authentication/RecoverPasswordFormTest.php +++ b/api/tests/unit/models/authentication/RecoverPasswordFormTest.php @@ -1,7 +1,8 @@ '12345678', ]); $result = $model->recoverPassword(); - $this->assertInstanceOf(AuthenticationResult::class, $result); - $this->assertNull($result->getSession(), 'session was not generated'); + $this->assertNotNull($result); + $this->assertNull($result->getRefreshToken(), 'session was not generated'); $this->assertFalse(EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists()); /** @var Account $account */ $account = Account::findOne($fixture['account_id']); diff --git a/api/tests/unit/models/authentication/RefreshTokenFormTest.php b/api/tests/unit/models/authentication/RefreshTokenFormTest.php index fada46e..9a89703 100644 --- a/api/tests/unit/models/authentication/RefreshTokenFormTest.php +++ b/api/tests/unit/models/authentication/RefreshTokenFormTest.php @@ -1,7 +1,8 @@ refresh_token = $this->tester->grabFixture('sessions', 'admin')['refresh_token']; - $this->assertInstanceOf(AuthenticationResult::class, $model->renew()); + $this->assertNotNull($model->renew()); } } diff --git a/api/tests/unit/modules/accounts/models/ChangePasswordFormTest.php b/api/tests/unit/modules/accounts/models/ChangePasswordFormTest.php index f1fefca..803bea3 100644 --- a/api/tests/unit/modules/accounts/models/ChangePasswordFormTest.php +++ b/api/tests/unit/modules/accounts/models/ChangePasswordFormTest.php @@ -2,7 +2,7 @@ namespace api\tests\unit\modules\accounts\models; use api\components\User\Component; -use api\components\User\Identity; +use api\components\User\IdentityFactory; use api\modules\accounts\models\ChangePasswordForm; use api\tests\unit\TestCase; use common\components\UserPass; @@ -57,7 +57,7 @@ class ChangePasswordFormTest extends TestCase { public function testPerformAction() { $component = mock(Component::class . '[terminateSessions]', [[ - 'identityClass' => Identity::class, + 'identityClass' => IdentityFactory::class, 'enableSession' => false, 'loginUrl' => null, 'secret' => 'secret', @@ -119,7 +119,7 @@ class ChangePasswordFormTest extends TestCase { /** @var Component|\Mockery\MockInterface $component */ $component = mock(Component::class . '[terminateSessions]', [[ - 'identityClass' => Identity::class, + 'identityClass' => IdentityFactory::class, 'enableSession' => false, 'loginUrl' => null, 'secret' => 'secret', diff --git a/api/tests/unit/modules/accounts/models/EnableTwoFactorAuthFormTest.php b/api/tests/unit/modules/accounts/models/EnableTwoFactorAuthFormTest.php index c70c98f..09647a4 100644 --- a/api/tests/unit/modules/accounts/models/EnableTwoFactorAuthFormTest.php +++ b/api/tests/unit/modules/accounts/models/EnableTwoFactorAuthFormTest.php @@ -2,7 +2,7 @@ namespace api\tests\unit\modules\accounts\models; use api\components\User\Component; -use api\components\User\Identity; +use api\components\User\IdentityFactory; use api\modules\accounts\models\EnableTwoFactorAuthForm; use api\tests\unit\TestCase; use common\helpers\Error as E; @@ -20,7 +20,7 @@ class EnableTwoFactorAuthFormTest extends TestCase { /** @var Component|\Mockery\MockInterface $component */ $component = mock(Component::class . '[terminateSessions]', [[ - 'identityClass' => Identity::class, + 'identityClass' => IdentityFactory::class, 'enableSession' => false, 'loginUrl' => null, 'secret' => 'secret', diff --git a/autocompletion.php b/autocompletion.php index ba53026..fa14d25 100644 --- a/autocompletion.php +++ b/autocompletion.php @@ -25,6 +25,7 @@ class Yii extends \yii\BaseYii { * @property \api\components\OAuth2\Component $oauth * @property \common\components\StatsD $statsd * @property \yii\queue\Queue $queue + * @property \api\components\Tokens\Component $tokens */ abstract class BaseApplication extends yii\base\Application { } diff --git a/common/config/config-test.php b/common/config/config-test.php index 2cffd5e..ecea105 100644 --- a/common/config/config-test.php +++ b/common/config/config-test.php @@ -6,6 +6,9 @@ return [ 'fromEmail' => 'ely@ely.by', ], 'components' => [ + 'cache' => [ + 'class' => \yii\caching\FileCache::class, + ], 'security' => [ // It's allows us to increase tests speed by decreasing password hashing algorithm complexity 'passwordHashCost' => 4, diff --git a/composer.json b/composer.json index 864979b..9a0d0e1 100644 --- a/composer.json +++ b/composer.json @@ -19,6 +19,7 @@ "emarref/jwt": "~1.0.3", "goaop/framework": "^2.2.0", "guzzlehttp/guzzle": "^6.0.0", + "lcobucci/jwt": "^3.3", "league/oauth2-server": "^4.1", "mito/yii2-sentry": "^1.0", "paragonie/constant_time_encoding": "^2.0", diff --git a/composer.lock b/composer.lock index 7a3d699..6271d21 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "80ccf8b828493911307a9daa95021dfc", + "content-hash": "2dfa204a51a82cd7c7d6a5b7d1ccbc0c", "packages": [ { "name": "bacon/bacon-qr-code", @@ -54,16 +54,16 @@ }, { "name": "beberlei/assert", - "version": "v3.2.0", + "version": "v3.2.1", "source": { "type": "git", "url": "https://github.com/beberlei/assert.git", - "reference": "fd82f4c8592c8128dd74481034c31da71ebafc56" + "reference": "ce139b6bf8f07fb8389d2c8e15b98dc24fdd93c7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/beberlei/assert/zipball/fd82f4c8592c8128dd74481034c31da71ebafc56", - "reference": "fd82f4c8592c8128dd74481034c31da71ebafc56", + "url": "https://api.github.com/repos/beberlei/assert/zipball/ce139b6bf8f07fb8389d2c8e15b98dc24fdd93c7", + "reference": "ce139b6bf8f07fb8389d2c8e15b98dc24fdd93c7", "shasum": "" }, "require": { @@ -72,7 +72,7 @@ "require-dev": { "friendsofphp/php-cs-fixer": "*", "phpstan/phpstan-shim": "*", - "phpunit/phpunit": "*" + "phpunit/phpunit": ">=6.0.0 <8" }, "type": "library", "autoload": { @@ -90,13 +90,13 @@ "authors": [ { "name": "Benjamin Eberlei", - "email": "kontakt@beberlei.de", - "role": "Lead Developer" + "role": "Lead Developer", + "email": "kontakt@beberlei.de" }, { "name": "Richard Quadling", - "email": "rquadling@gmail.com", - "role": "Collaborator" + "role": "Collaborator", + "email": "rquadling@gmail.com" } ], "description": "Thin assertion library for input validation in business models.", @@ -105,7 +105,7 @@ "assertion", "validation" ], - "time": "2018-12-24T15:25:25+00:00" + "time": "2019-05-28T15:18:28+00:00" }, { "name": "bower-asset/inputmask", @@ -151,7 +151,7 @@ "version": "v1.3.2", "source": { "type": "git", - "url": "git@github.com:bestiejs/punycode.js.git", + "url": "https://github.com/bestiejs/punycode.js.git", "reference": "38c8d3131a82567bfef18da09f7f4db68c84f8a3" }, "dist": { @@ -1146,6 +1146,61 @@ ], "time": "2013-01-29T21:29:14+00:00" }, + { + "name": "lcobucci/jwt", + "version": "3.3.1", + "source": { + "type": "git", + "url": "https://github.com/lcobucci/jwt.git", + "reference": "a11ec5f4b4d75d1fcd04e133dede4c317aac9e18" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/lcobucci/jwt/zipball/a11ec5f4b4d75d1fcd04e133dede4c317aac9e18", + "reference": "a11ec5f4b4d75d1fcd04e133dede4c317aac9e18", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "ext-openssl": "*", + "php": "^5.6 || ^7.0" + }, + "require-dev": { + "mikey179/vfsstream": "~1.5", + "phpmd/phpmd": "~2.2", + "phpunit/php-invoker": "~1.1", + "phpunit/phpunit": "^5.7 || ^7.3", + "squizlabs/php_codesniffer": "~2.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.1-dev" + } + }, + "autoload": { + "psr-4": { + "Lcobucci\\JWT\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Luís Otávio Cobucci Oblonczyk", + "email": "lcobucci@gmail.com", + "role": "Developer" + } + ], + "description": "A simple library to work with JSON Web Token and JSON Web Signature", + "keywords": [ + "JWS", + "jwt" + ], + "time": "2019-05-24T18:30:49+00:00" + }, { "name": "league/event", "version": "2.2.0", diff --git a/data/certs/private.key b/data/certs/private.key deleted file mode 100644 index 5423a00..0000000 --- a/data/certs/private.key +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQDbTqmRpLg3XjDH -3Z97uHdNq4F5j77Rp+M7ctyfUhtb+U7VWppjk2Dxyp2/iPzKK3K0lC91zlnxO4HT -jFCWTIQzSfiFx/Z6nbUXYFZunzRkbt6UgXjUhnYLSIVvNDneph/BZTSxNThky7a8 -weng1+1e7cYcYx7pJWUXB9XINEKdyZ/pF+kB8UPK/LCLY4jFTm7t+N1Rm1R6VpEy -VqhwoDTefkiP9H/QZBp4Ihy48v/NTtgHdsc3Yz+//M6km39MmxIh4wBrZiIictzg -5Xmd1vXamDYFbGZHpKRuujCSufZaglrjGvgaAq1lSS+Cwc5eNCDTlw8OWGJyeSMy -AvYKK5pnAgMBAAECggEBAKcg02kCtsC7L0GhS6Dle0XdpdYWDb2IzErJxghEckUt -QT6mxXGNJxwc5QrKQptvcQLcyy5kC3cjelTVYbSoqzbK8HJDaTsYZKFj8XpsKWlA -dK+H26Vasyr2IXoVuuRKhXjEv9ssS8XE2YYP4URQSb1GRuvrPes/bEKY3fqsmPfU -/rpaUNG9OvskfIDzT+VoEe5RfPW0+uchHZHypWdnhSxLC/oH8KjcUxmCdQ3q46fT -2GhDJnDLXC8MGbyUp7Nw+eSg+4UTCjaNqV7c4vOSXqSBPch7nYFf1YqYuseok21t -UK1G55JrBfsUAmldSi1UVdnAanVRNZiC2LsdDe9PpUECgYEA7kVk7nFqtHqx6EOz -4p6AeDlslrPEWz996AgV1qezBboGlpPkDv+of5cOG4ZMpDJD5KbSIJXTPC06G+3V -VgYpg7cYO9il3I5vaxo64dC9Ib5HQe8UTreVI5763S7Zq7V0jWKOzrlKzA/KQl3x -1kHXS5levDp1uuwAdRBn6DvXnv0CgYEA66ALVI1BUU+OhqSGRQu9pZATfyB5hJaD -1iICiOgl1LRwMJW7/uWUTQ+h5H3lYDmyf+y9/8x8jTfEVZYEwV2bw9wzII87YA9R -pKQl+HMlynrgYWZ2Z94mRFs3poxU8AgpU9MDN84b2cHyP3TGhQjkdtdyFE4lcCiQ -yQqnWa+BBjMCgYEArKeKQKHcoVT7D4PnmIIkM3ng7r7qvPggAv/A219/gNnQplIa -AqhM78+EgHtrk9t8iPY88zG99DANmGlZmlEyyefl3o/ZeB2aLPC/1BvOwOHBfsyA -WZ37qukrfRTS0/LTtxPAyZlI0t9qP3cVo5zoJjbHh/uQjdcvaaRutsCOOP0CgYEA -10TB9T6UdVgM6+A2N7CxVCicV2HxA3yL+D/cNv55SaqMcSbrucY/xmPI0btfq5kr -BorhT2mgRVi0zEiiEZOXMsrj/xQ899cnDRdXBXUWCrZWd0YoWV7xcTQxVL0TALVE -JKw9XWe1tC3oR6dFk9d6+0R8miaHN8An/zT3jg21AFcCgYEAslWiTkT1ULAAhlHa -KLbSW1slYJR8/i9mwIDOoD2BvVJUSqbowAogD4mXRm6S77AxoQX4nygzE6XscR4V -h+fINRJeh7yrFk5x/GUjh7tQo9EITjY89X0s35hZ27i61l66eZ5u06j4xE5+Y424 -HMsBjKAmKFNPebTWFcAlXXaeCPU= ------END PRIVATE KEY----- diff --git a/data/certs/private.pem b/data/certs/private.pem new file mode 100644 index 0000000..cdf213f --- /dev/null +++ b/data/certs/private.pem @@ -0,0 +1,5 @@ +-----BEGIN EC PRIVATE KEY----- +MHcCAQEEIJ5ERywpRs5Rxn3JsSBhQTkzyYShmbKk1ziwif6yeBRooAoGCCqGSM49 +AwEHoUQDQgAEv6ENZA59mzFvoDKTX3BI3Nx6di+xWnsOAo9+zx0hnMnfzdhOS930 +ocFTBcyZmmF7iM7nhGicfiDfJKIyV8w+BA== +-----END EC PRIVATE KEY----- diff --git a/data/certs/public.crt b/data/certs/public.crt deleted file mode 100644 index 8659eb4..0000000 --- a/data/certs/public.crt +++ /dev/null @@ -1,16 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICljCCAX4CCQDA6sdDyK1Y/zANBgkqhkiG9w0BAQsFADANMQswCQYDVQQGEwJC -WTAeFw0xOTA3MjQxMDI5NTdaFw0yMTA3MjMxMDI5NTdaMA0xCzAJBgNVBAYTAkJZ -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA206pkaS4N14wx92fe7h3 -TauBeY++0afjO3Lcn1IbW/lO1VqaY5Ng8cqdv4j8yitytJQvdc5Z8TuB04xQlkyE -M0n4hcf2ep21F2BWbp80ZG7elIF41IZ2C0iFbzQ53qYfwWU0sTU4ZMu2vMHp4Nft -Xu3GHGMe6SVlFwfVyDRCncmf6RfpAfFDyvywi2OIxU5u7fjdUZtUelaRMlaocKA0 -3n5Ij/R/0GQaeCIcuPL/zU7YB3bHN2M/v/zOpJt/TJsSIeMAa2YiInLc4OV5ndb1 -2pg2BWxmR6Skbrowkrn2WoJa4xr4GgKtZUkvgsHOXjQg05cPDlhicnkjMgL2Ciua -ZwIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQB+i6Q3Ltg5MPEqHZ3GCpsFMV+xWKp5 -TSgguFr422az9v/Da01VHOX884D0dZt1r6W+zzfIQzIXpRqQkl4YuS1N17Q/KN3E -7rJ0R7gsXM7+KiGVrZyoZlxRaRXCiErUWBOxamIPy07zOWLnWa1kZZNDvgiurMbF -yaREQargFM8G91zkA6XiMXFoermARYB6RLtyHD0EC3I2DSZpOuMD9Kg1k/uw6f3W -xwsQY6kpzoZkYfTqoM4ky16yNPRf9vsej2dYlRr1YPWWQOicY1TrwFJMKoogylTD -lN61u8WED7Z8M00F6FYuuFffzt2Si9GrYeTuf8ZShpKiDqK0P22oiAao ------END CERTIFICATE----- diff --git a/data/certs/public.pem b/data/certs/public.pem new file mode 100644 index 0000000..aeb8f26 --- /dev/null +++ b/data/certs/public.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEv6ENZA59mzFvoDKTX3BI3Nx6di+x +WnsOAo9+zx0hnMnfzdhOS930ocFTBcyZmmF7iM7nhGicfiDfJKIyV8w+BA== +-----END PUBLIC KEY----- From 6bd054e74356c076f3e4226e549cdeeae464a12f Mon Sep 17 00:00:00 2001 From: ErickSkrauch Date: Thu, 1 Aug 2019 19:58:18 +0300 Subject: [PATCH 2/7] Fix some tests --- api/models/authentication/LoginForm.php | 6 ++---- api/tests/_support/FunctionalTester.php | 2 +- .../functional/_steps/AuthserverSteps.php | 2 +- .../unit/components/User/ComponentTest.php | 16 ++-------------- .../User}/JwtIdentityTest.php | 2 +- .../tests/unit/rbac/rules/AccountOwnerTest.php | 18 ++++++------------ .../unit/rbac/rules/OauthClientOwnerTest.php | 10 ++++------ 7 files changed, 17 insertions(+), 39 deletions(-) rename api/tests/unit/{models => components/User}/JwtIdentityTest.php (97%) diff --git a/api/models/authentication/LoginForm.php b/api/models/authentication/LoginForm.php index 88c86ed..455bfa4 100644 --- a/api/models/authentication/LoginForm.php +++ b/api/models/authentication/LoginForm.php @@ -112,22 +112,20 @@ class LoginForm extends ApiForm { Assert::true($account->save(), 'Unable to upgrade user\'s password'); } - $refreshToken = null; + $session = null; if ($this->rememberMe) { $session = new AccountSession(); $session->account_id = $account->id; $session->setIp(Yii::$app->request->userIP); $session->generateRefreshToken(); Assert::true($session->save(), 'Cannot save account session model'); - - $refreshToken = $session->refresh_token; } $token = TokensFactory::createForAccount($account, $session); $transaction->commit(); - return new AuthenticationResult($token, $refreshToken); + return new AuthenticationResult($token, $session ? $session->refresh_token : null); } } diff --git a/api/tests/_support/FunctionalTester.php b/api/tests/_support/FunctionalTester.php index 5061011..86bef30 100644 --- a/api/tests/_support/FunctionalTester.php +++ b/api/tests/_support/FunctionalTester.php @@ -13,7 +13,7 @@ use Yii; class FunctionalTester extends Actor { use FunctionalTesterActions; - public function amAuthenticated(string $asUsername = 'admin'): int { + public function amAuthenticated(string $asUsername = 'admin') { // Do not declare type /** @var Account $account */ $account = Account::findOne(['username' => $asUsername]); if ($account === null) { diff --git a/api/tests/functional/_steps/AuthserverSteps.php b/api/tests/functional/_steps/AuthserverSteps.php index 84102a8..97cb5bf 100644 --- a/api/tests/functional/_steps/AuthserverSteps.php +++ b/api/tests/functional/_steps/AuthserverSteps.php @@ -9,7 +9,7 @@ use Ramsey\Uuid\Uuid; class AuthserverSteps extends FunctionalTester { - public function amAuthenticated(string $asUsername = 'admin', string $password = 'password_0'): array { + public function amAuthenticated(string $asUsername = 'admin', string $password = 'password_0') { $route = new AuthserverRoute($this); $clientToken = Uuid::uuid4()->toString(); $route->authenticate([ diff --git a/api/tests/unit/components/User/ComponentTest.php b/api/tests/unit/components/User/ComponentTest.php index 6dd371b..4232c39 100644 --- a/api/tests/unit/components/User/ComponentTest.php +++ b/api/tests/unit/components/User/ComponentTest.php @@ -25,7 +25,7 @@ class ComponentTest extends TestCase { public function _before() { parent::_before(); - $this->component = new Component($this->getComponentConfig()); + $this->component = new Component(); } public function _fixtures(): array { @@ -72,7 +72,6 @@ class ComponentTest extends TestCase { /** @var Component|\PHPUnit\Framework\MockObject\MockObject $component */ $component = $this->getMockBuilder(Component::class) ->setMethods(['getIsGuest']) - ->setConstructorArgs([$this->getComponentConfig()]) ->getMock(); $component @@ -91,7 +90,7 @@ class ComponentTest extends TestCase { $session = $this->tester->grabFixture('sessions', 'admin2'); /** @var Component|\Mockery\MockInterface $component */ - $component = mock(Component::class . '[getActiveSession]', [$this->getComponentConfig()])->makePartial(); + $component = mock(Component::class . '[getActiveSession]')->makePartial(); $component->shouldReceive('getActiveSession')->times(1)->andReturn($session); /** @var Account $account */ @@ -140,15 +139,4 @@ class ComponentTest extends TestCase { Yii::$app->request->headers->set('Authorization', $bearerToken); } - private function getComponentConfig() { - return [ - 'identityClass' => IdentityFactory::class, - 'enableSession' => false, - 'loginUrl' => null, - 'secret' => 'secret', - 'publicKeyPath' => 'data/certs/public.crt', - 'privateKeyPath' => 'data/certs/private.key', - ]; - } - } diff --git a/api/tests/unit/models/JwtIdentityTest.php b/api/tests/unit/components/User/JwtIdentityTest.php similarity index 97% rename from api/tests/unit/models/JwtIdentityTest.php rename to api/tests/unit/components/User/JwtIdentityTest.php index 04855ea..828eaf4 100644 --- a/api/tests/unit/models/JwtIdentityTest.php +++ b/api/tests/unit/components/User/JwtIdentityTest.php @@ -1,7 +1,7 @@ 'secret', - 'publicKeyPath' => 'data/certs/public.crt', - 'privateKeyPath' => 'data/certs/private.key', - ]]); - $component->shouldDeferMissing(); + $component = mock(Component::class . '[findIdentityByAccessToken]'); + $component->makePartial(); $component->shouldReceive('findIdentityByAccessToken')->andReturn(null); Yii::$app->set('user', $component); @@ -38,12 +36,8 @@ class AccountOwnerTest extends TestCase { $identity = mock(IdentityInterface::class); $identity->shouldReceive('getAccount')->andReturn($account); - $component = mock(Component::class . '[findIdentityByAccessToken]', [[ - 'secret' => 'secret', - 'publicKeyPath' => 'data/certs/public.crt', - 'privateKeyPath' => 'data/certs/private.key', - ]]); - $component->shouldDeferMissing(); + $component = mock(Component::class . '[findIdentityByAccessToken]'); + $component->makePartial(); $component->shouldReceive('findIdentityByAccessToken')->withArgs(['token'])->andReturn($identity); Yii::$app->set('user', $component); diff --git a/common/tests/unit/rbac/rules/OauthClientOwnerTest.php b/common/tests/unit/rbac/rules/OauthClientOwnerTest.php index 7148c3b..31520fb 100644 --- a/common/tests/unit/rbac/rules/OauthClientOwnerTest.php +++ b/common/tests/unit/rbac/rules/OauthClientOwnerTest.php @@ -1,4 +1,6 @@ shouldReceive('getAccount')->andReturn($account); /** @var Component|\Mockery\MockInterface $component */ - $component = mock(Component::class . '[findIdentityByAccessToken]', [[ - 'secret' => 'secret', - 'publicKeyPath' => 'data/certs/public.crt', - 'privateKeyPath' => 'data/certs/private.key', - ]]); - $component->shouldDeferMissing(); + $component = mock(Component::class . '[findIdentityByAccessToken]'); + $component->makePartial(); $component->shouldReceive('findIdentityByAccessToken')->withArgs(['token'])->andReturn($identity); Yii::$app->set('user', $component); From f2ab7346aaf955f8180b063f191d615c778d8466 Mon Sep 17 00:00:00 2001 From: ErickSkrauch Date: Fri, 2 Aug 2019 03:29:20 +0300 Subject: [PATCH 3/7] Fixed almost everything, but all functional tests are broken at the last minute :( --- api/codeception.dist.yml | 1 + .../OAuth2/Storage/ScopeStorage.php | 2 +- api/components/Tokens/Component.php | 9 +- api/components/Tokens/TokensFactory.php | 3 +- api/components/User/Component.php | 46 +--- api/components/User/JwtIdentity.php | 15 +- .../controllers/DefaultController.php | 2 +- api/modules/accounts/models/AccountInfo.php | 2 +- .../controllers/AccountsController.php | 2 +- .../controllers/AuthorizationController.php | 2 +- .../oauth/controllers/ClientsController.php | 2 +- .../oauth/controllers/IdentityController.php | 2 +- api/modules/oauth/models/OauthProcess.php | 2 +- api/modules/session/models/JoinForm.php | 2 +- {common => api}/rbac/.generated/.gitignore | 0 api/rbac/Manager.php | 38 +++ {common => api}/rbac/Permissions.php | 4 +- {common => api}/rbac/Roles.php | 4 +- {common => api}/rbac/rules/AccountOwner.php | 11 +- .../rbac/rules/OauthClientOwner.php | 15 +- .../functional/_steps/SessionServerSteps.php | 2 +- api/tests/functional/accounts/BanCest.php | 2 +- api/tests/functional/accounts/PardonCest.php | 2 +- api/tests/functional/oauth/AuthCodeCest.php | 2 +- .../functional/oauth/RefreshTokenCest.php | 2 +- .../functional/sessionserver/JoinCest.php | 2 +- .../sessionserver/JoinLegacyCest.php | 2 +- .../unit/components/Tokens/ComponentTest.php | 10 +- .../unit/components/User/ComponentTest.php | 98 +++---- .../unit/components/User/JwtIdentityTest.php | 99 ++++--- .../models/authentication/LogoutFormTest.php | 16 +- .../authentication/RefreshTokenFormTest.php | 52 ++-- .../models/ChangePasswordFormTest.php | 21 +- .../models/EnableTwoFactorAuthFormTest.php | 12 +- .../unit/rbac/rules/AccountOwnerTest.php | 43 +-- .../unit/rbac/rules/OauthClientOwnerTest.php | 39 ++- .../PasswordRequiredValidatorTest.php | 2 +- api/validators/PasswordRequiredValidator.php | 2 +- common/codeception.dist.yml | 1 + common/config/config.php | 2 +- common/rbac/Manager.php | 34 --- composer.json | 2 +- composer.lock | 244 +++++++++++++++--- console/codeception.dist.yml | 1 + console/controllers/RbacController.php | 25 +- 45 files changed, 504 insertions(+), 377 deletions(-) rename {common => api}/rbac/.generated/.gitignore (100%) create mode 100644 api/rbac/Manager.php rename {common => api}/rbac/Permissions.php (97%) rename {common => api}/rbac/Roles.php (65%) rename {common => api}/rbac/rules/AccountOwner.php (89%) rename {common => api}/rbac/rules/OauthClientOwner.php (81%) rename {common => api}/tests/unit/rbac/rules/AccountOwnerTest.php (61%) rename {common => api}/tests/unit/rbac/rules/OauthClientOwnerTest.php (55%) delete mode 100644 common/rbac/Manager.php diff --git a/api/codeception.dist.yml b/api/codeception.dist.yml index 4f785ce..ff9f984 100644 --- a/api/codeception.dist.yml +++ b/api/codeception.dist.yml @@ -22,4 +22,5 @@ coverage: - tests/* - codeception.dist.yml - codeception.yml + - index.php c3url: 'http://localhost/api/web/index.php' diff --git a/api/components/OAuth2/Storage/ScopeStorage.php b/api/components/OAuth2/Storage/ScopeStorage.php index 85be563..6defc0c 100644 --- a/api/components/OAuth2/Storage/ScopeStorage.php +++ b/api/components/OAuth2/Storage/ScopeStorage.php @@ -3,8 +3,8 @@ namespace api\components\OAuth2\Storage; use api\components\OAuth2\Entities\ClientEntity; use api\components\OAuth2\Entities\ScopeEntity; +use api\rbac\Permissions as P; use Assert\Assert; -use common\rbac\Permissions as P; use League\OAuth2\Server\Storage\AbstractStorage; use League\OAuth2\Server\Storage\ScopeInterface; diff --git a/api/components/Tokens/Component.php b/api/components/Tokens/Component.php index a16cea4..8872e7c 100644 --- a/api/components/Tokens/Component.php +++ b/api/components/Tokens/Component.php @@ -3,6 +3,7 @@ declare(strict_types=1); namespace api\components\Tokens; +use Carbon\Carbon; use Exception; use Lcobucci\JWT\Builder; use Lcobucci\JWT\Parser; @@ -11,8 +12,6 @@ use yii\base\Component as BaseComponent; class Component extends BaseComponent { - private const EXPIRATION_TIMEOUT = 3600; // 1h - private const PREFERRED_ALGORITHM = 'ES256'; /** @@ -41,10 +40,10 @@ class Component extends BaseComponent { private $algorithmManager; public function create(array $payloads = [], array $headers = []): Token { - $time = time(); + $now = Carbon::now(); $builder = (new Builder()) - ->issuedAt($time) - ->expiresAt($time + self::EXPIRATION_TIMEOUT); + ->issuedAt($now->getTimestamp()) + ->expiresAt($now->addHour()->getTimestamp()); foreach ($payloads as $claim => $value) { $builder->withClaim($claim, $value); } diff --git a/api/components/Tokens/TokensFactory.php b/api/components/Tokens/TokensFactory.php index e92446a..00fee41 100644 --- a/api/components/Tokens/TokensFactory.php +++ b/api/components/Tokens/TokensFactory.php @@ -3,6 +3,7 @@ declare(strict_types=1); namespace api\components\Tokens; +use Carbon\Carbon; use common\models\Account; use common\models\AccountSession; use Lcobucci\JWT\Token; @@ -20,7 +21,7 @@ class TokensFactory { if ($session === null) { // If we don't remember a session, the token should live longer // so that the session doesn't end while working with the account - $payloads['exp'] = time() + 60 * 60 * 24 * 7; // 7d + $payloads['exp'] = Carbon::now()->addDays(7)->getTimestamp(); } else { $payloads['jti'] = $session->id; } diff --git a/api/components/User/Component.php b/api/components/User/Component.php index 955a857..bf00f9c 100644 --- a/api/components/User/Component.php +++ b/api/components/User/Component.php @@ -5,10 +5,6 @@ namespace api\components\User; use common\models\Account; use common\models\AccountSession; -use Exception; -use InvalidArgumentException; -use Yii; -use yii\web\UnauthorizedHttpException; use yii\web\User as YiiUserComponent; /** @@ -38,29 +34,11 @@ class Component extends YiiUserComponent { */ public $identityClass = IdentityFactory::class; - public function findIdentityByAccessToken($accessToken): ?IdentityInterface { - if (empty($accessToken)) { - return null; - } - - try { - return IdentityFactory::findIdentityByAccessToken($accessToken); - } catch (UnauthorizedHttpException $e) { - // TODO: if this exception is catched there, how it forms "Token expired" exception? - // Do nothing. It's okay to catch this. - } catch (Exception $e) { - Yii::error($e); - } - - return null; - } - /** * The method searches AccountSession model, which one has been used to create current JWT token. * null will be returned in case when any of the following situations occurred: * - The user isn't authorized - * - There is no header with a token - * - Token validation isn't passed and some exception has been thrown + * - The user isn't authorized via JWT token * - No session key found in the token. This is possible if the user chose not to remember me * or just some old tokens, without the support of saving the used session * @@ -71,18 +49,13 @@ class Component extends YiiUserComponent { return null; } - $bearer = $this->getBearerToken(); - if ($bearer === null) { + /** @var IdentityInterface $identity */ + $identity = $this->getIdentity(); + if (!$identity instanceof JwtIdentity) { return null; } - try { - $token = Yii::$app->tokens->parse($bearer); - } catch (InvalidArgumentException $e) { - return null; - } - - $sessionId = $token->getClaim('jti', false); + $sessionId = $identity->getToken()->getClaim('jti', false); if ($sessionId === false) { return null; } @@ -111,13 +84,4 @@ class Component extends YiiUserComponent { } } - private function getBearerToken(): ?string { - $authHeader = Yii::$app->request->getHeaders()->get('Authorization'); - if ($authHeader === null || !preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) { - return null; - } - - return $matches[1]; - } - } diff --git a/api/components/User/JwtIdentity.php b/api/components/User/JwtIdentity.php index 479351f..e327e32 100644 --- a/api/components/User/JwtIdentity.php +++ b/api/components/User/JwtIdentity.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace api\components\User; use api\components\Tokens\TokensFactory; +use Carbon\Carbon; use common\models\Account; use Exception; use Lcobucci\JWT\Token; @@ -36,22 +37,27 @@ class JwtIdentity implements IdentityInterface { throw new UnauthorizedHttpException('Incorrect token'); } - if ($token->isExpired()) { + $now = Carbon::now(); + if ($token->isExpired($now)) { throw new UnauthorizedHttpException('Token expired'); } - if (!$token->validate(new ValidationData())) { + if (!$token->validate(new ValidationData($now->getTimestamp()))) { throw new UnauthorizedHttpException('Incorrect token'); } $sub = $token->getClaim('sub', false); - if ($sub !== false && strpos($sub, TokensFactory::SUB_ACCOUNT_PREFIX) !== 0) { + if ($sub !== false && strpos((string)$sub, TokensFactory::SUB_ACCOUNT_PREFIX) !== 0) { throw new UnauthorizedHttpException('Incorrect token'); } return new self($token); } + public function getToken(): Token { + return $this->token; + } + public function getAccount(): ?Account { $subject = $this->token->getClaim('sub', false); if ($subject === false) { @@ -77,6 +83,7 @@ class JwtIdentity implements IdentityInterface { return (string)$this->token; } + // @codeCoverageIgnoreStart public function getAuthKey() { throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth'); } @@ -89,4 +96,6 @@ class JwtIdentity implements IdentityInterface { throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth'); } + // @codeCoverageIgnoreEnd + } diff --git a/api/modules/accounts/controllers/DefaultController.php b/api/modules/accounts/controllers/DefaultController.php index b9ac258..911d434 100644 --- a/api/modules/accounts/controllers/DefaultController.php +++ b/api/modules/accounts/controllers/DefaultController.php @@ -5,8 +5,8 @@ use api\controllers\Controller; use api\modules\accounts\actions; use api\modules\accounts\models\AccountInfo; use api\modules\accounts\models\TwoFactorAuthInfo; +use api\rbac\Permissions as P; use common\models\Account; -use common\rbac\Permissions as P; use Yii; use yii\filters\AccessControl; use yii\helpers\ArrayHelper; diff --git a/api/modules/accounts/models/AccountInfo.php b/api/modules/accounts/models/AccountInfo.php index 87b486a..0086cf9 100644 --- a/api/modules/accounts/models/AccountInfo.php +++ b/api/modules/accounts/models/AccountInfo.php @@ -2,8 +2,8 @@ namespace api\modules\accounts\models; use api\models\base\BaseAccountForm; +use api\rbac\Permissions as P; use common\models\Account; -use common\rbac\Permissions as P; use yii\di\Instance; use yii\web\User; diff --git a/api/modules/internal/controllers/AccountsController.php b/api/modules/internal/controllers/AccountsController.php index 92bf23c..abea541 100644 --- a/api/modules/internal/controllers/AccountsController.php +++ b/api/modules/internal/controllers/AccountsController.php @@ -2,8 +2,8 @@ namespace api\modules\internal\controllers; use api\controllers\Controller; +use api\rbac\Permissions as P; use common\models\Account; -use common\rbac\Permissions as P; use yii\filters\AccessControl; use yii\helpers\ArrayHelper; use yii\web\BadRequestHttpException; diff --git a/api/modules/oauth/controllers/AuthorizationController.php b/api/modules/oauth/controllers/AuthorizationController.php index 03d073f..51b1ae4 100644 --- a/api/modules/oauth/controllers/AuthorizationController.php +++ b/api/modules/oauth/controllers/AuthorizationController.php @@ -3,7 +3,7 @@ namespace api\modules\oauth\controllers; use api\controllers\Controller; use api\modules\oauth\models\OauthProcess; -use common\rbac\Permissions as P; +use api\rbac\Permissions as P; use Yii; use yii\filters\AccessControl; use yii\helpers\ArrayHelper; diff --git a/api/modules/oauth/controllers/ClientsController.php b/api/modules/oauth/controllers/ClientsController.php index 485c1c5..9439376 100644 --- a/api/modules/oauth/controllers/ClientsController.php +++ b/api/modules/oauth/controllers/ClientsController.php @@ -7,9 +7,9 @@ use api\modules\oauth\exceptions\UnsupportedOauthClientType; use api\modules\oauth\models\OauthClientForm; use api\modules\oauth\models\OauthClientFormFactory; use api\modules\oauth\models\OauthClientTypeForm; +use api\rbac\Permissions as P; use common\models\Account; use common\models\OauthClient; -use common\rbac\Permissions as P; use Yii; use yii\filters\AccessControl; use yii\helpers\ArrayHelper; diff --git a/api/modules/oauth/controllers/IdentityController.php b/api/modules/oauth/controllers/IdentityController.php index 5f0f952..034e8c5 100644 --- a/api/modules/oauth/controllers/IdentityController.php +++ b/api/modules/oauth/controllers/IdentityController.php @@ -3,7 +3,7 @@ namespace api\modules\oauth\controllers; use api\controllers\Controller; use api\modules\oauth\models\IdentityInfo; -use common\rbac\Permissions as P; +use api\rbac\Permissions as P; use Yii; use yii\filters\AccessControl; use yii\helpers\ArrayHelper; diff --git a/api/modules/oauth/models/OauthProcess.php b/api/modules/oauth/models/OauthProcess.php index d282c95..ee0ebd6 100644 --- a/api/modules/oauth/models/OauthProcess.php +++ b/api/modules/oauth/models/OauthProcess.php @@ -5,9 +5,9 @@ use api\components\OAuth2\Exception\AcceptRequiredException; use api\components\OAuth2\Exception\AccessDeniedException; use api\components\OAuth2\Grants\AuthCodeGrant; use api\components\OAuth2\Grants\AuthorizeParams; +use api\rbac\Permissions as P; use common\models\Account; use common\models\OauthClient; -use common\rbac\Permissions as P; use League\OAuth2\Server\AuthorizationServer; use League\OAuth2\Server\Exception\InvalidGrantException; use League\OAuth2\Server\Exception\OAuthException; diff --git a/api/modules/session/models/JoinForm.php b/api/modules/session/models/JoinForm.php index 0361ae5..bc4e2ad 100644 --- a/api/modules/session/models/JoinForm.php +++ b/api/modules/session/models/JoinForm.php @@ -6,10 +6,10 @@ use api\modules\session\exceptions\IllegalArgumentException; use api\modules\session\models\protocols\JoinInterface; use api\modules\session\Module as Session; use api\modules\session\validators\RequiredValidator; +use api\rbac\Permissions as P; use common\helpers\StringHelper; use common\models\Account; use common\models\MinecraftAccessKey; -use common\rbac\Permissions as P; use Ramsey\Uuid\Uuid; use Yii; use yii\base\ErrorException; diff --git a/common/rbac/.generated/.gitignore b/api/rbac/.generated/.gitignore similarity index 100% rename from common/rbac/.generated/.gitignore rename to api/rbac/.generated/.gitignore diff --git a/api/rbac/Manager.php b/api/rbac/Manager.php new file mode 100644 index 0000000..9829158 --- /dev/null +++ b/api/rbac/Manager.php @@ -0,0 +1,38 @@ +user->getIdentity(); + if ($identity === null) { + return []; + } + + /** @noinspection NullPointerExceptionInspection */ + $rawPermissions = $identity->getAssignedPermissions(); + $result = []; + foreach ($rawPermissions as $name) { + $result[$name] = new Assignment(['roleName' => $name]); + } + + return $result; + } + +} diff --git a/common/rbac/Permissions.php b/api/rbac/Permissions.php similarity index 97% rename from common/rbac/Permissions.php rename to api/rbac/Permissions.php index 1b0b710..914905c 100644 --- a/common/rbac/Permissions.php +++ b/api/rbac/Permissions.php @@ -1,5 +1,7 @@ user->findIdentityByAccessToken($accessToken); + $identity = Yii::$app->user->getIdentity(); if ($identity === null) { return false; } diff --git a/common/rbac/rules/OauthClientOwner.php b/api/rbac/rules/OauthClientOwner.php similarity index 81% rename from common/rbac/rules/OauthClientOwner.php rename to api/rbac/rules/OauthClientOwner.php index b03636a..942dc13 100644 --- a/common/rbac/rules/OauthClientOwner.php +++ b/api/rbac/rules/OauthClientOwner.php @@ -1,10 +1,11 @@ execute($accessToken, $item, ['accountId' => $accountId]); } - $clientId = $params['clientId'] ?? null; - if ($clientId === null) { - return false; - } - + Assert::keyExists($params, 'clientId'); /** @var OauthClient|null $client */ - $client = OauthClient::findOne($clientId); + $client = OauthClient::findOne(['id' => $params['clientId']]); if ($client === null) { return true; } - $identity = Yii::$app->user->findIdentityByAccessToken($accessToken); + $identity = Yii::$app->user->getIdentity(); if ($identity === null) { return false; } diff --git a/api/tests/functional/_steps/SessionServerSteps.php b/api/tests/functional/_steps/SessionServerSteps.php index f33e2c8..00e8071 100644 --- a/api/tests/functional/_steps/SessionServerSteps.php +++ b/api/tests/functional/_steps/SessionServerSteps.php @@ -1,9 +1,9 @@ component = Yii::$app->tokens; - } - public function testCreate() { // Run without any arguments $token = $this->component->create(); @@ -80,6 +75,11 @@ class ComponentTest extends TestCase { ]; } + protected function _setUp() { + parent::_setUp(); + $this->component = Yii::$app->tokens; + } + private function assertValidParsedToken(Token $token, string $expectedAlg) { $this->assertSame($expectedAlg, $token->getHeader('alg')); $this->assertSame(1564527476, $token->getClaim('iat')); diff --git a/api/tests/unit/components/User/ComponentTest.php b/api/tests/unit/components/User/ComponentTest.php index 4232c39..1d9ac6e 100644 --- a/api/tests/unit/components/User/ComponentTest.php +++ b/api/tests/unit/components/User/ComponentTest.php @@ -4,17 +4,16 @@ declare(strict_types=1); namespace codeception\api\unit\components\User; use api\components\User\Component; -use api\components\User\IdentityFactory; +use api\components\User\JwtIdentity; +use api\components\User\Oauth2Identity; use api\tests\unit\TestCase; use common\models\Account; use common\models\AccountSession; use common\tests\fixtures\AccountFixture; use common\tests\fixtures\AccountSessionFixture; use common\tests\fixtures\MinecraftAccessKeyFixture; -use Emarref\Jwt\Claim; -use Emarref\Jwt\Jwt; -use Yii; -use yii\web\Request; +use Lcobucci\JWT\Claim\Basic; +use Lcobucci\JWT\Token; class ComponentTest extends TestCase { @@ -36,53 +35,37 @@ class ComponentTest extends TestCase { ]; } - // TODO: move test to refresh token form - public function testRenewJwtAuthenticationToken() { - $userIP = '192.168.0.1'; - $this->mockRequest($userIP); - /** @var AccountSession $session */ - $session = $this->tester->grabFixture('sessions', 'admin'); - $result = $this->component->renewJwtAuthenticationToken($session); - $this->assertSame($session, $result->getSession()); - $this->assertSame($session->account_id, $result->getAccount()->id); - $session->refresh(); // reload data from db - $this->assertEqualsWithDelta(time(), $session->last_refreshed_at, 3); - $this->assertSame($userIP, $session->getReadableIp()); - $payloads = (new Jwt())->deserialize($result->getJwt())->getPayload(); - /** @noinspection NullPointerExceptionInspection */ - $this->assertEqualsWithDelta(time(), $payloads->findClaimByName(Claim\IssuedAt::NAME)->getValue(), 3); - /** @noinspection NullPointerExceptionInspection */ - $this->assertEqualsWithDelta(time() + 3600, $payloads->findClaimByName('exp')->getValue(), 3); - /** @noinspection NullPointerExceptionInspection */ - $this->assertSame('ely|1', $payloads->findClaimByName('sub')->getValue()); - /** @noinspection NullPointerExceptionInspection */ - $this->assertSame('accounts_web_user', $payloads->findClaimByName('ely-scopes')->getValue()); - /** @noinspection NullPointerExceptionInspection */ - $this->assertSame($session->id, $payloads->findClaimByName('jti')->getValue(), 'session has not changed'); - } - public function testGetActiveSession() { - /** @var Account $account */ - $account = $this->tester->grabFixture('accounts', 'admin'); - /** @var AccountSession $session */ - $session = $this->tester->grabFixture('sessions', 'admin'); - $token = $this->component->createJwtAuthenticationToken($account, $session); - $jwt = $this->component->serializeToken($token); + // User is guest + $component = new Component(); + $this->assertNull($component->getActiveSession()); - /** @var Component|\PHPUnit\Framework\MockObject\MockObject $component */ - $component = $this->getMockBuilder(Component::class) - ->setMethods(['getIsGuest']) - ->getMock(); + // Identity is a Oauth2Identity + $component->setIdentity(mock(Oauth2Identity::class)); + $this->assertNull($component->getActiveSession()); - $component - ->method('getIsGuest') - ->willReturn(false); + // Identity is correct, but have no jti claim + /** @var JwtIdentity|\Mockery\MockInterface $identity */ + $identity = mock(JwtIdentity::class); + $identity->shouldReceive('getToken')->andReturn(new Token()); + $component->setIdentity($identity); + $this->assertNull($component->getActiveSession()); - $this->mockAuthorizationHeader($jwt); + // Identity is correct and has jti claim, but there is no associated session + /** @var JwtIdentity|\Mockery\MockInterface $identity */ + $identity = mock(JwtIdentity::class); + $identity->shouldReceive('getToken')->andReturn(new Token([], ['jti' => new Basic('jti', 999999)])); + $component->setIdentity($identity); + $this->assertNull($component->getActiveSession()); - $foundSession = $component->getActiveSession(); - $this->assertInstanceOf(AccountSession::class, $foundSession); - $this->assertSame($session->id, $foundSession->id); + // Identity is correct, has jti claim and associated session exists + /** @var JwtIdentity|\Mockery\MockInterface $identity */ + $identity = mock(JwtIdentity::class); + $identity->shouldReceive('getToken')->andReturn(new Token([], ['jti' => new Basic('jti', 1)])); + $component->setIdentity($identity); + $session = $component->getActiveSession(); + $this->assertNotNull($session); + $this->assertSame(1, $session->id); } public function testTerminateSessions() { @@ -95,7 +78,6 @@ class ComponentTest extends TestCase { /** @var Account $account */ $account = $this->tester->grabFixture('accounts', 'admin'); - $component->createJwtAuthenticationToken($account); // Dry run: no sessions should be removed $component->terminateSessions($account, Component::KEEP_MINECRAFT_SESSIONS | Component::KEEP_SITE_SESSIONS); @@ -119,24 +101,4 @@ class ComponentTest extends TestCase { $this->assertEmpty($account->getMinecraftAccessKeys()->all()); } - private function mockRequest($userIP = '127.0.0.1') { - /** @var Request|\Mockery\MockInterface $request */ - $request = mock(Request::class . '[getHostInfo,getUserIP]')->makePartial(); - $request->shouldReceive('getHostInfo')->andReturn('http://localhost'); - $request->shouldReceive('getUserIP')->andReturn($userIP); - - Yii::$app->set('request', $request); - } - - /** - * @param string $bearerToken - */ - private function mockAuthorizationHeader($bearerToken = null) { - if ($bearerToken !== null) { - $bearerToken = 'Bearer ' . $bearerToken; - } - - Yii::$app->request->headers->set('Authorization', $bearerToken); - } - } diff --git a/api/tests/unit/components/User/JwtIdentityTest.php b/api/tests/unit/components/User/JwtIdentityTest.php index 828eaf4..ef8c082 100644 --- a/api/tests/unit/components/User/JwtIdentityTest.php +++ b/api/tests/unit/components/User/JwtIdentityTest.php @@ -5,9 +5,9 @@ namespace codeception\api\unit\components\User; use api\components\User\JwtIdentity; use api\tests\unit\TestCase; +use Carbon\Carbon; use common\tests\fixtures\AccountFixture; -use Emarref\Jwt\Claim\Expiration as ExpirationClaim; -use Yii; +use yii\web\UnauthorizedHttpException; class JwtIdentityTest extends TestCase { @@ -18,40 +18,77 @@ class JwtIdentityTest extends TestCase { } public function testFindIdentityByAccessToken() { - $token = $this->generateToken(); + $token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ.4Oidvuo4spvUf9hkpHR72eeqZUh2Zbxh_L8Od3vcgTj--0iOrcOEp6zwmEW6vF7BTHtjz2b3mXce61bqsCjXjQ'; + /** @var JwtIdentity $identity */ $identity = JwtIdentity::findIdentityByAccessToken($token); $this->assertSame($token, $identity->getId()); - $this->assertSame($this->tester->grabFixture('accounts', 'admin')['id'], $identity->getAccount()->id); - } - - /** - * @expectedException \yii\web\UnauthorizedHttpException - * @expectedExceptionMessage Token expired - */ - public function testFindIdentityByAccessTokenWithExpiredToken() { - $expiredToken = $this->generateToken(time() - 3600); - JwtIdentity::findIdentityByAccessToken($expiredToken); - } - - /** - * @expectedException \yii\web\UnauthorizedHttpException - * @expectedExceptionMessage Incorrect token - */ - public function testFindIdentityByAccessTokenWithEmptyToken() { - JwtIdentity::findIdentityByAccessToken(''); - } - - private function generateToken(int $expiresAt = null): string { - /** @var \api\components\User\Component $component */ - $component = Yii::$app->user; + $this->assertSame($token, (string)$identity->getToken()); /** @var \common\models\Account $account */ $account = $this->tester->grabFixture('accounts', 'admin'); - $token = $component->createJwtAuthenticationToken($account); - if ($expiresAt !== null) { - $token->addClaim(new ExpirationClaim($expiresAt)); - } + $this->assertSame($account->id, $identity->getAccount()->id); + } - return $component->serializeToken($token); + /** + * @dataProvider getFindIdentityByAccessTokenInvalidCases + */ + public function testFindIdentityByAccessTokenInvalidCases(string $token, string $expectedExceptionMessage) { + $this->expectException(UnauthorizedHttpException::class); + $this->expectExceptionMessage($expectedExceptionMessage); + JwtIdentity::findIdentityByAccessToken($token); + } + + public function getFindIdentityByAccessTokenInvalidCases() { + yield 'expired token' => [ + 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MDMzNDIsImV4cCI6MTU2NDYwNjk0Miwic3ViIjoiZWx5fDEifQ.36cDWyiXRArv-lgK_S5dyC5m_Ddytwkb78tMrxcPcbWEpoeg2VtwPC7zr6NI0cd0CuLw6InC2hZ9Ey95SSOsHw', + 'Token expired', + ]; + yield 'iat from future' => [ + 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTc3NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ._6hj6XUSmSLibgT9ZE1Pokf4oI9r-d6tEc1z2J-fBlr1710Qiso5yNcXqb3Z_xy7Qtemyq8jOlOZA8DvmkVBrg', + 'Incorrect token', + ]; + yield 'invalid signature' => [ + 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ.yth31f2PyhUkYSfBlizzUXWIgOvxxk8gNP-js0z8g1OT5rig40FPTIkgsZRctAwAAlj6QoIWW7-hxLTcSb2vmw', + 'Incorrect token', + ]; + yield 'invalid sub' => [ + 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoxMjM0fQ.yigP5nWFdX0ktbuZC_Unb9bWxpAVd7Nv8Fb1Vsa0t5WkVA88VbhPi2P-CenbDOy8ngwoGV9m3c3upMs2V3gqvw', + 'Incorrect token', + ]; + yield 'empty token' => ['', 'Incorrect token']; + } + + public function testGetAccount() { + // Token with sub claim + $identity = JwtIdentity::findIdentityByAccessToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ.4Oidvuo4spvUf9hkpHR72eeqZUh2Zbxh_L8Od3vcgTj--0iOrcOEp6zwmEW6vF7BTHtjz2b3mXce61bqsCjXjQ'); + $this->assertSame(1, $identity->getAccount()->id); + + // Sub presented, but account not exists + $identity = JwtIdentity::findIdentityByAccessToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDk5OTk5In0.1pAnhkR-_ZqzjLBR-PNIMJUXRSUK3aYixrFNKZg2ynPNPiDvzh8U-iBTT6XRfMP5nvfXZucRpoPVoiXtx40CUQ'); + $this->assertNull($identity->getAccount()); + + // Token without sub claim + $identity = JwtIdentity::findIdentityByAccessToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Mn0.QxmYgSflZOQmhzYRr8bowU767yu4yKgTVaho0MPuyCmUfZO_0O0SQASMKVILf-wlT0ODTTG7vD753a2MTAmPmw'); + $this->assertNull($identity->getAccount()); + } + + public function testGetAssignedPermissions() { + // Token with ely-scopes claim + $identity = JwtIdentity::findIdentityByAccessToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoicGVybTEscGVybTIscGVybTMiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ.MO6T92EOFcZSPIdK8VBUG0qyV-pdayzOPQmpWLPwpl1933E9ann9GdV49piX1IfLHeCHVGThm5_v7AJgyZ5Oaw'); + $this->assertSame(['perm1', 'perm2', 'perm3'], $identity->getAssignedPermissions()); + + // Token without sub claim + $identity = JwtIdentity::findIdentityByAccessToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ.jsjv2dDetSxu4xivlHoTeDUhqsl-cxSI6SktufJhwR9wqDgQCVIONiqQCUzTzyTwyAz4Ztvel4lKjMCstdJOEw'); + $this->assertSame([], $identity->getAssignedPermissions()); + } + + protected function _before() { + parent::_before(); + Carbon::setTestNow(Carbon::create(2019, 8, 1, 1, 2, 22, 'Europe/Minsk')); + } + + protected function _after() { + parent::_after(); + Carbon::setTestNow(); } } diff --git a/api/tests/unit/models/authentication/LogoutFormTest.php b/api/tests/unit/models/authentication/LogoutFormTest.php index e5426f9..9608b52 100644 --- a/api/tests/unit/models/authentication/LogoutFormTest.php +++ b/api/tests/unit/models/authentication/LogoutFormTest.php @@ -1,8 +1,9 @@ specify('No actions if active session is not exists', function() { $userComp = $this ->getMockBuilder(Component::class) - ->setConstructorArgs([$this->getComponentArgs()]) ->setMethods(['getActiveSession']) ->getMock(); $userComp @@ -42,7 +42,6 @@ class LogoutFormTest extends TestCase { $userComp = $this ->getMockBuilder(Component::class) - ->setConstructorArgs([$this->getComponentArgs()]) ->setMethods(['getActiveSession']) ->getMock(); $userComp @@ -57,15 +56,4 @@ class LogoutFormTest extends TestCase { }); } - private function getComponentArgs() { - return [ - 'identityClass' => IdentityFactory::class, - 'enableSession' => false, - 'loginUrl' => null, - 'secret' => 'secret', - 'publicKeyPath' => 'data/certs/public.crt', - 'privateKeyPath' => 'data/certs/private.key', - ]; - } - } diff --git a/api/tests/unit/models/authentication/RefreshTokenFormTest.php b/api/tests/unit/models/authentication/RefreshTokenFormTest.php index 9a89703..4d26c96 100644 --- a/api/tests/unit/models/authentication/RefreshTokenFormTest.php +++ b/api/tests/unit/models/authentication/RefreshTokenFormTest.php @@ -8,6 +8,8 @@ use api\tests\unit\TestCase; use Codeception\Specify; use common\models\AccountSession; use common\tests\fixtures\AccountSessionFixture; +use Yii; +use yii\web\Request; class RefreshTokenFormTest extends TestCase { use Specify; @@ -18,34 +20,36 @@ class RefreshTokenFormTest extends TestCase { ]; } - public function testValidateRefreshToken() { - $this->specify('error.refresh_token_not_exist if passed token not exists', function() { - /** @var RefreshTokenForm $model */ - $model = new class extends RefreshTokenForm { - public function getSession() { - return null; - } - }; - $model->validateRefreshToken(); - $this->assertSame(['error.refresh_token_not_exist'], $model->getErrors('refresh_token')); - }); + public function testRenew() { + /** @var Request|\Mockery\MockInterface $request */ + $request = mock(Request::class . '[getUserIP]')->makePartial(); + $request->shouldReceive('getUserIP')->andReturn('10.1.2.3'); + Yii::$app->set('request', $request); - $this->specify('no errors if token exists', function() { - /** @var RefreshTokenForm $model */ - $model = new class extends RefreshTokenForm { - public function getSession() { - return new AccountSession(); - } - }; - $model->validateRefreshToken(); - $this->assertEmpty($model->getErrors('refresh_token')); - }); + $model = new RefreshTokenForm(); + $model->refresh_token = 'SOutIr6Seeaii3uqMVy3Wan8sKFVFrNz'; + $result = $model->renew(); + $this->assertNotNull($result); + $this->assertSame('SOutIr6Seeaii3uqMVy3Wan8sKFVFrNz', $result->getRefreshToken()); + + $token = $result->getToken(); + $this->assertSame('ely|1', $token->getClaim('sub')); + $this->assertSame('accounts_web_user', $token->getClaim('ely-scopes')); + $this->assertEqualsWithDelta(time(), $token->getClaim('iat'), 5); + $this->assertEqualsWithDelta(time() + 3600, $token->getClaim('exp'), 5); + $this->assertSame(1, $token->getClaim('jti')); + + /** @var AccountSession $session */ + $session = AccountSession::findOne(['refresh_token' => 'SOutIr6Seeaii3uqMVy3Wan8sKFVFrNz']); + $this->assertEqualsWithDelta(time(), $session->last_refreshed_at, 5); + $this->assertSame('10.1.2.3', $session->getReadableIp()); } - public function testRenew() { + public function testRenewWithInvalidRefreshToken() { $model = new RefreshTokenForm(); - $model->refresh_token = $this->tester->grabFixture('sessions', 'admin')['refresh_token']; - $this->assertNotNull($model->renew()); + $model->refresh_token = 'unknown refresh token'; + $this->assertNull($model->renew()); + $this->assertSame(['error.refresh_token_not_exist'], $model->getErrors('refresh_token')); } } diff --git a/api/tests/unit/modules/accounts/models/ChangePasswordFormTest.php b/api/tests/unit/modules/accounts/models/ChangePasswordFormTest.php index 803bea3..67dd574 100644 --- a/api/tests/unit/modules/accounts/models/ChangePasswordFormTest.php +++ b/api/tests/unit/modules/accounts/models/ChangePasswordFormTest.php @@ -1,8 +1,9 @@ IdentityFactory::class, - 'enableSession' => false, - 'loginUrl' => null, - 'secret' => 'secret', - 'publicKeyPath' => 'data/certs/public.crt', - 'privateKeyPath' => 'data/certs/private.key', - ]]); + $component = mock(Component::class . '[terminateSessions]'); $component->shouldNotReceive('terminateSessions'); Yii::$app->set('user', $component); @@ -118,14 +112,7 @@ class ChangePasswordFormTest extends TestCase { $account->setPassword('password_0'); /** @var Component|\Mockery\MockInterface $component */ - $component = mock(Component::class . '[terminateSessions]', [[ - 'identityClass' => IdentityFactory::class, - 'enableSession' => false, - 'loginUrl' => null, - 'secret' => 'secret', - 'publicKeyPath' => 'data/certs/public.crt', - 'privateKeyPath' => 'data/certs/private.key', - ]]); + $component = mock(Component::class . '[terminateSessions]'); $component->shouldReceive('terminateSessions')->once()->withArgs([$account, Component::KEEP_CURRENT_SESSION]); Yii::$app->set('user', $component); diff --git a/api/tests/unit/modules/accounts/models/EnableTwoFactorAuthFormTest.php b/api/tests/unit/modules/accounts/models/EnableTwoFactorAuthFormTest.php index 09647a4..322c908 100644 --- a/api/tests/unit/modules/accounts/models/EnableTwoFactorAuthFormTest.php +++ b/api/tests/unit/modules/accounts/models/EnableTwoFactorAuthFormTest.php @@ -1,8 +1,9 @@ otp_secret = 'mock secret'; /** @var Component|\Mockery\MockInterface $component */ - $component = mock(Component::class . '[terminateSessions]', [[ - 'identityClass' => IdentityFactory::class, - 'enableSession' => false, - 'loginUrl' => null, - 'secret' => 'secret', - 'publicKeyPath' => 'data/certs/public.crt', - 'privateKeyPath' => 'data/certs/private.key', - ]]); + $component = mock(Component::class . '[terminateSessions]'); $component->shouldReceive('terminateSessions')->withArgs([$account, Component::KEEP_CURRENT_SESSION]); Yii::$app->set('user', $component); diff --git a/common/tests/unit/rbac/rules/AccountOwnerTest.php b/api/tests/unit/rbac/rules/AccountOwnerTest.php similarity index 61% rename from common/tests/unit/rbac/rules/AccountOwnerTest.php rename to api/tests/unit/rbac/rules/AccountOwnerTest.php index dbf1c4d..065c9bb 100644 --- a/common/tests/unit/rbac/rules/AccountOwnerTest.php +++ b/api/tests/unit/rbac/rules/AccountOwnerTest.php @@ -1,12 +1,11 @@ makePartial(); - $component->shouldReceive('findIdentityByAccessToken')->andReturn(null); - - Yii::$app->set('user', $component); - - $this->assertFalse((new AccountOwner())->execute('some token', new Item(), ['accountId' => 123])); - } - public function testExecute() { $rule = new AccountOwner(); $item = new Item(); + // Identity is null + $this->assertFalse($rule->execute('some token', $item, ['accountId' => 123])); + + // Identity presented, but have no account + /** @var IdentityInterface|\Mockery\MockInterface $identity */ + $identity = mock(IdentityInterface::class); + $identity->shouldReceive('getAccount')->andReturn(null); + Yii::$app->user->setIdentity($identity); + + $this->assertFalse($rule->execute('some token', $item, ['accountId' => 123])); + + // Identity has an account $account = new Account(); $account->id = 1; $account->status = Account::STATUS_ACTIVE; $account->rules_agreement_version = LATEST_RULES_VERSION; + /** @var IdentityInterface|\Mockery\MockInterface $identity */ $identity = mock(IdentityInterface::class); $identity->shouldReceive('getAccount')->andReturn($account); - $component = mock(Component::class . '[findIdentityByAccessToken]'); - $component->makePartial(); - $component->shouldReceive('findIdentityByAccessToken')->withArgs(['token'])->andReturn($identity); + Yii::$app->user->setIdentity($identity); - Yii::$app->set('user', $component); - - $this->assertFalse($rule->execute('token', $item, [])); $this->assertFalse($rule->execute('token', $item, ['accountId' => 2])); $this->assertFalse($rule->execute('token', $item, ['accountId' => '2'])); $this->assertTrue($rule->execute('token', $item, ['accountId' => 1])); @@ -56,4 +53,12 @@ class AccountOwnerTest extends TestCase { $this->assertFalse($rule->execute('token', $item, ['accountId' => 1, 'optionalRules' => true])); } + /** + * @expectedException \InvalidArgumentException + */ + public function testExecuteWithoutAccountId() { + $rule = new AccountOwner(); + $this->assertFalse($rule->execute('token', new Item(), [])); + } + } diff --git a/common/tests/unit/rbac/rules/OauthClientOwnerTest.php b/api/tests/unit/rbac/rules/OauthClientOwnerTest.php similarity index 55% rename from common/tests/unit/rbac/rules/OauthClientOwnerTest.php rename to api/tests/unit/rbac/rules/OauthClientOwnerTest.php index 31520fb..c699415 100644 --- a/common/tests/unit/rbac/rules/OauthClientOwnerTest.php +++ b/api/tests/unit/rbac/rules/OauthClientOwnerTest.php @@ -1,13 +1,12 @@ assertTrue($rule->execute('some token', $item, ['clientId' => 'not exists client id'])); + + // Client exists, but identity is null + $this->assertFalse($rule->execute('some token', $item, ['clientId' => 'ely'])); + + // Client exists, identity presented, but have no account + /** @var IdentityInterface|\Mockery\MockInterface $identity */ + $identity = mock(IdentityInterface::class); + $identity->shouldReceive('getAccount')->andReturn(null); + Yii::$app->user->setIdentity($identity); + + $this->assertFalse($rule->execute('some token', $item, ['clientId' => 'ely'])); + + // Identity has an account $account = new Account(); $account->id = 1; $account->status = Account::STATUS_ACTIVE; @@ -34,15 +48,8 @@ class OauthClientOwnerTest extends TestCase { /** @var IdentityInterface|\Mockery\MockInterface $identity */ $identity = mock(IdentityInterface::class); $identity->shouldReceive('getAccount')->andReturn($account); + Yii::$app->user->setIdentity($identity); - /** @var Component|\Mockery\MockInterface $component */ - $component = mock(Component::class . '[findIdentityByAccessToken]'); - $component->makePartial(); - $component->shouldReceive('findIdentityByAccessToken')->withArgs(['token'])->andReturn($identity); - - Yii::$app->set('user', $component); - - $this->assertFalse($rule->execute('token', $item, [])); $this->assertTrue($rule->execute('token', $item, ['clientId' => 'admin-oauth-client'])); $this->assertTrue($rule->execute('token', $item, ['clientId' => 'not-exists-client'])); $account->id = 2; @@ -52,4 +59,12 @@ class OauthClientOwnerTest extends TestCase { $this->assertFalse($rule->execute('token', $item, ['accountId' => 1])); } + /** + * @expectedException \InvalidArgumentException + */ + public function testExecuteWithoutClientId() { + $rule = new OauthClientOwner(); + $this->assertFalse($rule->execute('token', new Item(), [])); + } + } diff --git a/api/tests/unit/validators/PasswordRequiredValidatorTest.php b/api/tests/unit/validators/PasswordRequiredValidatorTest.php index f60aed6..1c26e1d 100644 --- a/api/tests/unit/validators/PasswordRequiredValidatorTest.php +++ b/api/tests/unit/validators/PasswordRequiredValidatorTest.php @@ -1,11 +1,11 @@ api\components\OAuth2\Component::class, ], 'authManager' => [ - 'class' => common\rbac\Manager::class, + 'class' => \api\rbac\Manager::class, 'itemFile' => '@common/rbac/.generated/items.php', 'ruleFile' => '@common/rbac/.generated/rules.php', ], diff --git a/common/rbac/Manager.php b/common/rbac/Manager.php deleted file mode 100644 index 0565240..0000000 --- a/common/rbac/Manager.php +++ /dev/null @@ -1,34 +0,0 @@ -user->findIdentityByAccessToken($accessToken); - if ($identity === null) { - return []; - } - - /** @noinspection NullPointerExceptionInspection */ - $permissions = $identity->getAssignedPermissions(); - if (empty($permissions)) { - return []; - } - - return array_flip($permissions); - } - -} diff --git a/composer.json b/composer.json index 9a0d0e1..d58d470 100644 --- a/composer.json +++ b/composer.json @@ -16,12 +16,12 @@ "domnikl/statsd": "^2.6", "ely/mojang-api": "^0.2.0", "ely/yii2-tempmail-validator": "^2.0", - "emarref/jwt": "~1.0.3", "goaop/framework": "^2.2.0", "guzzlehttp/guzzle": "^6.0.0", "lcobucci/jwt": "^3.3", "league/oauth2-server": "^4.1", "mito/yii2-sentry": "^1.0", + "nesbot/carbon": "^2.22", "paragonie/constant_time_encoding": "^2.0", "ramsey/uuid": "^3.5", "spomky-labs/otphp": "^9.0.2", diff --git a/composer.lock b/composer.lock index 6271d21..0b2b56d 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "2dfa204a51a82cd7c7d6a5b7d1ccbc0c", + "content-hash": "2c49fce9e25e3bc27dc3ae43ac0c079b", "packages": [ { "name": "bacon/bacon-qr-code", @@ -701,48 +701,6 @@ ], "time": "2017-09-30T22:51:45+00:00" }, - { - "name": "emarref/jwt", - "version": "1.0.3", - "source": { - "type": "git", - "url": "https://github.com/emarref/jwt.git", - "reference": "79f563750ff90dabd4fa677c4b4e5ec9ed52d9b4" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/emarref/jwt/zipball/79f563750ff90dabd4fa677c4b4e5ec9ed52d9b4", - "reference": "79f563750ff90dabd4fa677c4b4e5ec9ed52d9b4", - "shasum": "" - }, - "require": { - "php": ">=5.4" - }, - "require-dev": { - "phpunit/phpunit": "*" - }, - "suggest": { - "ext-openssl": "Enables more token encryption options" - }, - "type": "library", - "autoload": { - "psr-4": { - "Emarref\\Jwt\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Malcolm Fell", - "email": "emarref@gmail.com" - } - ], - "description": "A JWT implementation", - "time": "2016-09-05T20:33:06+00:00" - }, { "name": "ezyang/htmlpurifier", "version": "v4.10.0", @@ -1369,6 +1327,73 @@ ], "time": "2017-11-28T16:52:35+00:00" }, + { + "name": "nesbot/carbon", + "version": "2.22.0", + "source": { + "type": "git", + "url": "https://github.com/briannesbitt/Carbon.git", + "reference": "1a0e48b5f656065ba3c265b058b25d36c2162a5e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/briannesbitt/Carbon/zipball/1a0e48b5f656065ba3c265b058b25d36c2162a5e", + "reference": "1a0e48b5f656065ba3c265b058b25d36c2162a5e", + "shasum": "" + }, + "require": { + "ext-json": "*", + "php": "^7.1.8 || ^8.0", + "symfony/translation": "^3.4 || ^4.0" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^2.14 || ^3.0", + "kylekatarnls/multi-tester": "^1.1", + "phpmd/phpmd": "dev-php-7.1-compatibility", + "phpstan/phpstan": "^0.11", + "phpunit/phpunit": "^7.5 || ^8.0", + "squizlabs/php_codesniffer": "^3.4" + }, + "bin": [ + "bin/carbon" + ], + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Carbon\\Laravel\\ServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "Carbon\\": "src/Carbon/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Brian Nesbitt", + "email": "brian@nesbot.com", + "homepage": "http://nesbot.com" + }, + { + "name": "kylekatarnls", + "homepage": "http://github.com/kylekatarnls" + } + ], + "description": "A simple API extension for DateTime.", + "homepage": "http://carbon.nesbot.com", + "keywords": [ + "date", + "datetime", + "time" + ], + "time": "2019-07-28T09:02:12+00:00" + }, { "name": "nikic/php-parser", "version": "v4.2.1", @@ -1990,6 +2015,139 @@ "homepage": "https://symfony.com", "time": "2019-04-10T16:20:36+00:00" }, + { + "name": "symfony/translation", + "version": "v4.3.3", + "source": { + "type": "git", + "url": "https://github.com/symfony/translation.git", + "reference": "4e3e39cc485304f807622bdc64938e4633396406" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/translation/zipball/4e3e39cc485304f807622bdc64938e4633396406", + "reference": "4e3e39cc485304f807622bdc64938e4633396406", + "shasum": "" + }, + "require": { + "php": "^7.1.3", + "symfony/polyfill-mbstring": "~1.0", + "symfony/translation-contracts": "^1.1.2" + }, + "conflict": { + "symfony/config": "<3.4", + "symfony/dependency-injection": "<3.4", + "symfony/yaml": "<3.4" + }, + "provide": { + "symfony/translation-implementation": "1.0" + }, + "require-dev": { + "psr/log": "~1.0", + "symfony/config": "~3.4|~4.0", + "symfony/console": "~3.4|~4.0", + "symfony/dependency-injection": "~3.4|~4.0", + "symfony/finder": "~2.8|~3.0|~4.0", + "symfony/http-kernel": "~3.4|~4.0", + "symfony/intl": "~3.4|~4.0", + "symfony/service-contracts": "^1.1.2", + "symfony/var-dumper": "~3.4|~4.0", + "symfony/yaml": "~3.4|~4.0" + }, + "suggest": { + "psr/log-implementation": "To use logging capability in translator", + "symfony/config": "", + "symfony/yaml": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.3-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Translation\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Translation Component", + "homepage": "https://symfony.com", + "time": "2019-07-18T10:34:59+00:00" + }, + { + "name": "symfony/translation-contracts", + "version": "v1.1.5", + "source": { + "type": "git", + "url": "https://github.com/symfony/translation-contracts.git", + "reference": "cb4b18ad7b92a26e83b65dde940fab78339e6f3c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/cb4b18ad7b92a26e83b65dde940fab78339e6f3c", + "reference": "cb4b18ad7b92a26e83b65dde940fab78339e6f3c", + "shasum": "" + }, + "require": { + "php": "^7.1.3" + }, + "suggest": { + "symfony/translation-implementation": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\Translation\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to translation", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "time": "2019-06-13T11:15:36+00:00" + }, { "name": "webmozart/assert", "version": "1.4.0", diff --git a/console/codeception.dist.yml b/console/codeception.dist.yml index 673cb42..9aed054 100644 --- a/console/codeception.dist.yml +++ b/console/codeception.dist.yml @@ -18,6 +18,7 @@ coverage: - config/* - runtime/* - migrations/* + - tests/* - views/* - codeception.dist.yml - codeception.yml diff --git a/console/controllers/RbacController.php b/console/controllers/RbacController.php index 66f9a7c..2d0b8a0 100644 --- a/console/controllers/RbacController.php +++ b/console/controllers/RbacController.php @@ -1,13 +1,14 @@ getAuthManager(); $role = $authManager->createRole($name); - if (!$authManager->add($role)) { - throw new ErrorException('Cannot save role in authManager'); - } + Assert::true($authManager->add($role), 'Cannot save role in authManager'); return $role; } @@ -96,9 +95,7 @@ class RbacController extends Controller { $permission = $authManager->createPermission($name); if ($ruleClassName !== null) { $rule = new $ruleClassName(); - if (!$rule instanceof Rule) { - throw new InvalidArgumentException('ruleClassName must be rule class name'); - } + Assert::isInstanceOf($rule, Rule::class, 'ruleClassName must be rule class name'); $ruleFromAuthManager = $authManager->getRule($rule->name); if ($ruleFromAuthManager === null) { @@ -108,9 +105,7 @@ class RbacController extends Controller { $permission->ruleName = $rule->name; } - if (!$authManager->add($permission)) { - throw new ErrorException('Cannot save permission in authManager'); - } + Assert::true($authManager->add($permission), 'Cannot save permission in authManager'); return $permission; } From 7b11366a5acc424ed957fcc44b06316b20ae17e0 Mon Sep 17 00:00:00 2001 From: ErickSkrauch Date: Fri, 2 Aug 2019 03:36:24 +0300 Subject: [PATCH 4/7] Fix rbac generator --- common/config/config.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/common/config/config.php b/common/config/config.php index 6313da6..bc10472 100644 --- a/common/config/config.php +++ b/common/config/config.php @@ -99,8 +99,8 @@ return [ ], 'authManager' => [ 'class' => \api\rbac\Manager::class, - 'itemFile' => '@common/rbac/.generated/items.php', - 'ruleFile' => '@common/rbac/.generated/rules.php', + 'itemFile' => '@api/rbac/.generated/items.php', + 'ruleFile' => '@api/rbac/.generated/rules.php', ], 'statsd' => [ 'class' => common\components\StatsD::class, From d9f2b1a8c90188d4e6b7b13a51cc0c86e4c02f21 Mon Sep 17 00:00:00 2001 From: ErickSkrauch Date: Fri, 2 Aug 2019 15:57:17 +0300 Subject: [PATCH 5/7] Upgrade PHPUnit to 8. Replace codeception/base with codeception/codeception due to release bug in the base version. --- api/tests/unit/TestCase.php | 2 +- api/tests/unit/models/FeedbackFormTest.php | 7 +- .../authentication/ForgotPasswordFormTest.php | 4 +- .../models/authentication/LoginFormTest.php | 4 +- .../authentication/RegistrationFormTest.php | 2 +- .../RepeatAccountActivationFormTest.php | 4 +- .../models/AuthenticationFormTest.php | 34 +- .../validators/RequiredValidatorTest.php | 8 +- .../models/OauthClientFormFactoryTest.php | 8 +- .../session/filters/RateLimiterTest.php | 6 +- .../unit/rbac/rules/AccountOwnerTest.php | 6 +- .../unit/rbac/rules/OauthClientOwnerTest.php | 6 +- common/tests/unit/TestCase.php | 2 +- .../EmailsRenderer/ComponentTest.php | 2 +- .../tasks/CreateWebHooksDeliveriesTest.php | 7 +- .../tests/unit/tasks/DeliveryWebHookTest.php | 5 +- .../unit/tasks/PullMojangUsernameTest.php | 4 +- .../SendCurrentEmailConfirmationTest.php | 2 +- .../tasks/SendNewEmailConfirmationTest.php | 2 +- composer.json | 5 +- composer.lock | 621 +++++++++++++----- 21 files changed, 522 insertions(+), 219 deletions(-) diff --git a/api/tests/unit/TestCase.php b/api/tests/unit/TestCase.php index 60e2a4d..c2e62f1 100644 --- a/api/tests/unit/TestCase.php +++ b/api/tests/unit/TestCase.php @@ -13,7 +13,7 @@ class TestCase extends Unit { */ protected $tester; - protected function tearDown() { + protected function tearDown(): void { parent::tearDown(); Mockery::close(); } diff --git a/api/tests/unit/models/FeedbackFormTest.php b/api/tests/unit/models/FeedbackFormTest.php index b3e2cfa..b9cba73 100644 --- a/api/tests/unit/models/FeedbackFormTest.php +++ b/api/tests/unit/models/FeedbackFormTest.php @@ -30,20 +30,19 @@ class FeedbackFormTest extends TestCase { ->getMock(); $model - ->expects($this->any()) ->method('getAccount') - ->will($this->returnValue(new Account([ + ->willReturn(new Account([ 'id' => '123', 'username' => 'Erick', 'email' => 'find-this@email.net', 'created_at' => time() - 86400, - ]))); + ])); $this->assertTrue($model->sendMessage()); /** @var Message $message */ $message = $this->tester->grabLastSentEmail(); $this->assertInstanceOf(Message::class, $message); $data = (string)$message; - $this->assertContains('find-this@email.net', $data); + $this->assertStringContainsString('find-this@email.net', $data); } } diff --git a/api/tests/unit/models/authentication/ForgotPasswordFormTest.php b/api/tests/unit/models/authentication/ForgotPasswordFormTest.php index d8ace21..3ee8114 100644 --- a/api/tests/unit/models/authentication/ForgotPasswordFormTest.php +++ b/api/tests/unit/models/authentication/ForgotPasswordFormTest.php @@ -1,4 +1,6 @@ set(ReCaptchaValidator::class, new class(mock(ClientInterface::class)) extends ReCaptchaValidator { public function validateValue($value) { diff --git a/api/tests/unit/models/authentication/LoginFormTest.php b/api/tests/unit/models/authentication/LoginFormTest.php index 35e7615..384e63a 100644 --- a/api/tests/unit/models/authentication/LoginFormTest.php +++ b/api/tests/unit/models/authentication/LoginFormTest.php @@ -15,13 +15,13 @@ class LoginFormTest extends TestCase { private $originalRemoteAddr; - protected function setUp() { + protected function setUp(): void { $this->originalRemoteAddr = $_SERVER['REMOTE_ADDR'] ?? null; $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; parent::setUp(); } - protected function tearDown() { + protected function tearDown(): void { parent::tearDown(); $_SERVER['REMOTE_ADDR'] = $this->originalRemoteAddr; } diff --git a/api/tests/unit/models/authentication/RegistrationFormTest.php b/api/tests/unit/models/authentication/RegistrationFormTest.php index cc61563..eb4e472 100644 --- a/api/tests/unit/models/authentication/RegistrationFormTest.php +++ b/api/tests/unit/models/authentication/RegistrationFormTest.php @@ -22,7 +22,7 @@ use const common\LATEST_RULES_VERSION; class RegistrationFormTest extends TestCase { - protected function setUp() { + protected function setUp(): void { parent::setUp(); $this->mockRequest(); Yii::$container->set(ReCaptchaValidator::class, new class(mock(ClientInterface::class)) extends ReCaptchaValidator { diff --git a/api/tests/unit/models/authentication/RepeatAccountActivationFormTest.php b/api/tests/unit/models/authentication/RepeatAccountActivationFormTest.php index e0cdfcd..9e9895f 100644 --- a/api/tests/unit/models/authentication/RepeatAccountActivationFormTest.php +++ b/api/tests/unit/models/authentication/RepeatAccountActivationFormTest.php @@ -1,4 +1,6 @@ set(ReCaptchaValidator::class, new class(mock(ClientInterface::class)) extends ReCaptchaValidator { public function validateValue($value) { diff --git a/api/tests/unit/modules/authserver/models/AuthenticationFormTest.php b/api/tests/unit/modules/authserver/models/AuthenticationFormTest.php index 0cb9288..35e2db2 100644 --- a/api/tests/unit/modules/authserver/models/AuthenticationFormTest.php +++ b/api/tests/unit/modules/authserver/models/AuthenticationFormTest.php @@ -1,7 +1,10 @@ expectException(ForbiddenOperationException::class); + $this->expectExceptionMessage('Invalid credentials. Invalid nickname or password.'); + $authForm = $this->createAuthForm(); $authForm->username = 'wrong-username'; @@ -36,11 +38,10 @@ class AuthenticationFormTest extends TestCase { $authForm->authenticate(); } - /** - * @expectedException \api\modules\authserver\exceptions\ForbiddenOperationException - * @expectedExceptionMessage Invalid credentials. Invalid email or password. - */ public function testAuthenticateByWrongEmailPass() { + $this->expectException(ForbiddenOperationException::class); + $this->expectExceptionMessage('Invalid credentials. Invalid email or password.'); + $authForm = $this->createAuthForm(); $authForm->username = 'wrong-email@ely.by'; @@ -50,11 +51,10 @@ class AuthenticationFormTest extends TestCase { $authForm->authenticate(); } - /** - * @expectedException \api\modules\authserver\exceptions\ForbiddenOperationException - * @expectedExceptionMessage This account has been suspended. - */ public function testAuthenticateByValidCredentialsIntoBlockedAccount() { + $this->expectException(ForbiddenOperationException::class); + $this->expectExceptionMessage('This account has been suspended.'); + $authForm = $this->createAuthForm(Account::STATUS_BANNED); $authForm->username = 'dummy'; @@ -71,7 +71,7 @@ class AuthenticationFormTest extends TestCase { $minecraftAccessKey->access_token = Uuid::uuid4(); $authForm->expects($this->once()) ->method('createMinecraftAccessToken') - ->will($this->returnValue($minecraftAccessKey)); + ->willReturn($minecraftAccessKey); $authForm->username = 'dummy'; $authForm->password = 'password_0'; @@ -122,18 +122,18 @@ class AuthenticationFormTest extends TestCase { $account->status = $status; $account->setPassword('password_0'); - $loginForm->expects($this->any()) + $loginForm ->method('getAccount') - ->will($this->returnValue($account)); + ->willReturn($account); /** @var AuthenticationForm|\PHPUnit\Framework\MockObject\MockObject $authForm */ $authForm = $this->getMockBuilder(AuthenticationForm::class) ->setMethods(['createLoginForm', 'createMinecraftAccessToken']) ->getMock(); - $authForm->expects($this->any()) + $authForm ->method('createLoginForm') - ->will($this->returnValue($loginForm)); + ->willReturn($loginForm); return $authForm; } diff --git a/api/tests/unit/modules/authserver/validators/RequiredValidatorTest.php b/api/tests/unit/modules/authserver/validators/RequiredValidatorTest.php index e31704b..254545f 100644 --- a/api/tests/unit/modules/authserver/validators/RequiredValidatorTest.php +++ b/api/tests/unit/modules/authserver/validators/RequiredValidatorTest.php @@ -1,6 +1,9 @@ assertNull($this->callProtected($validator, 'validateValue', 'dummy')); } - /** - * @expectedException \api\modules\authserver\exceptions\IllegalArgumentException - */ public function testValidateValueEmpty() { + $this->expectException(IllegalArgumentException::class); + $validator = new RequiredValidator(); $this->assertNull($this->callProtected($validator, 'validateValue', '')); } diff --git a/api/tests/unit/modules/oauth/models/OauthClientFormFactoryTest.php b/api/tests/unit/modules/oauth/models/OauthClientFormFactoryTest.php index 2b26b2f..60ac323 100644 --- a/api/tests/unit/modules/oauth/models/OauthClientFormFactoryTest.php +++ b/api/tests/unit/modules/oauth/models/OauthClientFormFactoryTest.php @@ -1,6 +1,9 @@ assertSame('localhost:12345', $requestForm->minecraftServerIp); } - /** - * @expectedException \api\modules\oauth\exceptions\UnsupportedOauthClientType - */ public function testCreateUnknownType() { + $this->expectException(UnsupportedOauthClientType::class); + $client = new OauthClient(); $client->type = 'unknown-type'; OauthClientFormFactory::create($client); diff --git a/api/tests/unit/modules/session/filters/RateLimiterTest.php b/api/tests/unit/modules/session/filters/RateLimiterTest.php index 2860059..94ff1de 100644 --- a/api/tests/unit/modules/session/filters/RateLimiterTest.php +++ b/api/tests/unit/modules/session/filters/RateLimiterTest.php @@ -10,6 +10,7 @@ use Faker\Provider\Internet; use Yii; use yii\redis\Connection; use yii\web\Request; +use yii\web\TooManyRequestsHttpException; class RateLimiterTest extends TestCase { @@ -63,10 +64,9 @@ class RateLimiterTest extends TestCase { $filter->checkRateLimit(null, $request, null, null); } - /** - * @expectedException \yii\web\TooManyRequestsHttpException - */ public function testCheckRateLimiter() { + $this->expectException(TooManyRequestsHttpException::class); + /** @var Connection|\PHPUnit\Framework\MockObject\MockObject $redis */ $redis = $this->getMockBuilder(Connection::class) ->setMethods(['executeCommand']) diff --git a/api/tests/unit/rbac/rules/AccountOwnerTest.php b/api/tests/unit/rbac/rules/AccountOwnerTest.php index 065c9bb..679d2ee 100644 --- a/api/tests/unit/rbac/rules/AccountOwnerTest.php +++ b/api/tests/unit/rbac/rules/AccountOwnerTest.php @@ -7,6 +7,7 @@ use api\components\User\IdentityInterface; use api\rbac\rules\AccountOwner; use common\models\Account; use common\tests\unit\TestCase; +use InvalidArgumentException; use Yii; use yii\rbac\Item; use const common\LATEST_RULES_VERSION; @@ -53,10 +54,9 @@ class AccountOwnerTest extends TestCase { $this->assertFalse($rule->execute('token', $item, ['accountId' => 1, 'optionalRules' => true])); } - /** - * @expectedException \InvalidArgumentException - */ public function testExecuteWithoutAccountId() { + $this->expectException(InvalidArgumentException::class); + $rule = new AccountOwner(); $this->assertFalse($rule->execute('token', new Item(), [])); } diff --git a/api/tests/unit/rbac/rules/OauthClientOwnerTest.php b/api/tests/unit/rbac/rules/OauthClientOwnerTest.php index c699415..b828a0c 100644 --- a/api/tests/unit/rbac/rules/OauthClientOwnerTest.php +++ b/api/tests/unit/rbac/rules/OauthClientOwnerTest.php @@ -9,6 +9,7 @@ use api\rbac\rules\OauthClientOwner; use common\models\Account; use common\tests\fixtures\OauthClientFixture; use common\tests\unit\TestCase; +use InvalidArgumentException; use Yii; use yii\rbac\Item; use const common\LATEST_RULES_VERSION; @@ -59,10 +60,9 @@ class OauthClientOwnerTest extends TestCase { $this->assertFalse($rule->execute('token', $item, ['accountId' => 1])); } - /** - * @expectedException \InvalidArgumentException - */ public function testExecuteWithoutClientId() { + $this->expectException(InvalidArgumentException::class); + $rule = new OauthClientOwner(); $this->assertFalse($rule->execute('token', new Item(), [])); } diff --git a/common/tests/unit/TestCase.php b/common/tests/unit/TestCase.php index 6e5d085..7c46c95 100644 --- a/common/tests/unit/TestCase.php +++ b/common/tests/unit/TestCase.php @@ -13,7 +13,7 @@ class TestCase extends Unit { */ protected $tester; - protected function tearDown() { + protected function tearDown(): void { parent::tearDown(); Mockery::close(); } diff --git a/common/tests/unit/components/EmailsRenderer/ComponentTest.php b/common/tests/unit/components/EmailsRenderer/ComponentTest.php index ea95708..e57203d 100644 --- a/common/tests/unit/components/EmailsRenderer/ComponentTest.php +++ b/common/tests/unit/components/EmailsRenderer/ComponentTest.php @@ -20,7 +20,7 @@ class ComponentTest extends TestCase { */ private $component; - protected function setUp() { + protected function setUp(): void { parent::setUp(); $this->api = $this->createMock(Api::class); diff --git a/common/tests/unit/tasks/CreateWebHooksDeliveriesTest.php b/common/tests/unit/tasks/CreateWebHooksDeliveriesTest.php index f67a186..5503af3 100644 --- a/common/tests/unit/tasks/CreateWebHooksDeliveriesTest.php +++ b/common/tests/unit/tasks/CreateWebHooksDeliveriesTest.php @@ -38,9 +38,8 @@ class CreateWebHooksDeliveriesTest extends TestCase { 'status' => 0, ]; $result = CreateWebHooksDeliveries::createAccountEdit($account, $changedAttributes); - $this->assertInstanceOf(CreateWebHooksDeliveries::class, $result); $this->assertSame('account.edit', $result->type); - $this->assertArraySubset([ + $this->assertEmpty(array_diff_assoc([ 'id' => 123, 'uuid' => 'afc8dc7a-4bbf-4d3a-8699-68890088cf84', 'username' => 'mock-username', @@ -48,8 +47,8 @@ class CreateWebHooksDeliveriesTest extends TestCase { 'lang' => 'en', 'isActive' => true, 'registered' => '2018-07-08T00:13:34+00:00', - 'changedAttributes' => $changedAttributes, - ], $result->payloads); + ], $result->payloads)); + $this->assertSame($changedAttributes, $result->payloads['changedAttributes']); } public function testExecute() { diff --git a/common/tests/unit/tasks/DeliveryWebHookTest.php b/common/tests/unit/tasks/DeliveryWebHookTest.php index e2f980e..586212b 100644 --- a/common/tests/unit/tasks/DeliveryWebHookTest.php +++ b/common/tests/unit/tasks/DeliveryWebHookTest.php @@ -90,10 +90,9 @@ class DeliveryWebHookTest extends TestCase { $task->execute(mock(Queue::class)); } - /** - * @expectedException \GuzzleHttp\Exception\ServerException - */ public function testExecuteUnhandledException() { + $this->expectException(ServerException::class); + $this->response = new Response(502); $task = $this->createMockedTask(); $task->type = 'account.edit'; diff --git a/common/tests/unit/tasks/PullMojangUsernameTest.php b/common/tests/unit/tasks/PullMojangUsernameTest.php index 4435f39..3e0caf5 100644 --- a/common/tests/unit/tasks/PullMojangUsernameTest.php +++ b/common/tests/unit/tasks/PullMojangUsernameTest.php @@ -50,7 +50,7 @@ class PullMojangUsernameTest extends TestCase { public function testExecuteUsernameExists() { $this->mockedMethod->willReturn(new ProfileInfo('069a79f444e94726a5befca90e38aaf5', 'Notch')); - /** @var \common\models\MojangUsername $mojangUsernameFixture */ + /** @var MojangUsername $mojangUsernameFixture */ $mojangUsernameFixture = $this->tester->grabFixture('mojangUsernames', 'Notch'); $task = new PullMojangUsername(); $task->username = 'Notch'; @@ -89,7 +89,7 @@ class PullMojangUsernameTest extends TestCase { } public function testExecuteRemoveIfExistsNoMore() { - $this->mockedMethod->willThrowException(new NoContentException(new Request('', ''), new Response())); + $this->mockedMethod->willThrowException(new NoContentException(new Request('GET', ''), new Response())); $username = $this->tester->grabFixture('mojangUsernames', 'not-exists')['username']; $task = new PullMojangUsername(); diff --git a/common/tests/unit/tasks/SendCurrentEmailConfirmationTest.php b/common/tests/unit/tasks/SendCurrentEmailConfirmationTest.php index 768001b..6301d88 100644 --- a/common/tests/unit/tasks/SendCurrentEmailConfirmationTest.php +++ b/common/tests/unit/tasks/SendCurrentEmailConfirmationTest.php @@ -41,7 +41,7 @@ class SendCurrentEmailConfirmationTest extends TestCase { $this->assertSame(['mock@ely.by' => 'mock-username'], $email->getTo()); $this->assertSame('Ely.by Account change E-mail confirmation', $email->getSubject()); $children = $email->getSwiftMessage()->getChildren()[0]; - $this->assertContains('GFEDCBA', $children->getBody()); + $this->assertStringContainsString('GFEDCBA', $children->getBody()); } } diff --git a/common/tests/unit/tasks/SendNewEmailConfirmationTest.php b/common/tests/unit/tasks/SendNewEmailConfirmationTest.php index d6ec76d..33b2444 100644 --- a/common/tests/unit/tasks/SendNewEmailConfirmationTest.php +++ b/common/tests/unit/tasks/SendNewEmailConfirmationTest.php @@ -41,7 +41,7 @@ class SendNewEmailConfirmationTest extends TestCase { $this->assertSame(['mock@ely.by' => 'mock-username'], $email->getTo()); $this->assertSame('Ely.by Account new E-mail confirmation', $email->getSubject()); $children = $email->getSwiftMessage()->getChildren()[0]; - $this->assertContains('GFEDCBA', $children->getBody()); + $this->assertStringContainsString('GFEDCBA', $children->getBody()); } } diff --git a/composer.json b/composer.json index d58d470..6f06d85 100644 --- a/composer.json +++ b/composer.json @@ -32,7 +32,7 @@ "yiisoft/yii2-swiftmailer": "~2.1.0" }, "require-dev": { - "codeception/base": "^3.0.0", + "codeception/codeception": "^3.0", "codeception/specify": "^1.0.0", "ely/php-code-style": "^0.3.0", "flow/jsonpath": "^0.4.0", @@ -47,7 +47,8 @@ "symfony/polyfill-ctype": "*", "symfony/polyfill-mbstring": "*", "symfony/polyfill-php70": "*", - "symfony/polyfill-php72": "*" + "symfony/polyfill-php72": "*", + "symfony/polyfill-php73": "*" }, "repositories": [ { diff --git a/composer.lock b/composer.lock index 0b2b56d..c7464af 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "2c49fce9e25e3bc27dc3ae43ac0c079b", + "content-hash": "35095ab389bcc73cacbafceffa74fb71", "packages": [ { "name": "bacon/bacon-qr-code", @@ -984,33 +984,37 @@ }, { "name": "guzzlehttp/psr7", - "version": "1.5.2", + "version": "1.6.1", "source": { "type": "git", "url": "https://github.com/guzzle/psr7.git", - "reference": "9f83dded91781a01c63574e387eaa769be769115" + "reference": "239400de7a173fe9901b9ac7c06497751f00727a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/psr7/zipball/9f83dded91781a01c63574e387eaa769be769115", - "reference": "9f83dded91781a01c63574e387eaa769be769115", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/239400de7a173fe9901b9ac7c06497751f00727a", + "reference": "239400de7a173fe9901b9ac7c06497751f00727a", "shasum": "" }, "require": { "php": ">=5.4.0", "psr/http-message": "~1.0", - "ralouphie/getallheaders": "^2.0.5" + "ralouphie/getallheaders": "^2.0.5 || ^3.0.0" }, "provide": { "psr/http-message-implementation": "1.0" }, "require-dev": { + "ext-zlib": "*", "phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.8" }, + "suggest": { + "zendframework/zend-httphandlerrunner": "Emit PSR-7 responses" + }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.5-dev" + "dev-master": "1.6-dev" } }, "autoload": { @@ -1047,7 +1051,7 @@ "uri", "url" ], - "time": "2018-12-04T20:46:45+00:00" + "time": "2019-07-01T23:21:34+00:00" }, { "name": "jakubledl/dissect", @@ -1559,24 +1563,24 @@ }, { "name": "ralouphie/getallheaders", - "version": "2.0.5", + "version": "3.0.3", "source": { "type": "git", "url": "https://github.com/ralouphie/getallheaders.git", - "reference": "5601c8a83fbba7ef674a7369456d12f1e0d0eafa" + "reference": "120b605dfeb996808c31b6477290a714d356e822" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/5601c8a83fbba7ef674a7369456d12f1e0d0eafa", - "reference": "5601c8a83fbba7ef674a7369456d12f1e0d0eafa", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", "shasum": "" }, "require": { - "php": ">=5.3" + "php": ">=5.6" }, "require-dev": { - "phpunit/phpunit": "~3.7.0", - "satooshi/php-coveralls": ">=1.0" + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" }, "type": "library", "autoload": { @@ -1595,7 +1599,7 @@ } ], "description": "A polyfill for getallheaders.", - "time": "2016-02-11T07:05:27+00:00" + "time": "2019-03-08T08:55:37+00:00" }, { "name": "ramsey/uuid", @@ -1865,16 +1869,16 @@ }, { "name": "symfony/finder", - "version": "v4.2.8", + "version": "v4.3.3", "source": { "type": "git", "url": "https://github.com/symfony/finder.git", - "reference": "e45135658bd6c14b61850bf131c4f09a55133f69" + "reference": "9638d41e3729459860bb96f6247ccb61faaa45f2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/finder/zipball/e45135658bd6c14b61850bf131c4f09a55133f69", - "reference": "e45135658bd6c14b61850bf131c4f09a55133f69", + "url": "https://api.github.com/repos/symfony/finder/zipball/9638d41e3729459860bb96f6247ccb61faaa45f2", + "reference": "9638d41e3729459860bb96f6247ccb61faaa45f2", "shasum": "" }, "require": { @@ -1883,7 +1887,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.2-dev" + "dev-master": "4.3-dev" } }, "autoload": { @@ -1910,7 +1914,7 @@ ], "description": "Symfony Finder Component", "homepage": "https://symfony.com", - "time": "2019-04-06T13:51:08+00:00" + "time": "2019-06-28T13:16:30+00:00" }, { "name": "symfony/http-foundation", @@ -2603,17 +2607,17 @@ "time": "2019-01-16T14:22:17+00:00" }, { - "name": "codeception/base", - "version": "3.0.0", + "name": "codeception/codeception", + "version": "3.0.3", "source": { "type": "git", - "url": "https://github.com/Codeception/base.git", - "reference": "86f10d5dcb05895e76711e6d25e5eb8ead354a09" + "url": "https://github.com/Codeception/Codeception.git", + "reference": "feb566a9dc26993611602011ae3834d8e3c1dd7f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Codeception/base/zipball/86f10d5dcb05895e76711e6d25e5eb8ead354a09", - "reference": "86f10d5dcb05895e76711e6d25e5eb8ead354a09", + "url": "https://api.github.com/repos/Codeception/Codeception/zipball/feb566a9dc26993611602011ae3834d8e3c1dd7f", + "reference": "feb566a9dc26993611602011ae3834d8e3c1dd7f", "shasum": "" }, "require": { @@ -2623,6 +2627,8 @@ "ext-curl": "*", "ext-json": "*", "ext-mbstring": "*", + "facebook/webdriver": "^1.6.0", + "guzzlehttp/guzzle": "^6.3.0", "guzzlehttp/psr7": "~1.4", "hoa/console": "~3.0", "php": ">=5.6.0 <8.0", @@ -2636,6 +2642,8 @@ }, "require-dev": { "codeception/specify": "~0.3", + "doctrine/annotations": "^1", + "doctrine/orm": "^2", "flow/jsonpath": "~0.2", "monolog/monolog": "~1.8", "pda/pheanstalk": "~3.0", @@ -2690,25 +2698,26 @@ "functional testing", "unit testing" ], - "time": "2019-04-24T12:13:51+00:00" + "time": "2019-07-18T16:21:08+00:00" }, { "name": "codeception/phpunit-wrapper", - "version": "7.7.1", + "version": "8.0.4", "source": { "type": "git", "url": "https://github.com/Codeception/phpunit-wrapper.git", - "reference": "ab04a956264291505ea84998f43cf91639b4575d" + "reference": "7090736f36b4398cae6ef838b9a2bdfe8d8d104b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Codeception/phpunit-wrapper/zipball/ab04a956264291505ea84998f43cf91639b4575d", - "reference": "ab04a956264291505ea84998f43cf91639b4575d", + "url": "https://api.github.com/repos/Codeception/phpunit-wrapper/zipball/7090736f36b4398cae6ef838b9a2bdfe8d8d104b", + "reference": "7090736f36b4398cae6ef838b9a2bdfe8d8d104b", "shasum": "" }, "require": { - "phpunit/php-code-coverage": "^6.0", - "phpunit/phpunit": "7.5.*", + "php": ">=7.2", + "phpunit/php-code-coverage": "^7.0", + "phpunit/phpunit": "^8.0", "sebastian/comparator": "^3.0", "sebastian/diff": "^3.0" }, @@ -2733,26 +2742,26 @@ } ], "description": "PHPUnit classes used by Codeception", - "time": "2019-02-26T20:35:32+00:00" + "time": "2019-02-27T12:58:57+00:00" }, { "name": "codeception/specify", - "version": "1.1", + "version": "1.2.0", "source": { "type": "git", "url": "https://github.com/Codeception/Specify.git", - "reference": "504ac7a882e6f7226b0cff44c72a6c0bbd0bad95" + "reference": "e3fefa22f2304170024b9242b2bd8b01cf5a2ac0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Codeception/Specify/zipball/504ac7a882e6f7226b0cff44c72a6c0bbd0bad95", - "reference": "504ac7a882e6f7226b0cff44c72a6c0bbd0bad95", + "url": "https://api.github.com/repos/Codeception/Specify/zipball/e3fefa22f2304170024b9242b2bd8b01cf5a2ac0", + "reference": "e3fefa22f2304170024b9242b2bd8b01cf5a2ac0", "shasum": "" }, "require": { "myclabs/deep-copy": "~1.1", "php": ">=7.1.0", - "phpunit/phpunit": "^7.0" + "phpunit/phpunit": ">=7.0 <9.0" }, "type": "library", "autoload": { @@ -2771,7 +2780,7 @@ } ], "description": "BDD code blocks for PHPUnit and Codeception", - "time": "2018-03-12T23:55:10+00:00" + "time": "2019-08-01T20:09:26+00:00" }, { "name": "codeception/stub", @@ -3014,6 +3023,66 @@ ], "time": "2019-02-23T17:29:08+00:00" }, + { + "name": "facebook/webdriver", + "version": "1.7.1", + "source": { + "type": "git", + "url": "https://github.com/facebook/php-webdriver.git", + "reference": "e43de70f3c7166169d0f14a374505392734160e5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/facebook/php-webdriver/zipball/e43de70f3c7166169d0f14a374505392734160e5", + "reference": "e43de70f3c7166169d0f14a374505392734160e5", + "shasum": "" + }, + "require": { + "ext-curl": "*", + "ext-json": "*", + "ext-mbstring": "*", + "ext-zip": "*", + "php": "^5.6 || ~7.0", + "symfony/process": "^2.8 || ^3.1 || ^4.0" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^2.0", + "jakub-onderka/php-parallel-lint": "^0.9.2", + "php-coveralls/php-coveralls": "^2.0", + "php-mock/php-mock-phpunit": "^1.1", + "phpunit/phpunit": "^5.7", + "sebastian/environment": "^1.3.4 || ^2.0 || ^3.0", + "squizlabs/php_codesniffer": "^2.6", + "symfony/var-dumper": "^3.3 || ^4.0" + }, + "suggest": { + "ext-SimpleXML": "For Firefox profile creation" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-community": "1.5-dev" + } + }, + "autoload": { + "psr-4": { + "Facebook\\WebDriver\\": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "description": "A PHP client for Selenium WebDriver", + "homepage": "https://github.com/facebook/php-webdriver", + "keywords": [ + "facebook", + "php", + "selenium", + "webdriver" + ], + "time": "2019-06-13T08:02:18+00:00" + }, { "name": "flow/jsonpath", "version": "0.4.0", @@ -4378,16 +4447,16 @@ }, { "name": "phpspec/prophecy", - "version": "1.8.0", + "version": "1.8.1", "source": { "type": "git", "url": "https://github.com/phpspec/prophecy.git", - "reference": "4ba436b55987b4bf311cb7c6ba82aa528aac0a06" + "reference": "1927e75f4ed19131ec9bcc3b002e07fb1173ee76" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpspec/prophecy/zipball/4ba436b55987b4bf311cb7c6ba82aa528aac0a06", - "reference": "4ba436b55987b4bf311cb7c6ba82aa528aac0a06", + "url": "https://api.github.com/repos/phpspec/prophecy/zipball/1927e75f4ed19131ec9bcc3b002e07fb1173ee76", + "reference": "1927e75f4ed19131ec9bcc3b002e07fb1173ee76", "shasum": "" }, "require": { @@ -4408,8 +4477,8 @@ } }, "autoload": { - "psr-0": { - "Prophecy\\": "src/" + "psr-4": { + "Prophecy\\": "src/Prophecy" } }, "notification-url": "https://packagist.org/downloads/", @@ -4437,44 +4506,44 @@ "spy", "stub" ], - "time": "2018-08-05T17:53:17+00:00" + "time": "2019-06-13T12:50:23+00:00" }, { "name": "phpunit/php-code-coverage", - "version": "6.1.4", + "version": "7.0.7", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-code-coverage.git", - "reference": "807e6013b00af69b6c5d9ceb4282d0393dbb9d8d" + "reference": "7743bbcfff2a907e9ee4a25be13d0f8ec5e73800" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/807e6013b00af69b6c5d9ceb4282d0393dbb9d8d", - "reference": "807e6013b00af69b6c5d9ceb4282d0393dbb9d8d", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/7743bbcfff2a907e9ee4a25be13d0f8ec5e73800", + "reference": "7743bbcfff2a907e9ee4a25be13d0f8ec5e73800", "shasum": "" }, "require": { "ext-dom": "*", "ext-xmlwriter": "*", - "php": "^7.1", - "phpunit/php-file-iterator": "^2.0", + "php": "^7.2", + "phpunit/php-file-iterator": "^2.0.2", "phpunit/php-text-template": "^1.2.1", - "phpunit/php-token-stream": "^3.0", + "phpunit/php-token-stream": "^3.1.0", "sebastian/code-unit-reverse-lookup": "^1.0.1", - "sebastian/environment": "^3.1 || ^4.0", + "sebastian/environment": "^4.2.2", "sebastian/version": "^2.0.1", - "theseer/tokenizer": "^1.1" + "theseer/tokenizer": "^1.1.3" }, "require-dev": { - "phpunit/phpunit": "^7.0" + "phpunit/phpunit": "^8.2.2" }, "suggest": { - "ext-xdebug": "^2.6.0" + "ext-xdebug": "^2.7.2" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "6.1-dev" + "dev-master": "7.0-dev" } }, "autoload": { @@ -4489,8 +4558,8 @@ "authors": [ { "name": "Sebastian Bergmann", - "email": "sebastian@phpunit.de", - "role": "lead" + "role": "lead", + "email": "sebastian@phpunit.de" } ], "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.", @@ -4500,7 +4569,7 @@ "testing", "xunit" ], - "time": "2018-10-31T16:06:48+00:00" + "time": "2019-07-25T05:31:54+00:00" }, { "name": "phpunit/php-file-iterator", @@ -4595,16 +4664,16 @@ }, { "name": "phpunit/php-timer", - "version": "2.1.1", + "version": "2.1.2", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-timer.git", - "reference": "8b389aebe1b8b0578430bda0c7c95a829608e059" + "reference": "1038454804406b0b5f5f520358e78c1c2f71501e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/8b389aebe1b8b0578430bda0c7c95a829608e059", - "reference": "8b389aebe1b8b0578430bda0c7c95a829608e059", + "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/1038454804406b0b5f5f520358e78c1c2f71501e", + "reference": "1038454804406b0b5f5f520358e78c1c2f71501e", "shasum": "" }, "require": { @@ -4631,8 +4700,8 @@ "authors": [ { "name": "Sebastian Bergmann", - "email": "sebastian@phpunit.de", - "role": "lead" + "role": "lead", + "email": "sebastian@phpunit.de" } ], "description": "Utility class for timing", @@ -4640,20 +4709,20 @@ "keywords": [ "timer" ], - "time": "2019-02-20T10:12:59+00:00" + "time": "2019-06-07T04:22:29+00:00" }, { "name": "phpunit/php-token-stream", - "version": "3.0.1", + "version": "3.1.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-token-stream.git", - "reference": "c99e3be9d3e85f60646f152f9002d46ed7770d18" + "reference": "e899757bb3df5ff6e95089132f32cd59aac2220a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/c99e3be9d3e85f60646f152f9002d46ed7770d18", - "reference": "c99e3be9d3e85f60646f152f9002d46ed7770d18", + "url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/e899757bb3df5ff6e95089132f32cd59aac2220a", + "reference": "e899757bb3df5ff6e95089132f32cd59aac2220a", "shasum": "" }, "require": { @@ -4666,7 +4735,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "3.0-dev" + "dev-master": "3.1-dev" } }, "autoload": { @@ -4689,57 +4758,56 @@ "keywords": [ "tokenizer" ], - "time": "2018-10-30T05:52:18+00:00" + "time": "2019-07-25T05:29:42+00:00" }, { "name": "phpunit/phpunit", - "version": "7.5.10", + "version": "8.3.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "d7d9cee051d03ed98df6023aad93f7902731a780" + "reference": "21461ce5b162d0f1a0fa658e27f975517c5d4234" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/d7d9cee051d03ed98df6023aad93f7902731a780", - "reference": "d7d9cee051d03ed98df6023aad93f7902731a780", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/21461ce5b162d0f1a0fa658e27f975517c5d4234", + "reference": "21461ce5b162d0f1a0fa658e27f975517c5d4234", "shasum": "" }, "require": { - "doctrine/instantiator": "^1.1", + "doctrine/instantiator": "^1.2.0", "ext-dom": "*", "ext-json": "*", "ext-libxml": "*", "ext-mbstring": "*", "ext-xml": "*", - "myclabs/deep-copy": "^1.7", - "phar-io/manifest": "^1.0.2", - "phar-io/version": "^2.0", - "php": "^7.1", - "phpspec/prophecy": "^1.7", - "phpunit/php-code-coverage": "^6.0.7", - "phpunit/php-file-iterator": "^2.0.1", + "ext-xmlwriter": "*", + "myclabs/deep-copy": "^1.9.1", + "phar-io/manifest": "^1.0.3", + "phar-io/version": "^2.0.1", + "php": "^7.2", + "phpspec/prophecy": "^1.8.1", + "phpunit/php-code-coverage": "^7.0.7", + "phpunit/php-file-iterator": "^2.0.2", "phpunit/php-text-template": "^1.2.1", - "phpunit/php-timer": "^2.1", - "sebastian/comparator": "^3.0", - "sebastian/diff": "^3.0", - "sebastian/environment": "^4.0", - "sebastian/exporter": "^3.1", - "sebastian/global-state": "^2.0", + "phpunit/php-timer": "^2.1.2", + "sebastian/comparator": "^3.0.2", + "sebastian/diff": "^3.0.2", + "sebastian/environment": "^4.2.2", + "sebastian/exporter": "^3.1.0", + "sebastian/global-state": "^3.0.0", "sebastian/object-enumerator": "^3.0.3", - "sebastian/resource-operations": "^2.0", + "sebastian/resource-operations": "^2.0.1", + "sebastian/type": "^1.1.3", "sebastian/version": "^2.0.1" }, - "conflict": { - "phpunit/phpunit-mock-objects": "*" - }, "require-dev": { "ext-pdo": "*" }, "suggest": { "ext-soap": "*", "ext-xdebug": "*", - "phpunit/php-invoker": "^2.0" + "phpunit/php-invoker": "^2.0.0" }, "bin": [ "phpunit" @@ -4747,7 +4815,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "7.5-dev" + "dev-master": "8.3-dev" } }, "autoload": { @@ -4762,8 +4830,8 @@ "authors": [ { "name": "Sebastian Bergmann", - "email": "sebastian@phpunit.de", - "role": "lead" + "role": "lead", + "email": "sebastian@phpunit.de" } ], "description": "The PHP Unit Testing framework.", @@ -4773,7 +4841,7 @@ "testing", "xunit" ], - "time": "2019-05-09T05:06:47+00:00" + "time": "2019-08-02T07:54:25+00:00" }, { "name": "predis/predis", @@ -4825,6 +4893,55 @@ ], "time": "2016-06-16T16:22:20+00:00" }, + { + "name": "psr/container", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/b7ce3b176482dbbc1245ebf52b181af44c2cf55f", + "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "time": "2017-02-14T16:28:37+00:00" + }, { "name": "psr/log", "version": "1.1.0", @@ -5446,23 +5563,26 @@ }, { "name": "sebastian/global-state", - "version": "2.0.0", + "version": "3.0.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/global-state.git", - "reference": "e8ba02eed7bbbb9e59e43dedd3dddeff4a56b0c4" + "reference": "edf8a461cf1d4005f19fb0b6b8b95a9f7fa0adc4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/e8ba02eed7bbbb9e59e43dedd3dddeff4a56b0c4", - "reference": "e8ba02eed7bbbb9e59e43dedd3dddeff4a56b0c4", + "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/edf8a461cf1d4005f19fb0b6b8b95a9f7fa0adc4", + "reference": "edf8a461cf1d4005f19fb0b6b8b95a9f7fa0adc4", "shasum": "" }, "require": { - "php": "^7.0" + "php": "^7.2", + "sebastian/object-reflector": "^1.1.1", + "sebastian/recursion-context": "^3.0" }, "require-dev": { - "phpunit/phpunit": "^6.0" + "ext-dom": "*", + "phpunit/phpunit": "^8.0" }, "suggest": { "ext-uopz": "*" @@ -5470,7 +5590,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "2.0-dev" + "dev-master": "3.0-dev" } }, "autoload": { @@ -5493,7 +5613,7 @@ "keywords": [ "global state" ], - "time": "2017-04-27T15:39:26+00:00" + "time": "2019-02-01T05:30:01+00:00" }, { "name": "sebastian/object-enumerator", @@ -5682,6 +5802,52 @@ "homepage": "https://www.github.com/sebastianbergmann/resource-operations", "time": "2018-10-04T04:07:39+00:00" }, + { + "name": "sebastian/type", + "version": "1.1.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/type.git", + "reference": "3aaaa15fa71d27650d62a948be022fe3b48541a3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/3aaaa15fa71d27650d62a948be022fe3b48541a3", + "reference": "3aaaa15fa71d27650d62a948be022fe3b48541a3", + "shasum": "" + }, + "require": { + "php": "^7.2" + }, + "require-dev": { + "phpunit/phpunit": "^8.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "role": "lead", + "email": "sebastian@phpunit.de" + } + ], + "description": "Collection of value objects that represent the types of the PHP type system", + "homepage": "https://github.com/sebastianbergmann/type", + "time": "2019-07-02T08:10:15+00:00" + }, { "name": "sebastian/version", "version": "2.0.1", @@ -5727,16 +5893,16 @@ }, { "name": "symfony/browser-kit", - "version": "v4.2.8", + "version": "v4.3.3", "source": { "type": "git", "url": "https://github.com/symfony/browser-kit.git", - "reference": "c09c18cca96d7067152f78956faf55346c338283" + "reference": "a29dd02a1f3f81b9a15c7730cc3226718ddb55ca" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/browser-kit/zipball/c09c18cca96d7067152f78956faf55346c338283", - "reference": "c09c18cca96d7067152f78956faf55346c338283", + "url": "https://api.github.com/repos/symfony/browser-kit/zipball/a29dd02a1f3f81b9a15c7730cc3226718ddb55ca", + "reference": "a29dd02a1f3f81b9a15c7730cc3226718ddb55ca", "shasum": "" }, "require": { @@ -5745,6 +5911,8 @@ }, "require-dev": { "symfony/css-selector": "~3.4|~4.0", + "symfony/http-client": "^4.3", + "symfony/mime": "^4.3", "symfony/process": "~3.4|~4.0" }, "suggest": { @@ -5753,7 +5921,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.2-dev" + "dev-master": "4.3-dev" } }, "autoload": { @@ -5780,29 +5948,31 @@ ], "description": "Symfony BrowserKit Component", "homepage": "https://symfony.com", - "time": "2019-04-07T09:56:43+00:00" + "time": "2019-06-11T15:41:59+00:00" }, { "name": "symfony/console", - "version": "v4.2.8", + "version": "v4.3.3", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "e2840bb38bddad7a0feaf85931e38fdcffdb2f81" + "reference": "8b0ae5742ce9aaa8b0075665862c1ca397d1c1d9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/e2840bb38bddad7a0feaf85931e38fdcffdb2f81", - "reference": "e2840bb38bddad7a0feaf85931e38fdcffdb2f81", + "url": "https://api.github.com/repos/symfony/console/zipball/8b0ae5742ce9aaa8b0075665862c1ca397d1c1d9", + "reference": "8b0ae5742ce9aaa8b0075665862c1ca397d1c1d9", "shasum": "" }, "require": { "php": "^7.1.3", - "symfony/contracts": "^1.0", - "symfony/polyfill-mbstring": "~1.0" + "symfony/polyfill-mbstring": "~1.0", + "symfony/polyfill-php73": "^1.8", + "symfony/service-contracts": "^1.1" }, "conflict": { "symfony/dependency-injection": "<3.4", + "symfony/event-dispatcher": "<4.3", "symfony/process": "<3.3" }, "provide": { @@ -5812,9 +5982,10 @@ "psr/log": "~1.0", "symfony/config": "~3.4|~4.0", "symfony/dependency-injection": "~3.4|~4.0", - "symfony/event-dispatcher": "~3.4|~4.0", + "symfony/event-dispatcher": "^4.3", "symfony/lock": "~3.4|~4.0", - "symfony/process": "~3.4|~4.0" + "symfony/process": "~3.4|~4.0", + "symfony/var-dumper": "^4.3" }, "suggest": { "psr/log": "For using the console logger", @@ -5825,7 +5996,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.2-dev" + "dev-master": "4.3-dev" } }, "autoload": { @@ -5852,7 +6023,7 @@ ], "description": "Symfony Console Component", "homepage": "https://symfony.com", - "time": "2019-04-08T14:23:48+00:00" + "time": "2019-07-24T17:13:59+00:00" }, { "name": "symfony/contracts", @@ -5927,16 +6098,16 @@ }, { "name": "symfony/css-selector", - "version": "v4.2.8", + "version": "v4.3.3", "source": { "type": "git", "url": "https://github.com/symfony/css-selector.git", - "reference": "48eddf66950fa57996e1be4a55916d65c10c604a" + "reference": "105c98bb0c5d8635bea056135304bd8edcc42b4d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/css-selector/zipball/48eddf66950fa57996e1be4a55916d65c10c604a", - "reference": "48eddf66950fa57996e1be4a55916d65c10c604a", + "url": "https://api.github.com/repos/symfony/css-selector/zipball/105c98bb0c5d8635bea056135304bd8edcc42b4d", + "reference": "105c98bb0c5d8635bea056135304bd8edcc42b4d", "shasum": "" }, "require": { @@ -5945,7 +6116,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.2-dev" + "dev-master": "4.3-dev" } }, "autoload": { @@ -5961,14 +6132,14 @@ "MIT" ], "authors": [ - { - "name": "Jean-François Simon", - "email": "jeanfrancois.simon@sensiolabs.com" - }, { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, + { + "name": "Jean-François Simon", + "email": "jeanfrancois.simon@sensiolabs.com" + }, { "name": "Symfony Community", "homepage": "https://symfony.com/contributors" @@ -5976,20 +6147,20 @@ ], "description": "Symfony CssSelector Component", "homepage": "https://symfony.com", - "time": "2019-01-16T20:31:39+00:00" + "time": "2019-01-16T21:53:39+00:00" }, { "name": "symfony/dom-crawler", - "version": "v4.2.8", + "version": "v4.3.3", "source": { "type": "git", "url": "https://github.com/symfony/dom-crawler.git", - "reference": "53c97769814c80a84a8403efcf3ae7ae966d53bb" + "reference": "291397232a2eefb3347eaab9170409981eaad0e2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/dom-crawler/zipball/53c97769814c80a84a8403efcf3ae7ae966d53bb", - "reference": "53c97769814c80a84a8403efcf3ae7ae966d53bb", + "url": "https://api.github.com/repos/symfony/dom-crawler/zipball/291397232a2eefb3347eaab9170409981eaad0e2", + "reference": "291397232a2eefb3347eaab9170409981eaad0e2", "shasum": "" }, "require": { @@ -5997,7 +6168,11 @@ "symfony/polyfill-ctype": "~1.8", "symfony/polyfill-mbstring": "~1.0" }, + "conflict": { + "masterminds/html5": "<2.6" + }, "require-dev": { + "masterminds/html5": "^2.6", "symfony/css-selector": "~3.4|~4.0" }, "suggest": { @@ -6006,7 +6181,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.2-dev" + "dev-master": "4.3-dev" } }, "autoload": { @@ -6033,34 +6208,40 @@ ], "description": "Symfony DomCrawler Component", "homepage": "https://symfony.com", - "time": "2019-02-23T15:17:42+00:00" + "time": "2019-06-13T11:03:18+00:00" }, { "name": "symfony/event-dispatcher", - "version": "v4.2.8", + "version": "v4.3.3", "source": { "type": "git", "url": "https://github.com/symfony/event-dispatcher.git", - "reference": "fbce53cd74ac509cbe74b6f227622650ab759b02" + "reference": "212b020949331b6531250584531363844b34a94e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/fbce53cd74ac509cbe74b6f227622650ab759b02", - "reference": "fbce53cd74ac509cbe74b6f227622650ab759b02", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/212b020949331b6531250584531363844b34a94e", + "reference": "212b020949331b6531250584531363844b34a94e", "shasum": "" }, "require": { "php": "^7.1.3", - "symfony/contracts": "^1.0" + "symfony/event-dispatcher-contracts": "^1.1" }, "conflict": { "symfony/dependency-injection": "<3.4" }, + "provide": { + "psr/event-dispatcher-implementation": "1.0", + "symfony/event-dispatcher-implementation": "1.1" + }, "require-dev": { "psr/log": "~1.0", "symfony/config": "~3.4|~4.0", "symfony/dependency-injection": "~3.4|~4.0", "symfony/expression-language": "~3.4|~4.0", + "symfony/http-foundation": "^3.4|^4.0", + "symfony/service-contracts": "^1.1", "symfony/stopwatch": "~3.4|~4.0" }, "suggest": { @@ -6070,7 +6251,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.2-dev" + "dev-master": "4.3-dev" } }, "autoload": { @@ -6097,7 +6278,65 @@ ], "description": "Symfony EventDispatcher Component", "homepage": "https://symfony.com", - "time": "2019-04-06T13:51:08+00:00" + "time": "2019-06-27T06:42:14+00:00" + }, + { + "name": "symfony/event-dispatcher-contracts", + "version": "v1.1.5", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher-contracts.git", + "reference": "c61766f4440ca687de1084a5c00b08e167a2575c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/c61766f4440ca687de1084a5c00b08e167a2575c", + "reference": "c61766f4440ca687de1084a5c00b08e167a2575c", + "shasum": "" + }, + "require": { + "php": "^7.1.3" + }, + "suggest": { + "psr/event-dispatcher": "", + "symfony/event-dispatcher-implementation": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\EventDispatcher\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to dispatching event", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "time": "2019-06-20T06:46:26+00:00" }, { "name": "symfony/filesystem", @@ -6203,6 +6442,64 @@ ], "time": "2019-01-16T21:31:25+00:00" }, + { + "name": "symfony/service-contracts", + "version": "v1.1.5", + "source": { + "type": "git", + "url": "https://github.com/symfony/service-contracts.git", + "reference": "f391a00de78ec7ec8cf5cdcdae59ec7b883edb8d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/f391a00de78ec7ec8cf5cdcdae59ec7b883edb8d", + "reference": "f391a00de78ec7ec8cf5cdcdae59ec7b883edb8d", + "shasum": "" + }, + "require": { + "php": "^7.1.3", + "psr/container": "^1.0" + }, + "suggest": { + "symfony/service-implementation": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\Service\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to writing services", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "time": "2019-06-13T11:15:36+00:00" + }, { "name": "symfony/stopwatch", "version": "v4.2.3", @@ -6255,16 +6552,16 @@ }, { "name": "symfony/yaml", - "version": "v4.2.8", + "version": "v4.3.3", "source": { "type": "git", "url": "https://github.com/symfony/yaml.git", - "reference": "6712daf03ee25b53abb14e7e8e0ede1a770efdb1" + "reference": "34d29c2acd1ad65688f58452fd48a46bd996d5a6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/yaml/zipball/6712daf03ee25b53abb14e7e8e0ede1a770efdb1", - "reference": "6712daf03ee25b53abb14e7e8e0ede1a770efdb1", + "url": "https://api.github.com/repos/symfony/yaml/zipball/34d29c2acd1ad65688f58452fd48a46bd996d5a6", + "reference": "34d29c2acd1ad65688f58452fd48a46bd996d5a6", "shasum": "" }, "require": { @@ -6283,7 +6580,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.2-dev" + "dev-master": "4.3-dev" } }, "autoload": { @@ -6310,20 +6607,20 @@ ], "description": "Symfony Yaml Component", "homepage": "https://symfony.com", - "time": "2019-03-30T15:58:42+00:00" + "time": "2019-07-24T14:47:54+00:00" }, { "name": "theseer/tokenizer", - "version": "1.1.2", + "version": "1.1.3", "source": { "type": "git", "url": "https://github.com/theseer/tokenizer.git", - "reference": "1c42705be2b6c1de5904f8afacef5895cab44bf8" + "reference": "11336f6f84e16a720dae9d8e6ed5019efa85a0f9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/theseer/tokenizer/zipball/1c42705be2b6c1de5904f8afacef5895cab44bf8", - "reference": "1c42705be2b6c1de5904f8afacef5895cab44bf8", + "url": "https://api.github.com/repos/theseer/tokenizer/zipball/11336f6f84e16a720dae9d8e6ed5019efa85a0f9", + "reference": "11336f6f84e16a720dae9d8e6ed5019efa85a0f9", "shasum": "" }, "require": { @@ -6350,7 +6647,7 @@ } ], "description": "A small library for converting tokenized PHP source code into XML and potentially other formats", - "time": "2019-04-04T09:56:43+00:00" + "time": "2019-06-13T22:48:21+00:00" } ], "aliases": [], From 967d8b11a0c1ed773f172b49889534f993635db7 Mon Sep 17 00:00:00 2001 From: ErickSkrauch Date: Fri, 2 Aug 2019 18:32:08 +0300 Subject: [PATCH 6/7] Improve tests coverage --- .../OAuth2/Entities/RefreshTokenEntity.php | 11 ++-- api/components/User/IdentityFactory.php | 2 +- ...{Oauth2Identity.php => OAuth2Identity.php} | 7 ++- .../unit/components/Tokens/ComponentTest.php | 4 ++ .../unit/components/User/ComponentTest.php | 4 +- .../components/User/IdentityFactoryTest.php | 59 +++++++++++++++++++ .../components/User/OAuth2IdentityTest.php | 56 ++++++++++++++++++ 7 files changed, 133 insertions(+), 10 deletions(-) rename api/components/User/{Oauth2Identity.php => OAuth2Identity.php} (90%) create mode 100644 api/tests/unit/components/User/IdentityFactoryTest.php create mode 100644 api/tests/unit/components/User/OAuth2IdentityTest.php diff --git a/api/components/OAuth2/Entities/RefreshTokenEntity.php b/api/components/OAuth2/Entities/RefreshTokenEntity.php index 5ef3fc7..372f003 100644 --- a/api/components/OAuth2/Entities/RefreshTokenEntity.php +++ b/api/components/OAuth2/Entities/RefreshTokenEntity.php @@ -1,9 +1,11 @@ session; } + /** @var SessionStorage $sessionStorage */ $sessionStorage = $this->server->getSessionStorage(); - if (!$sessionStorage instanceof SessionStorage) { - throw new ErrorException('SessionStorage must be instance of ' . SessionStorage::class); - } + Assert::isInstanceOf($sessionStorage, SessionStorage::class); return $sessionStorage->getById($this->sessionId); } @@ -32,7 +33,7 @@ class RefreshTokenEntity extends \League\OAuth2\Server\Entity\RefreshTokenEntity public function setSession(OriginalSessionEntity $session): self { parent::setSession($session); - $this->setSessionId($session->getId()); + $this->setSessionId((int)$session->getId()); return $this; } diff --git a/api/components/User/IdentityFactory.php b/api/components/User/IdentityFactory.php index f38f47e..2b59630 100644 --- a/api/components/User/IdentityFactory.php +++ b/api/components/User/IdentityFactory.php @@ -20,7 +20,7 @@ class IdentityFactory { return JwtIdentity::findIdentityByAccessToken($token, $type); } - return Oauth2Identity::findIdentityByAccessToken($token, $type); + return OAuth2Identity::findIdentityByAccessToken($token, $type); } } diff --git a/api/components/User/Oauth2Identity.php b/api/components/User/OAuth2Identity.php similarity index 90% rename from api/components/User/Oauth2Identity.php rename to api/components/User/OAuth2Identity.php index 8a9001a..bbb06cf 100644 --- a/api/components/User/Oauth2Identity.php +++ b/api/components/User/OAuth2Identity.php @@ -10,7 +10,7 @@ use Yii; use yii\base\NotSupportedException; use yii\web\UnauthorizedHttpException; -class Oauth2Identity implements IdentityInterface { +class OAuth2Identity implements IdentityInterface { /** * @var AccessTokenEntity @@ -55,6 +55,7 @@ class Oauth2Identity implements IdentityInterface { return $this->_accessToken->getId(); } + // @codeCoverageIgnoreStart public function getAuthKey() { throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth'); } @@ -67,8 +68,10 @@ class Oauth2Identity implements IdentityInterface { throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth'); } + // @codeCoverageIgnoreEnd + private function getSession(): OauthSession { - return OauthSession::findOne($this->_accessToken->getSessionId()); + return OauthSession::findOne(['id' => $this->_accessToken->getSessionId()]); } } diff --git a/api/tests/unit/components/Tokens/ComponentTest.php b/api/tests/unit/components/Tokens/ComponentTest.php index 9cd9c36..d8a7018 100644 --- a/api/tests/unit/components/Tokens/ComponentTest.php +++ b/api/tests/unit/components/Tokens/ComponentTest.php @@ -73,6 +73,10 @@ class ComponentTest extends TestCase { (new Parser())->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.xxx'), false, ]; + yield 'RS256 (unsupported)' => [ + (new Parser())->parse('eyJhbGciOiJSUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.t3c68OMaoWWXxNFuz6SW-RfNmCOwAagyPSedbzJ1K3gR3bY5C8PRP6IEyE-OQvAcSFQcake0brsa4caXAmVlU0c3jQxpjk0bl4fBMd-InpGCoo42G89lgAY-dqWeJqokRORCpUL5Mzptbm5fNDlCrnNhI_6EmQygL3WXh1uorCbcxxO-Lb2Nr7Sge7GV0t24-I61I7ErrFL2ZC9ybSi6V8pdhFZlfO6MSUM0ASyRN994sVmcQEZHDiQFP7zj79zoAFamfYe8JBFAGtC-p4LeVYjrw052VahNXyRuGLxW7y1gX-znpyx0T-7lgKSWVxhJ6k3qt5qT33utdC76w1vihEdYinpEE3VbTMN01bxAFpyDbK11R49FCwCKStPjw_wdoLZChx_zob95yVU6IUCJwPYVc4SBtrAPV0uVe3mL3Gzgtr6MkhJAF3diFevTLGfnOOCAWwhdjVs10VWqcajBwvfFlm_Yw5MYZnetEECqumqFEr_u6CdRxtx0gCiPReDG8XwYHt0EqEw-LoRqxGWp5zqfud7f0DWv6cXlLbnKsB8XQh8EqnKblvNCFilXJIgfknCZ34PAob1pUkXO1geMLw4b8NUnKta1D3ad3AxGW5CEmOjWzEhzMOxIgnouU2ZVtWFDrPVs12Q4494BxTvGKXrG2cT6TK18-XY26DllglY'), + false, + ]; } protected function _setUp() { diff --git a/api/tests/unit/components/User/ComponentTest.php b/api/tests/unit/components/User/ComponentTest.php index 1d9ac6e..e9ca1cc 100644 --- a/api/tests/unit/components/User/ComponentTest.php +++ b/api/tests/unit/components/User/ComponentTest.php @@ -5,7 +5,7 @@ namespace codeception\api\unit\components\User; use api\components\User\Component; use api\components\User\JwtIdentity; -use api\components\User\Oauth2Identity; +use api\components\User\OAuth2Identity; use api\tests\unit\TestCase; use common\models\Account; use common\models\AccountSession; @@ -41,7 +41,7 @@ class ComponentTest extends TestCase { $this->assertNull($component->getActiveSession()); // Identity is a Oauth2Identity - $component->setIdentity(mock(Oauth2Identity::class)); + $component->setIdentity(mock(OAuth2Identity::class)); $this->assertNull($component->getActiveSession()); // Identity is correct, but have no jti claim diff --git a/api/tests/unit/components/User/IdentityFactoryTest.php b/api/tests/unit/components/User/IdentityFactoryTest.php new file mode 100644 index 0000000..b3d6851 --- /dev/null +++ b/api/tests/unit/components/User/IdentityFactoryTest.php @@ -0,0 +1,59 @@ +assertInstanceOf(JwtIdentity::class, $identity); + + // Find identity by oauth2 token + $accessToken = new AccessTokenEntity(mock(AbstractServer::class)); + $accessToken->setExpireTime(time() + 3600); + $accessToken->setId('mock-token'); + + /** @var AccessTokenInterface|\Mockery\MockInterface $accessTokensStorage */ + $accessTokensStorage = mock(AccessTokenInterface::class); + $accessTokensStorage->shouldReceive('get')->with('mock-token')->andReturn($accessToken); + + /** @var Component|\Mockery\MockInterface $component */ + $component = mock(Component::class); + $component->shouldReceive('getAccessTokenStorage')->andReturn($accessTokensStorage); + Yii::$app->set('oauth', $component); + + $identity = IdentityFactory::findIdentityByAccessToken('mock-token'); + $this->assertInstanceOf(OAuth2Identity::class, $identity); + } + + public function testFindIdentityByAccessTokenWithEmptyValue() { + $this->expectException(UnauthorizedHttpException::class); + $this->expectExceptionMessage('Incorrect token'); + IdentityFactory::findIdentityByAccessToken(''); + } + + protected function _setUp() { + parent::_setUp(); + Carbon::setTestNow(Carbon::create(2019, 8, 1, 1, 2, 22, 'Europe/Minsk')); + } + + protected function _tearDown() { + parent::_tearDown(); + Carbon::setTestNow(); + } + +} diff --git a/api/tests/unit/components/User/OAuth2IdentityTest.php b/api/tests/unit/components/User/OAuth2IdentityTest.php new file mode 100644 index 0000000..790f139 --- /dev/null +++ b/api/tests/unit/components/User/OAuth2IdentityTest.php @@ -0,0 +1,56 @@ +setExpireTime(time() + 3600); + $accessToken->setId('mock-token'); + $this->mockFoundedAccessToken($accessToken); + + $identity = OAuth2Identity::findIdentityByAccessToken('mock-token'); + $this->assertSame('mock-token', $identity->getId()); + } + + public function testFindIdentityByAccessTokenWithNonExistsToken() { + $this->expectException(UnauthorizedHttpException::class); + $this->expectExceptionMessage('Incorrect token'); + + OAuth2Identity::findIdentityByAccessToken('not exists token'); + } + + public function testFindIdentityByAccessTokenWithExpiredToken() { + $this->expectException(UnauthorizedHttpException::class); + $this->expectExceptionMessage('Token expired'); + + $accessToken = new AccessTokenEntity(mock(AbstractServer::class)); + $accessToken->setExpireTime(time() - 3600); + $this->mockFoundedAccessToken($accessToken); + + OAuth2Identity::findIdentityByAccessToken('mock-token'); + } + + private function mockFoundedAccessToken(AccessTokenEntity $accessToken) { + /** @var AccessTokenInterface|\Mockery\MockInterface $accessTokensStorage */ + $accessTokensStorage = mock(AccessTokenInterface::class); + $accessTokensStorage->shouldReceive('get')->with('mock-token')->andReturn($accessToken); + + /** @var Component|\Mockery\MockInterface $component */ + $component = mock(Component::class); + $component->shouldReceive('getAccessTokenStorage')->andReturn($accessTokensStorage); + Yii::$app->set('oauth', $component); + } + +} From 6ad66b28cf3352ca1a0a6379231249e92eac655a Mon Sep 17 00:00:00 2001 From: ErickSkrauch Date: Fri, 2 Aug 2019 19:16:34 +0300 Subject: [PATCH 7/7] Generate keys pair if they aren't exists --- api/components/Tokens/Component.php | 8 ++++++++ docker-compose.prod.yml | 10 ++++++++++ docker/php/docker-entrypoint.sh | 8 ++++++++ 3 files changed, 26 insertions(+) diff --git a/api/components/Tokens/Component.php b/api/components/Tokens/Component.php index 8872e7c..ec19bbf 100644 --- a/api/components/Tokens/Component.php +++ b/api/components/Tokens/Component.php @@ -8,6 +8,7 @@ use Exception; use Lcobucci\JWT\Builder; use Lcobucci\JWT\Parser; use Lcobucci\JWT\Token; +use Webmozart\Assert\Assert; use yii\base\Component as BaseComponent; class Component extends BaseComponent { @@ -39,6 +40,13 @@ class Component extends BaseComponent { */ private $algorithmManager; + public function init(): void { + parent::init(); + Assert::notEmpty($this->hmacKey, 'hmacKey must be set'); + Assert::notEmpty($this->privateKeyPath, 'privateKeyPath must be set'); + Assert::notEmpty($this->publicKeyPath, 'publicKeyPath must be set'); + } + public function create(array $payloads = [], array $headers = []): Token { $now = Carbon::now(); $builder = (new Builder()) diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 9d1a6a0..851cf7a 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -27,6 +27,8 @@ services: - db - redis env_file: .env + volumes: + - certs-storage:/var/www/html/data/certs networks: default: aliases: @@ -71,6 +73,14 @@ services: volumes: - ./data/redis:/data +volumes: + certs-storage: + driver: local + driver_opts: + type: none + device: $PWD/data/certs + o: bind + networks: nginx-proxy: external: diff --git a/docker/php/docker-entrypoint.sh b/docker/php/docker-entrypoint.sh index 7898d21..9cf1d5e 100755 --- a/docker/php/docker-entrypoint.sh +++ b/docker/php/docker-entrypoint.sh @@ -31,6 +31,14 @@ fi # Fix permissions for cron tasks chmod 644 /etc/cron.d/* +JWT_PRIVATE_PEM_LOCATION="/var/www/html/data/certs/private.pem" +JWT_PUBLIC_PEM_LOCATION="/var/www/html/data/certs/public.pem" +if [ ! -f "$JWT_PRIVATE_PEM_LOCATION" ] ; then + echo "There is no private key. Generating the new one." + openssl ecparam -name prime256v1 -genkey -noout -out "$JWT_PRIVATE_PEM_LOCATION" + openssl ec -in "$JWT_PRIVATE_PEM_LOCATION" -pubout -out "$JWT_PUBLIC_PEM_LOCATION" +fi + if [ "$1" = "crond" ] ; then # see: https://github.com/dubiousjim/dcron/issues/13 # ignore using `exec` for `dcron` to get another pid instead of `1`