Merge branch 'jwt-encryption-algorithm' into 'master'

Implemented Rs256 jwt encryption algorithm

See merge request elyby/accounts!7
This commit is contained in:
ErickSkrauch 2019-08-02 21:27:07 +00:00
commit fff358e038
103 changed files with 2040 additions and 1159 deletions

View File

@ -7,6 +7,8 @@ EMAILS_RENDERER_HOST=http://emails-renderer:3000
## Security params
JWT_USER_SECRET=
JWT_PUBLIC_KEY_PATH=
JWT_PRIVATE_KEY_PATH=
## External services
RECAPTCHA_PUBLIC=

View File

@ -22,4 +22,5 @@ coverage:
- tests/*
- codeception.dist.yml
- codeception.yml
- index.php
c3url: 'http://localhost/api/web/index.php'

View File

@ -1,9 +1,11 @@
<?php
declare(strict_types=1);
namespace api\components\OAuth2\Entities;
use api\components\OAuth2\Storage\SessionStorage;
use ErrorException;
use League\OAuth2\Server\Entity\SessionEntity as OriginalSessionEntity;
use Webmozart\Assert\Assert;
class RefreshTokenEntity extends \League\OAuth2\Server\Entity\RefreshTokenEntity {
@ -18,10 +20,9 @@ class RefreshTokenEntity extends \League\OAuth2\Server\Entity\RefreshTokenEntity
return $this->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;
}

View File

@ -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;

View File

@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace api\components\Tokens;
class AlgorithmIsNotDefinedException extends \Exception {
public function __construct(string $algorithmId) {
parent::__construct("Algorithm with id \"{$algorithmId}\" is not defined");
}
}

View File

@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace api\components\Tokens\Algorithms;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Key;
interface AlgorithmInterface {
public function getAlgorithmId(): string;
public function getSigner(): Signer;
public function getPrivateKey(): Key;
public function getPublicKey(): Key;
}

View File

@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace api\components\Tokens\Algorithms;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Ecdsa\Sha256;
use Lcobucci\JWT\Signer\Key;
class ES256 implements AlgorithmInterface {
/**
* @var string
*/
private $privateKey;
/**
* @var string|null
*/
private $privateKeyPass;
/**
* @var string
*/
private $publicKey;
/**
* @var Key|null
*/
private $loadedPrivateKey;
/**
* @var Key|null
*/
private $loadedPublicKey;
/**
* TODO: document arguments
*
* @param string $privateKey
* @param string|null $privateKeyPass
* @param string $publicKey
*/
public function __construct(string $privateKey, ?string $privateKeyPass, string $publicKey) {
$this->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;
}
}

View File

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace api\components\Tokens\Algorithms;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key;
class HS256 implements AlgorithmInterface {
/**
* @var string
*/
private $key;
/**
* @var Key|null
*/
private $loadedKey;
public function __construct(string $key) {
$this->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;
}
}

View File

@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace api\components\Tokens;
use api\components\Tokens\Algorithms\AlgorithmInterface;
use Webmozart\Assert\Assert;
class AlgorithmsManager {
/**
* @var AlgorithmInterface[]
*/
private $algorithms = [];
public function __construct(array $algorithms = []) {
array_map([$this, 'add'], $algorithms);
}
public function add(AlgorithmInterface $algorithm): self {
$id = $algorithm->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];
}
}

View File

@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
namespace api\components\Tokens;
use Carbon\Carbon;
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 {
private const PREFERRED_ALGORITHM = 'ES256';
/**
* @var string
*/
public $hmacKey;
/**
* @var string
*/
public $publicKeyPath;
/**
* @var string
*/
public $privateKeyPath;
/**
* @var string|null
*/
public $privateKeyPass;
/**
* @var AlgorithmsManager|null
*/
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())
->issuedAt($now->getTimestamp())
->expiresAt($now->addHour()->getTimestamp());
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;
}
}

View File

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace api\components\Tokens;
use Carbon\Carbon;
use common\models\Account;
use common\models\AccountSession;
use Lcobucci\JWT\Token;
use Yii;
class TokensFactory {
public const SUB_ACCOUNT_PREFIX = 'ely|';
public static function createForAccount(Account $account, AccountSession $session = null): Token {
$payloads = [
'ely-scopes' => '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'] = Carbon::now()->addDays(7)->getTimestamp();
} else {
$payloads['jti'] = $session->id;
}
return Yii::$app->tokens->create($payloads);
}
}

View File

@ -1,60 +0,0 @@
<?php
namespace api\components\User;
use common\models\Account;
use common\models\AccountSession;
use Emarref\Jwt\Claim\Expiration;
class AuthenticationResult {
/**
* @var Account
*/
private $account;
/**
* @var string
*/
private $jwt;
/**
* @var AccountSession|null
*/
private $session;
public function __construct(Account $account, string $jwt, ?AccountSession $session) {
$this->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;
}
}

View File

@ -1,23 +1,10 @@
<?php
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\Claim;
use Emarref\Jwt\Encryption\Factory as EncryptionFactory;
use Emarref\Jwt\Exception\VerificationException;
use Emarref\Jwt\Token;
use Emarref\Jwt\Verification\Context as VerificationContext;
use Exception;
use Yii;
use yii\base\InvalidConfigException;
use yii\web\UnauthorizedHttpException;
use yii\web\User as YiiUserComponent;
/**
@ -33,127 +20,25 @@ class Component extends YiiUserComponent {
public const KEEP_SITE_SESSIONS = 2;
public const KEEP_CURRENT_SESSION = 4;
public const JWT_SUBJECT_PREFIX = 'ely|';
public $enableSession = false;
public $loginUrl = null;
public $identityClass = Identity::class;
public $secret;
public $expirationTimeout = 'PT1H';
public $sessionTimeout = 'P7D';
/**
* @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();
if (!$this->secret) {
throw new InvalidConfigException('secret must be specified');
}
}
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);
} catch (UnauthorizedHttpException $e) {
// Do nothing. It's okay to catch this.
} catch (Exception $e) {
Yii::error($e);
}
return null;
}
public function createJwtAuthenticationToken(Account $account, bool $rememberMe): AuthenticationResult {
$ip = Yii::$app->request->userIP;
$token = $this->createToken($account);
if ($rememberMe) {
$session = new AccountSession();
$session->account_id = $account->id;
$session->setIp($ip);
$session->generateRefreshToken();
if (!$session->save()) {
throw new ThisShouldNotHappenException('Cannot save account session model');
}
$token->addClaim(new Claim\JwtId($session->id));
} else {
$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
$token->addClaim(new Claim\Expiration((new DateTime())->add(new DateInterval($this->sessionTimeout))));
}
$jwt = $this->serializeToken($token);
return new AuthenticationResult($account, $jwt, $session);
}
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;
}
/**
* @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);
}
$context = new VerificationContext(EncryptionFactory::create($this->getAlgorithm()));
$context->setSubject(self::JWT_SUBJECT_PREFIX);
$jwt->verify($notVerifiedToken, $context);
$token = $notVerifiedToken;
}
return $token;
}
public $identityClass = IdentityFactory::class;
/**
* 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
*
@ -164,23 +49,18 @@ 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 = $this->parseToken($bearer);
} catch (VerificationException $e) {
$sessionId = $identity->getToken()->getClaim('jti', false);
if ($sessionId === false) {
return null;
}
$sessionId = $token->getPayload()->findClaimByName(Claim\JwtId::NAME);
if ($sessionId === null) {
return null;
}
return AccountSession::findOne($sessionId->getValue());
return AccountSession::findOne($sessionId);
}
public function terminateSessions(Account $account, int $mode = 0): void {
@ -204,45 +84,4 @@ class Component extends YiiUserComponent {
}
}
public function getAlgorithm(): AlgorithmInterface {
return new Hs256($this->secret);
}
protected function serializeToken(Token $token): string {
return (new Jwt())->serialize($token, EncryptionFactory::create($this->getAlgorithm()));
}
protected function createToken(Account $account): Token {
$token = new Token();
foreach ($this->getClaims($account) as $claim) {
$token->addClaim($claim);
}
return $token;
}
/**
* @param Account $account
* @return Claim\AbstractClaim[]
*/
protected 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 getBearerToken() {
$authHeader = Yii::$app->request->getHeaders()->get('Authorization');
if ($authHeader === null || !preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
return null;
}
return $matches[1];
}
}

View File

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace api\components\User;
use yii\web\UnauthorizedHttpException;
class IdentityFactory {
/**
* @throws UnauthorizedHttpException
* @return IdentityInterface
*/
public static function findIdentityByAccessToken($token, $type = null): IdentityInterface {
if (empty($token)) {
throw new UnauthorizedHttpException('Incorrect token');
}
if (substr_count($token, '.') === 2) {
return JwtIdentity::findIdentityByAccessToken($token, $type);
}
return OAuth2Identity::findIdentityByAccessToken($token, $type);
}
}

View File

@ -1,23 +0,0 @@
<?php
namespace api\components\User;
use Emarref\Jwt\Verification\Context;
use Emarref\Jwt\Verification\SubjectVerifier;
class Jwt extends \Emarref\Jwt\Jwt {
protected function getVerifiers(Context $context): array {
$verifiers = parent::getVerifiers($context);
foreach ($verifiers as $i => $verifier) {
if (!$verifier instanceof SubjectVerifier) {
continue;
}
$verifiers[$i] = new SubjectPrefixVerifier($context->getSubject());
break;
}
return $verifiers;
}
}

View File

@ -1,84 +1,89 @@
<?php
declare(strict_types=1);
namespace api\components\User;
use api\components\Tokens\TokensFactory;
use Carbon\Carbon;
use common\models\Account;
use Emarref\Jwt\Claim\Subject;
use Emarref\Jwt\Exception\ExpiredException;
use Emarref\Jwt\Token;
use Exception;
use Lcobucci\JWT\Token;
use Lcobucci\JWT\ValidationData;
use Webmozart\Assert\Assert;
use Yii;
use yii\base\NotSupportedException;
use yii\helpers\StringHelper;
use yii\web\UnauthorizedHttpException;
class JwtIdentity implements IdentityInterface {
/**
* @var string
*/
private $rawToken;
/**
* @var Token
*/
private $token;
private function __construct(string $rawToken, Token $token) {
$this->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');
}
$now = Carbon::now();
if ($token->isExpired($now)) {
throw new UnauthorizedHttpException('Token expired');
}
if (!$token->validate(new ValidationData($now->getTimestamp()))) {
throw new UnauthorizedHttpException('Incorrect token');
}
$sub = $token->getClaim('sub', false);
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 {
/** @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;
}
// @codeCoverageIgnoreStart
public function getAuthKey() {
throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth');
}
@ -91,4 +96,6 @@ class JwtIdentity implements IdentityInterface {
throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth');
}
// @codeCoverageIgnoreEnd
}

View File

@ -1,4 +1,6 @@
<?php
declare(strict_types=1);
namespace api\components\User;
use api\components\OAuth2\Entities\AccessTokenEntity;
@ -8,10 +10,7 @@ use Yii;
use yii\base\NotSupportedException;
use yii\web\UnauthorizedHttpException;
/**
* @property Account $account
*/
class Identity implements IdentityInterface {
class OAuth2Identity implements IdentityInterface {
/**
* @var AccessTokenEntity
@ -24,19 +23,10 @@ class Identity implements IdentityInterface {
/**
* @inheritdoc
* @throws \yii\web\UnauthorizedHttpException
* @throws UnauthorizedHttpException
* @return IdentityInterface
*/
public static function findIdentityByAccessToken($token, $type = null): IdentityInterface {
if ($token === null) {
throw new UnauthorizedHttpException('Incorrect token');
}
// Speed-improved analogue of the `count(explode('.', $token)) === 3`
if (substr_count($token, '.') === 2) {
return JwtIdentity::findIdentityByAccessToken($token, $type);
}
/** @var AccessTokenEntity|null $model */
$model = Yii::$app->oauth->getAccessTokenStorage()->get($token);
if ($model === null) {
@ -65,6 +55,7 @@ class Identity implements IdentityInterface {
return $this->_accessToken->getId();
}
// @codeCoverageIgnoreStart
public function getAuthKey() {
throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth');
}
@ -77,8 +68,10 @@ class Identity 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()]);
}
}

View File

@ -1,30 +0,0 @@
<?php
namespace api\components\User;
use Emarref\Jwt\Claim\AbstractClaim;
class ScopesClaim extends AbstractClaim {
public const NAME = 'ely-scopes';
/**
* ScopesClaim constructor.
*
* @param array|string $value
*/
public function __construct($value = null) {
if (is_array($value)) {
$value = implode(',', $value);
}
parent::__construct($value);
}
/**
* @inheritdoc
*/
public function getName(): string {
return self::NAME;
}
}

View File

@ -1,28 +0,0 @@
<?php
namespace api\components\User;
use Emarref\Jwt\Claim\Subject;
use Emarref\Jwt\Exception\InvalidSubjectException;
use Emarref\Jwt\Token;
use Emarref\Jwt\Verification\VerifierInterface;
use yii\helpers\StringHelper;
class SubjectPrefixVerifier implements VerifierInterface {
private $subjectPrefix;
public function __construct(string $subjectPrefix) {
$this->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();
}
}
}

View File

@ -1,8 +1,11 @@
<?php
return [
'components' => [
'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',

View File

@ -10,7 +10,13 @@ return [
'components' => [
'user' => [
'class' => api\components\User\Component::class,
'secret' => getenv('JWT_USER_SECRET'),
],
'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,

View File

@ -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([

View File

@ -89,7 +89,7 @@ class SignupController extends Controller {
return array_merge([
'success' => true,
], $result->getAsResponse());
], $result->formatAsOAuth2Response());
}
}

View File

@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace api\models\authentication;
use Lcobucci\JWT\Token;
class AuthenticationResult {
/**
* @var Token
*/
private $token;
/**
* @var string|null
*/
private $refreshToken;
public function __construct(Token $token, string $refreshToken = null) {
$this->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;
}
}

View File

@ -4,12 +4,14 @@ 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\models\Account;
use common\models\AccountSession;
use common\models\EmailActivation;
use Webmozart\Assert\Assert;
use Yii;
use yii\base\ErrorException;
class ConfirmEmailForm extends ApiForm {
@ -23,12 +25,10 @@ class ConfirmEmailForm extends ApiForm {
/**
* @CollectModelMetrics(prefix="signup.confirmEmail")
* @return \api\components\User\AuthenticationResult|bool
* @throws ErrorException
*/
public function confirm() {
public function confirm(): ?AuthenticationResult {
if (!$this->validate()) {
return false;
return null;
}
$transaction = Yii::$app->db->beginTransaction();
@ -37,17 +37,22 @@ class ConfirmEmailForm extends ApiForm {
$confirmModel = $this->key;
$account = $confirmModel->account;
$account->status = Account::STATUS_ACTIVE;
if (!$confirmModel->delete()) {
throw new ErrorException('Unable remove activation key.');
}
/** @noinspection PhpUnhandledExceptionInspection */
Assert::notSame($confirmModel->delete(), false, 'Unable remove activation key.');
if (!$account->save()) {
throw new ErrorException('Unable activate user account.');
}
Assert::true($account->save(), 'Unable activate user account.');
$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');
$token = TokensFactory::createForAccount($account, $session);
$transaction->commit();
return Yii::$app->user->createJwtAuthenticationToken($account, true);
return new AuthenticationResult($token, $session->refresh_token);
}
}

View File

@ -1,12 +1,17 @@
<?php
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\traits\AccountFinder;
use api\validators\TotpValidator;
use common\helpers\Error as E;
use common\models\Account;
use common\models\AccountSession;
use Webmozart\Assert\Assert;
use Yii;
class LoginForm extends ApiForm {
@ -25,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'],
@ -41,15 +46,13 @@ class LoginForm extends ApiForm {
];
}
public function validateLogin($attribute) {
if (!$this->hasErrors()) {
if ($this->getAccount() === null) {
$this->addError($attribute, E::LOGIN_NOT_EXIST);
}
public function validateLogin(string $attribute): void {
if (!$this->hasErrors() && $this->getAccount() === null) {
$this->addError($attribute, E::LOGIN_NOT_EXIST);
}
}
public function validatePassword($attribute) {
public function validatePassword(string $attribute): void {
if (!$this->hasErrors()) {
$account = $this->getAccount();
if ($account === null || !$account->validatePassword($this->password)) {
@ -58,11 +61,12 @@ class LoginForm extends ApiForm {
}
}
public function validateTotp($attribute) {
public function validateTotp(string $attribute): void {
if ($this->hasErrors()) {
return;
}
/** @var Account $account */
$account = $this->getAccount();
if (!$account->is_otp_enabled) {
return;
@ -73,8 +77,9 @@ class LoginForm extends ApiForm {
$validator->validateAttribute($this, $attribute);
}
public function validateActivity($attribute) {
public function validateActivity(string $attribute): void {
if (!$this->hasErrors()) {
/** @var Account $account */
$account = $this->getAccount();
if ($account->status === Account::STATUS_BANNED) {
$this->addError($attribute, E::ACCOUNT_BANNED);
@ -92,20 +97,35 @@ class LoginForm extends ApiForm {
/**
* @CollectModelMetrics(prefix="authentication.login")
* @return \api\components\User\AuthenticationResult|bool
*/
public function login() {
public function login(): ?AuthenticationResult {
if (!$this->validate()) {
return false;
return null;
}
$transaction = Yii::$app->db->beginTransaction();
/** @var Account $account */
$account = $this->getAccount();
if ($account->password_hash_strategy !== Account::PASS_HASH_STRATEGY_YII2) {
$account->setPassword($this->password);
$account->save();
Assert::true($account->save(), 'Unable to upgrade user\'s password');
}
return Yii::$app->user->createJwtAuthenticationToken($account, $this->rememberMe);
$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');
}
$token = TokensFactory::createForAccount($account, $session);
$transaction->commit();
return new AuthenticationResult($token, $session ? $session->refresh_token : null);
}
}

View File

@ -1,14 +1,17 @@
<?php
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;
use common\models\EmailActivation;
use common\validators\PasswordValidator;
use Webmozart\Assert\Assert;
use Yii;
use yii\base\ErrorException;
class RecoverPasswordForm extends ApiForm {
@ -18,7 +21,7 @@ class RecoverPasswordForm extends ApiForm {
public $newRePassword;
public function rules() {
public function rules(): array {
return [
['key', EmailActivationKeyValidator::class, 'type' => EmailActivation::TYPE_FORGOT_PASSWORD_KEY],
['newPassword', 'required', 'message' => E::NEW_PASSWORD_REQUIRED],
@ -28,22 +31,18 @@ class RecoverPasswordForm extends ApiForm {
];
}
public function validatePasswordAndRePasswordMatch($attribute) {
if (!$this->hasErrors()) {
if ($this->newPassword !== $this->newRePassword) {
$this->addError($attribute, E::NEW_RE_PASSWORD_DOES_NOT_MATCH);
}
public function validatePasswordAndRePasswordMatch(string $attribute): void {
if (!$this->hasErrors() && $this->newPassword !== $this->newRePassword) {
$this->addError($attribute, E::NEW_RE_PASSWORD_DOES_NOT_MATCH);
}
}
/**
* @CollectModelMetrics(prefix="authentication.recoverPassword")
* @return \api\components\User\AuthenticationResult|bool
* @throws ErrorException
*/
public function recoverPassword() {
public function recoverPassword(): ?AuthenticationResult {
if (!$this->validate()) {
return false;
return null;
}
$transaction = Yii::$app->db->beginTransaction();
@ -52,17 +51,16 @@ class RecoverPasswordForm extends ApiForm {
$confirmModel = $this->key;
$account = $confirmModel->account;
$account->password = $this->newPassword;
if (!$confirmModel->delete()) {
throw new ErrorException('Unable remove activation key.');
}
/** @noinspection PhpUnhandledExceptionInspection */
Assert::notSame($confirmModel->delete(), false, 'Unable remove activation key.');
if (!$account->save(false)) {
throw new ErrorException('Unable activate user account.');
}
Assert::true($account->save(), 'Unable activate user account.');
$token = TokensFactory::createForAccount($account);
$transaction->commit();
return Yii::$app->user->createJwtAuthenticationToken($account, false);
return new AuthenticationResult($token);
}
}

View File

@ -1,10 +1,14 @@
<?php
declare(strict_types=1);
namespace api\models\authentication;
use api\aop\annotations\CollectModelMetrics;
use api\components\Tokens\TokensFactory;
use api\models\base\ApiForm;
use common\helpers\Error as E;
use common\models\AccountSession;
use Webmozart\Assert\Assert;
use Yii;
class RefreshTokenForm extends ApiForm {
@ -16,41 +20,45 @@ class RefreshTokenForm extends ApiForm {
*/
private $session;
public function rules() {
public function rules(): array {
return [
['refresh_token', 'required', 'message' => 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]);
}

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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;

38
api/rbac/Manager.php Normal file
View File

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace api\rbac;
use Yii;
use yii\rbac\Assignment;
use yii\rbac\PhpManager;
class Manager extends PhpManager {
/**
* In our application the permissions are given not to users itself, but to tokens,
* so we extract them from the extended identity interface.
*
* In Yii2, the mechanism of recursive permissions checking requires that the array
* with permissions must be indexed by the keys of these permissions.
*
* @param string $accessToken
* @return string[]
*/
public function getAssignments($accessToken): array {
$identity = Yii::$app->user->getIdentity();
if ($identity === null) {
return [];
}
/** @noinspection NullPointerExceptionInspection */
$rawPermissions = $identity->getAssignedPermissions();
$result = [];
foreach ($rawPermissions as $name) {
$result[$name] = new Assignment(['roleName' => $name]);
}
return $result;
}
}

View File

@ -1,5 +1,7 @@
<?php
namespace common\rbac;
declare(strict_types=1);
namespace api\rbac;
final class Permissions {

View File

@ -1,5 +1,7 @@
<?php
namespace common\rbac;
declare(strict_types=1);
namespace api\rbac;
final class Roles {

View File

@ -1,7 +1,10 @@
<?php
namespace common\rbac\rules;
declare(strict_types=1);
namespace api\rbac\rules;
use common\models\Account;
use Webmozart\Assert\Assert;
use Yii;
use yii\rbac\Rule;
@ -23,12 +26,10 @@ class AccountOwner extends Rule {
* @return bool a value indicating whether the rule permits the auth item it is associated with.
*/
public function execute($accessToken, $item, $params): bool {
Assert::keyExists($params, 'accountId');
$accountId = $params['accountId'] ?? null;
if ($accountId === null) {
return false;
}
$identity = Yii::$app->user->findIdentityByAccessToken($accessToken);
$identity = Yii::$app->user->getIdentity();
if ($identity === null) {
return false;
}

View File

@ -1,10 +1,11 @@
<?php
declare(strict_types=1);
namespace common\rbac\rules;
namespace api\rbac\rules;
use api\rbac\Permissions as P;
use common\models\OauthClient;
use common\rbac\Permissions as P;
use Webmozart\Assert\Assert;
use Yii;
use yii\rbac\Rule;
@ -30,18 +31,14 @@ class OauthClientOwner extends Rule {
return (new AccountOwner())->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;
}

View File

@ -0,0 +1,5 @@
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIKrv4e6B9XP7l8F94ZMJotA+7FtjK7k9/olQi7Eb2tgmoAoGCCqGSM49
AwEHoUQDQgAES2Pyq9r0CyyviLaWwq0ki5uy8hr/ZbNO++3j4XP43uLD9/GYkrKG
IRl+Hu5HT+LwZvrFcEaVhPk5CvtV4zlYJg==
-----END EC PRIVATE KEY-----

View File

@ -0,0 +1,4 @@
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAES2Pyq9r0CyyviLaWwq0ki5uy8hr/
ZbNO++3j4XP43uLD9/GYkrKGIRl+Hu5HT+LwZvrFcEaVhPk5CvtV4zlYJg==
-----END PUBLIC KEY-----

View File

@ -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,15 +13,15 @@ use Yii;
class FunctionalTester extends Actor {
use FunctionalTesterActions;
public function amAuthenticated(string $asUsername = 'admin') {
public function amAuthenticated(string $asUsername = 'admin') { // Do not declare type
/** @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}\"");
}
$result = Yii::$app->user->createJwtAuthenticationToken($account, false);
$this->amBearerAuthenticated($result->getJwt());
$token = TokensFactory::createForAccount($account);
$this->amBearerAuthenticated((string)$token);
return $account->id;
}
@ -30,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');

View File

@ -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([

View File

@ -1,9 +1,9 @@
<?php
namespace api\tests\functional\_steps;
use api\rbac\Permissions as P;
use api\tests\_pages\SessionServerRoute;
use api\tests\FunctionalTester;
use common\rbac\Permissions as P;
use Faker\Provider\Uuid;
class SessionServerSteps extends FunctionalTester {

View File

@ -1,10 +1,10 @@
<?php
namespace api\tests\functional\accounts;
use api\rbac\Permissions as P;
use api\tests\_pages\AccountsRoute;
use api\tests\functional\_steps\OauthSteps;
use api\tests\FunctionalTester;
use common\rbac\Permissions as P;
class BanCest {

View File

@ -1,10 +1,10 @@
<?php
namespace api\tests\functional\accounts;
use api\rbac\Permissions as P;
use api\tests\_pages\AccountsRoute;
use api\tests\functional\_steps\OauthSteps;
use api\tests\FunctionalTester;
use common\rbac\Permissions as P;
class PardonCest {

View File

@ -1,9 +1,9 @@
<?php
namespace api\tests\functional\oauth;
use api\rbac\Permissions as P;
use api\tests\_pages\OauthRoute;
use api\tests\FunctionalTester;
use common\rbac\Permissions as P;
class AuthCodeCest {

View File

@ -2,10 +2,10 @@
namespace api\tests\functional\oauth;
use api\components\OAuth2\Storage\ScopeStorage as S;
use api\rbac\Permissions as P;
use api\tests\_pages\OauthRoute;
use api\tests\functional\_steps\OauthSteps;
use api\tests\FunctionalTester;
use common\rbac\Permissions as P;
class RefreshTokenCest {

View File

@ -1,11 +1,11 @@
<?php
namespace api\tests\functional\sessionserver;
use api\rbac\Permissions as P;
use api\tests\_pages\SessionServerRoute;
use api\tests\functional\_steps\AuthserverSteps;
use api\tests\functional\_steps\OauthSteps;
use api\tests\FunctionalTester;
use common\rbac\Permissions as P;
use Faker\Provider\Uuid;
class JoinCest {

View File

@ -1,11 +1,11 @@
<?php
namespace api\tests\functional\sessionserver;
use api\rbac\Permissions as P;
use api\tests\_pages\SessionServerRoute;
use api\tests\functional\_steps\AuthserverSteps;
use api\tests\functional\_steps\OauthSteps;
use api\tests\FunctionalTester;
use common\rbac\Permissions as P;
use Faker\Provider\Uuid;
class JoinLegacyCest {

View File

@ -13,7 +13,7 @@ class TestCase extends Unit {
*/
protected $tester;
protected function tearDown() {
protected function tearDown(): void {
parent::tearDown();
Mockery::close();
}

View File

@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace api\tests\unit\components\Tokens;
use api\tests\unit\TestCase;
use InvalidArgumentException;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Token;
use Yii;
class ComponentTest extends TestCase {
/**
* @var \api\components\Tokens\Component
*/
private $component;
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,
];
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() {
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'));
$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'));
}
}

View File

@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace api\tests\unit\components\Tokens;
use api\components\Tokens\TokensFactory;
use api\tests\unit\TestCase;
use common\models\Account;
use common\models\AccountSession;
class TokensFactoryTest extends TestCase {
public function testCreateForAccount() {
$account = new Account();
$account->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'));
}
}

View File

@ -1,24 +1,21 @@
<?php
declare(strict_types=1);
namespace codeception\api\unit\components\User;
use api\components\User\AuthenticationResult;
use api\components\User\Component;
use api\components\User\Identity;
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\_support\ProtectedCaller;
use common\tests\fixtures\AccountFixture;
use common\tests\fixtures\AccountSessionFixture;
use common\tests\fixtures\MinecraftAccessKeyFixture;
use Emarref\Jwt\Claim;
use Emarref\Jwt\Jwt;
use Emarref\Jwt\Token;
use Yii;
use yii\web\Request;
use Lcobucci\JWT\Claim\Basic;
use Lcobucci\JWT\Token;
class ComponentTest extends TestCase {
use ProtectedCaller;
/**
* @var Component|\PHPUnit\Framework\MockObject\MockObject
@ -27,7 +24,7 @@ class ComponentTest extends TestCase {
public function _before() {
parent::_before();
$this->component = new Component($this->getComponentConfig());
$this->component = new Component();
}
public function _fixtures(): array {
@ -38,158 +35,70 @@ class ComponentTest extends TestCase {
];
}
public function testCreateJwtAuthenticationToken() {
$this->mockRequest();
$account = new Account(['id' => 1]);
$result = $this->component->createJwtAuthenticationToken($account, false);
$this->assertInstanceOf(AuthenticationResult::class, $result);
$this->assertNull($result->getSession());
$this->assertSame($account, $result->getAccount());
$payloads = (new Jwt())->deserialize($result->getJwt())->getPayload();
/** @noinspection NullPointerExceptionInspection */
$this->assertEqualsWithDelta(time(), $payloads->findClaimByName(Claim\IssuedAt::NAME)->getValue(), 3);
/** @noinspection SummerTimeUnsafeTimeManipulationInspection */
/** @noinspection NullPointerExceptionInspection */
$this->assertEqualsWithDelta(time() + 60 * 60 * 24 * 7, $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());
$this->assertNull($payloads->findClaimByName('jti'));
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
$result = $this->component->createJwtAuthenticationToken($account, true);
$this->assertInstanceOf(AuthenticationResult::class, $result);
$this->assertInstanceOf(AccountSession::class, $result->getSession());
$this->assertSame($account, $result->getAccount());
/** @noinspection NullPointerExceptionInspection */
$this->assertTrue($result->getSession()->refresh());
$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($result->getSession()->id, $payloads->findClaimByName('jti')->getValue());
}
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 testParseToken() {
$this->mockRequest();
$token = $this->callProtected($this->component, 'createToken', new Account(['id' => 1]));
$jwt = $this->callProtected($this->component, 'serializeToken', $token);
$this->assertInstanceOf(Token::class, $this->component->parseToken($jwt), 'success get RenewResult object');
}
public function testGetActiveSession() {
$account = $this->tester->grabFixture('accounts', 'admin');
$result = $this->component->createJwtAuthenticationToken($account, true);
$this->component->logout();
// User is guest
$component = new Component();
$this->assertNull($component->getActiveSession());
/** @var Component|\PHPUnit\Framework\MockObject\MockObject $component */
$component = $this->getMockBuilder(Component::class)
->setMethods(['getIsGuest'])
->setConstructorArgs([$this->getComponentConfig()])
->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($result->getJwt());
// 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());
// 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->assertInstanceOf(AccountSession::class, $session);
/** @noinspection NullPointerExceptionInspection */
$this->assertSame($session->id, $result->getSession()->id);
$this->assertNotNull($session);
$this->assertSame(1, $session->id);
}
public function testTerminateSessions() {
/** @var AccountSession $session */
$session = AccountSession::findOne($this->tester->grabFixture('sessions', 'admin2')['id']);
$session = $this->tester->grabFixture('sessions', 'admin2');
/** @var Component|\Mockery\MockInterface $component */
$component = mock(Component::class . '[getActiveSession]', [$this->getComponentConfig()])->shouldDeferMissing();
$component = mock(Component::class . '[getActiveSession]')->makePartial();
$component->shouldReceive('getActiveSession')->times(1)->andReturn($session);
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
$component->createJwtAuthenticationToken($account, true);
// Dry run: no sessions should be removed
$component->terminateSessions($account, Component::KEEP_MINECRAFT_SESSIONS | Component::KEEP_SITE_SESSIONS);
$this->assertNotEmpty($account->getMinecraftAccessKeys()->all());
$this->assertNotEmpty($account->getSessions()->all());
// All Minecraft sessions should be removed. Web sessions should be kept
$component->terminateSessions($account, Component::KEEP_SITE_SESSIONS);
$this->assertEmpty($account->getMinecraftAccessKeys()->all());
$this->assertNotEmpty($account->getSessions()->all());
// All sessions should be removed except the current one
$component->terminateSessions($account, Component::KEEP_CURRENT_SESSION);
$sessions = $account->getSessions()->all();
$this->assertCount(1, $sessions);
$this->assertSame($session->id, $sessions[0]->id);
// With no arguments each and every session should be removed
$component->terminateSessions($account);
$this->assertEmpty($account->getSessions()->all());
$this->assertEmpty($account->getMinecraftAccessKeys()->all());
}
private function mockRequest($userIP = '127.0.0.1') {
/** @var Request|\Mockery\MockInterface $request */
$request = mock(Request::class . '[getHostInfo,getUserIP]')->shouldDeferMissing();
$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);
}
private function getComponentConfig() {
return [
'identityClass' => Identity::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',
];
}
}

View File

@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace api\tests\unit\components\User;
use api\components\OAuth2\Component;
use api\components\OAuth2\Entities\AccessTokenEntity;
use api\components\User\IdentityFactory;
use api\components\User\JwtIdentity;
use api\components\User\OAuth2Identity;
use api\tests\unit\TestCase;
use Carbon\Carbon;
use League\OAuth2\Server\AbstractServer;
use League\OAuth2\Server\Storage\AccessTokenInterface;
use Yii;
use yii\web\UnauthorizedHttpException;
class IdentityFactoryTest extends TestCase {
public function testFindIdentityByAccessToken() {
// Find identity by jwt token
$identity = IdentityFactory::findIdentityByAccessToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ.4Oidvuo4spvUf9hkpHR72eeqZUh2Zbxh_L8Od3vcgTj--0iOrcOEp6zwmEW6vF7BTHtjz2b3mXce61bqsCjXjQ');
$this->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();
}
}

View File

@ -1,63 +0,0 @@
<?php
namespace api\tests\unit\components\User;
use api\components\User\AuthenticationResult;
use api\tests\unit\TestCase;
use common\models\Account;
use common\models\AccountSession;
use Emarref\Jwt\Algorithm\Hs256;
use Emarref\Jwt\Claim\Expiration;
use Emarref\Jwt\Encryption\Factory as EncryptionFactory;
use Emarref\Jwt\Jwt;
use Emarref\Jwt\Token;
class JwtAuthenticationResultTest extends TestCase {
public function testGetAccount() {
$account = new Account();
$account->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')));
}
}

View File

@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
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 yii\web\UnauthorizedHttpException;
class JwtIdentityTest extends TestCase {
public function _fixtures(): array {
return [
'accounts' => AccountFixture::class,
];
}
public function testFindIdentityByAccessToken() {
$token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ.4Oidvuo4spvUf9hkpHR72eeqZUh2Zbxh_L8Od3vcgTj--0iOrcOEp6zwmEW6vF7BTHtjz2b3mXce61bqsCjXjQ';
/** @var JwtIdentity $identity */
$identity = JwtIdentity::findIdentityByAccessToken($token);
$this->assertSame($token, $identity->getId());
$this->assertSame($token, (string)$identity->getToken());
/** @var \common\models\Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
$this->assertSame($account->id, $identity->getAccount()->id);
}
/**
* @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();
}
}

View File

@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace api\tests\unit\components\User;
use api\components\OAuth2\Component;
use api\components\OAuth2\Entities\AccessTokenEntity;
use api\components\User\OAuth2Identity;
use api\tests\unit\TestCase;
use League\OAuth2\Server\AbstractServer;
use League\OAuth2\Server\Storage\AccessTokenInterface;
use Yii;
use yii\web\UnauthorizedHttpException;
class OAuth2IdentityTest extends TestCase {
public function testFindIdentityByAccessToken() {
$accessToken = new AccessTokenEntity(mock(AbstractServer::class));
$accessToken->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);
}
}

View File

@ -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);
}
}

View File

@ -1,62 +0,0 @@
<?php
namespace codeception\api\unit\models;
use api\components\User\Jwt;
use api\components\User\JwtIdentity;
use api\tests\unit\TestCase;
use common\tests\_support\ProtectedCaller;
use common\tests\fixtures\AccountFixture;
use Emarref\Jwt\Claim;
use Emarref\Jwt\Encryption\Factory as EncryptionFactory;
use Emarref\Jwt\Token;
use Yii;
class JwtIdentityTest extends TestCase {
use ProtectedCaller;
public function _fixtures(): array {
return [
'accounts' => AccountFixture::class,
];
}
public function testFindIdentityByAccessToken() {
$token = $this->generateToken();
$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() {
$token = new Token();
$token->addClaim(new Claim\IssuedAt(1464593193));
$token->addClaim(new Claim\Expiration(1464596793));
$token->addClaim(new Claim\Subject('ely|' . $this->tester->grabFixture('accounts', 'admin')['id']));
$expiredToken = (new Jwt())->serialize($token, EncryptionFactory::create(Yii::$app->user->getAlgorithm()));
JwtIdentity::findIdentityByAccessToken($expiredToken);
}
/**
* @expectedException \yii\web\UnauthorizedHttpException
* @expectedExceptionMessage Incorrect token
*/
public function testFindIdentityByAccessTokenWithEmptyToken() {
JwtIdentity::findIdentityByAccessToken('');
}
protected function generateToken() {
/** @var \api\components\User\Component $component */
$component = Yii::$app->user;
/** @var \common\models\Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
$token = $this->callProtected($component, 'createToken', $account);
return $this->callProtected($component, 'serializeToken', $token);
}
}

View File

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace api\tests\unit\models\authentication;
use api\models\authentication\AuthenticationResult;
use api\tests\unit\TestCase;
use Lcobucci\JWT\Token;
use Yii;
class AuthenticationResultTest extends TestCase {
public function testGetters() {
$token = new Token();
$model = new AuthenticationResult($token);
$this->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']);
}
}

View File

@ -1,11 +1,11 @@
<?php
declare(strict_types=1);
namespace api\tests\_support\models\authentication;
use api\components\User\AuthenticationResult;
use api\models\authentication\ConfirmEmailForm;
use api\tests\unit\TestCase;
use common\models\Account;
use common\models\AccountSession;
use common\models\EmailActivation;
use common\tests\fixtures\EmailActivationFixture;
@ -21,8 +21,8 @@ class ConfirmEmailFormTest extends TestCase {
$fixture = $this->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 */

View File

@ -1,4 +1,6 @@
<?php
declare(strict_types=1);
namespace codeception\api\unit\models\authentication;
use api\components\ReCaptcha\Validator as ReCaptchaValidator;
@ -14,7 +16,7 @@ use Yii;
class ForgotPasswordFormTest extends TestCase {
protected function setUp() {
protected function setUp(): void {
parent::setUp();
Yii::$container->set(ReCaptchaValidator::class, new class(mock(ClientInterface::class)) extends ReCaptchaValidator {
public function validateValue($value) {

View File

@ -1,7 +1,8 @@
<?php
declare(strict_types=1);
namespace api\tests\_support\models\authentication;
use api\components\User\AuthenticationResult;
use api\models\authentication\LoginForm;
use api\tests\unit\TestCase;
use Codeception\Specify;
@ -14,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;
}
@ -135,7 +136,7 @@ class LoginFormTest extends TestCase {
'status' => 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,

View File

@ -1,8 +1,9 @@
<?php
declare(strict_types=1);
namespace api\tests\_support\models\authentication;
use api\components\User\Component;
use api\components\User\Identity;
use api\models\authentication\LogoutForm;
use api\tests\unit\TestCase;
use Codeception\Specify;
@ -16,7 +17,6 @@ class LogoutFormTest extends TestCase {
$this->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,13 +56,4 @@ class LogoutFormTest extends TestCase {
});
}
private function getComponentArgs() {
return [
'identityClass' => Identity::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',
];
}
}

View File

@ -1,7 +1,8 @@
<?php
declare(strict_types=1);
namespace api\tests\_support\models\authentication;
use api\components\User\AuthenticationResult;
use api\models\authentication\RecoverPasswordForm;
use api\tests\unit\TestCase;
use common\models\Account;
@ -24,8 +25,8 @@ class RecoverPasswordFormTest extends TestCase {
'newRePassword' => '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']);

View File

@ -1,12 +1,15 @@
<?php
declare(strict_types=1);
namespace codeception\api\unit\models\authentication;
use api\components\User\AuthenticationResult;
use api\models\authentication\RefreshTokenForm;
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;
@ -17,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->assertInstanceOf(AuthenticationResult::class, $model->renew());
$model->refresh_token = 'unknown refresh token';
$this->assertNull($model->renew());
$this->assertSame(['error.refresh_token_not_exist'], $model->getErrors('refresh_token'));
}
}

View File

@ -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 {

View File

@ -1,4 +1,6 @@
<?php
declare(strict_types=1);
namespace api\tests\_support\models\authentication;
use api\components\ReCaptcha\Validator as ReCaptchaValidator;
@ -15,7 +17,7 @@ use Yii;
class RepeatAccountActivationFormTest extends TestCase {
use Specify;
protected function setUp() {
protected function setUp(): void {
parent::setUp();
Yii::$container->set(ReCaptchaValidator::class, new class(mock(ClientInterface::class)) extends ReCaptchaValidator {
public function validateValue($value) {

View File

@ -1,8 +1,9 @@
<?php
declare(strict_types=1);
namespace api\tests\unit\modules\accounts\models;
use api\components\User\Component;
use api\components\User\Identity;
use api\modules\accounts\models\ChangePasswordForm;
use api\tests\unit\TestCase;
use common\components\UserPass;
@ -56,12 +57,7 @@ class ChangePasswordFormTest extends TestCase {
}
public function testPerformAction() {
$component = mock(Component::class . '[terminateSessions]', [[
'identityClass' => Identity::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',
]]);
$component = mock(Component::class . '[terminateSessions]');
$component->shouldNotReceive('terminateSessions');
Yii::$app->set('user', $component);
@ -116,12 +112,7 @@ class ChangePasswordFormTest extends TestCase {
$account->setPassword('password_0');
/** @var Component|\Mockery\MockInterface $component */
$component = mock(Component::class . '[terminateSessions]', [[
'identityClass' => Identity::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',
]]);
$component = mock(Component::class . '[terminateSessions]');
$component->shouldReceive('terminateSessions')->once()->withArgs([$account, Component::KEEP_CURRENT_SESSION]);
Yii::$app->set('user', $component);

View File

@ -1,8 +1,9 @@
<?php
declare(strict_types=1);
namespace api\tests\unit\modules\accounts\models;
use api\components\User\Component;
use api\components\User\Identity;
use api\modules\accounts\models\EnableTwoFactorAuthForm;
use api\tests\unit\TestCase;
use common\helpers\Error as E;
@ -19,12 +20,7 @@ class EnableTwoFactorAuthFormTest extends TestCase {
$account->otp_secret = 'mock secret';
/** @var Component|\Mockery\MockInterface $component */
$component = mock(Component::class . '[terminateSessions]', [[
'identityClass' => Identity::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',
]]);
$component = mock(Component::class . '[terminateSessions]');
$component->shouldReceive('terminateSessions')->withArgs([$account, Component::KEEP_CURRENT_SESSION]);
Yii::$app->set('user', $component);

View File

@ -1,7 +1,10 @@
<?php
declare(strict_types=1);
namespace codeception\api\unit\modules\authserver\models;
use api\models\authentication\LoginForm;
use api\modules\authserver\exceptions\ForbiddenOperationException;
use api\modules\authserver\models\AuthenticateData;
use api\modules\authserver\models\AuthenticationForm;
use api\tests\unit\TestCase;
@ -22,11 +25,10 @@ class AuthenticationFormTest extends TestCase {
];
}
/**
* @expectedException \api\modules\authserver\exceptions\ForbiddenOperationException
* @expectedExceptionMessage Invalid credentials. Invalid nickname or password.
*/
public function testAuthenticateByWrongNicknamePass() {
$this->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;
}

View File

@ -1,6 +1,9 @@
<?php
declare(strict_types=1);
namespace codeception\api\unit\modules\authserver\validators;
use api\modules\authserver\exceptions\IllegalArgumentException;
use api\modules\authserver\validators\RequiredValidator;
use api\tests\unit\TestCase;
use common\tests\_support\ProtectedCaller;
@ -13,10 +16,9 @@ class RequiredValidatorTest extends TestCase {
$this->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', ''));
}

View File

@ -1,6 +1,9 @@
<?php
declare(strict_types=1);
namespace api\tests\unit\modules\oauth\models;
use api\modules\oauth\exceptions\UnsupportedOauthClientType;
use api\modules\oauth\models\ApplicationType;
use api\modules\oauth\models\MinecraftServerType;
use api\modules\oauth\models\OauthClientFormFactory;
@ -37,10 +40,9 @@ class OauthClientFormFactoryTest extends TestCase {
$this->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);

View File

@ -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'])

View File

@ -1,46 +1,46 @@
<?php
namespace common\tests\unit\rbac\rules;
declare(strict_types=1);
namespace api\tests\unit\rbac\rules;
use api\components\User\Component;
use api\components\User\IdentityInterface;
use api\rbac\rules\AccountOwner;
use common\models\Account;
use common\rbac\rules\AccountOwner;
use common\tests\unit\TestCase;
use InvalidArgumentException;
use Yii;
use yii\rbac\Item;
use const common\LATEST_RULES_VERSION;
class AccountOwnerTest extends TestCase {
public function testIdentityIsNull() {
$component = mock(Component::class . '[findIdentityByAccessToken]', [['secret' => 'secret']]);
$component->shouldDeferMissing();
$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]', [['secret' => 'secret']]);
$component->shouldDeferMissing();
$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]));
@ -54,4 +54,11 @@ class AccountOwnerTest extends TestCase {
$this->assertFalse($rule->execute('token', $item, ['accountId' => 1, 'optionalRules' => true]));
}
public function testExecuteWithoutAccountId() {
$this->expectException(InvalidArgumentException::class);
$rule = new AccountOwner();
$this->assertFalse($rule->execute('token', new Item(), []));
}
}

View File

@ -1,13 +1,15 @@
<?php
namespace common\tests\unit\rbac\rules;
declare(strict_types=1);
namespace api\tests\unit\rbac\rules;
use api\components\User\Component;
use api\components\User\IdentityInterface;
use api\rbac\Permissions as P;
use api\rbac\rules\OauthClientOwner;
use common\models\Account;
use common\rbac\Permissions as P;
use common\rbac\rules\OauthClientOwner;
use common\tests\fixtures\OauthClientFixture;
use common\tests\unit\TestCase;
use InvalidArgumentException;
use Yii;
use yii\rbac\Item;
use const common\LATEST_RULES_VERSION;
@ -24,6 +26,21 @@ class OauthClientOwnerTest extends TestCase {
$rule = new OauthClientOwner();
$item = new Item();
// Client not exists (we expect true to let controller throw corresponding 404 exception)
$this->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;
@ -32,15 +49,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]', [['secret' => 'secret']]);
$component->shouldDeferMissing();
$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;
@ -50,4 +60,11 @@ class OauthClientOwnerTest extends TestCase {
$this->assertFalse($rule->execute('token', $item, ['accountId' => 1]));
}
public function testExecuteWithoutClientId() {
$this->expectException(InvalidArgumentException::class);
$rule = new OauthClientOwner();
$this->assertFalse($rule->execute('token', new Item(), []));
}
}

View File

@ -1,11 +1,11 @@
<?php
namespace codeception\api\unit\validators;
use api\rbac\Permissions as P;
use api\tests\unit\TestCase;
use api\validators\PasswordRequiredValidator;
use common\helpers\Error as E;
use common\models\Account;
use common\rbac\Permissions as P;
use common\tests\_support\ProtectedCaller;
use yii\web\User;

View File

@ -1,9 +1,9 @@
<?php
namespace api\validators;
use api\rbac\Permissions as P;
use common\helpers\Error as E;
use common\models\Account;
use common\rbac\Permissions as P;
use yii\base\InvalidConfigException;
use yii\di\Instance;
use yii\validators\Validator;

View File

@ -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 {
}

View File

@ -17,5 +17,6 @@ coverage:
exclude:
- config/*
- mail/*
- tests/*
- codeception.dist.yml
- codeception.yml

View File

@ -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,

View File

@ -98,9 +98,9 @@ return [
'class' => api\components\OAuth2\Component::class,
],
'authManager' => [
'class' => common\rbac\Manager::class,
'itemFile' => '@common/rbac/.generated/items.php',
'ruleFile' => '@common/rbac/.generated/rules.php',
'class' => \api\rbac\Manager::class,
'itemFile' => '@api/rbac/.generated/items.php',
'ruleFile' => '@api/rbac/.generated/rules.php',
],
'statsd' => [
'class' => common\components\StatsD::class,

View File

@ -1,34 +0,0 @@
<?php
namespace common\rbac;
use Yii;
use yii\rbac\PhpManager;
class Manager extends PhpManager {
/**
* In our application the permissions are given not to users but to tokens,
* so we receive $accessToken here and extract all the assigned scopes from it.
*
* In Yii2, the mechanism of recursive permissions checking requires that the array with permissions
* is indexed by the keys of these rights, so at the end we turn the array inside out.
*
* @param string $accessToken
* @return string[]
*/
public function getAssignments($accessToken): array {
$identity = Yii::$app->user->findIdentityByAccessToken($accessToken);
if ($identity === null) {
return [];
}
/** @noinspection NullPointerExceptionInspection */
$permissions = $identity->getAssignedPermissions();
if (empty($permissions)) {
return [];
}
return array_flip($permissions);
}
}

View File

@ -13,7 +13,7 @@ class TestCase extends Unit {
*/
protected $tester;
protected function tearDown() {
protected function tearDown(): void {
parent::tearDown();
Mockery::close();
}

View File

@ -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);

View File

@ -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() {

View File

@ -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';

View File

@ -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();

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -16,11 +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",
@ -31,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",
@ -46,7 +47,8 @@
"symfony/polyfill-ctype": "*",
"symfony/polyfill-mbstring": "*",
"symfony/polyfill-php70": "*",
"symfony/polyfill-php72": "*"
"symfony/polyfill-php72": "*",
"symfony/polyfill-php73": "*"
},
"repositories": [
{

940
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -18,6 +18,7 @@ coverage:
- config/*
- runtime/*
- migrations/*
- tests/*
- views/*
- codeception.dist.yml
- codeception.yml

View File

@ -1,13 +1,14 @@
<?php
declare(strict_types=1);
namespace console\controllers;
use common\rbac\Permissions as P;
use common\rbac\Roles as R;
use common\rbac\rules\AccountOwner;
use common\rbac\rules\OauthClientOwner;
use InvalidArgumentException;
use api\rbac\Permissions as P;
use api\rbac\Roles as R;
use api\rbac\rules\AccountOwner;
use api\rbac\rules\OauthClientOwner;
use Webmozart\Assert\Assert;
use Yii;
use yii\base\ErrorException;
use yii\console\Controller;
use yii\rbac\ManagerInterface;
use yii\rbac\Permission;
@ -84,9 +85,7 @@ class RbacController extends Controller {
private function createRole(string $name): Role {
$authManager = $this->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;
}

1
data/.gitignore vendored
View File

@ -1,2 +1,3 @@
*
!certs/*
!.gitignore

5
data/certs/private.pem Normal file
View File

@ -0,0 +1,5 @@
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIJ5ERywpRs5Rxn3JsSBhQTkzyYShmbKk1ziwif6yeBRooAoGCCqGSM49
AwEHoUQDQgAEv6ENZA59mzFvoDKTX3BI3Nx6di+xWnsOAo9+zx0hnMnfzdhOS930
ocFTBcyZmmF7iM7nhGicfiDfJKIyV8w+BA==
-----END EC PRIVATE KEY-----

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