Fixed almost everything, but all functional tests are broken at the last minute :(

This commit is contained in:
ErickSkrauch
2019-08-02 03:29:20 +03:00
parent 6bd054e743
commit f2ab7346aa
45 changed files with 504 additions and 377 deletions

View File

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

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

@@ -3,6 +3,7 @@ declare(strict_types=1);
namespace api\components\Tokens;
use Carbon\Carbon;
use Exception;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
@@ -11,8 +12,6 @@ use yii\base\Component as BaseComponent;
class Component extends BaseComponent {
private const EXPIRATION_TIMEOUT = 3600; // 1h
private const PREFERRED_ALGORITHM = 'ES256';
/**
@@ -41,10 +40,10 @@ class Component extends BaseComponent {
private $algorithmManager;
public function create(array $payloads = [], array $headers = []): Token {
$time = time();
$now = Carbon::now();
$builder = (new Builder())
->issuedAt($time)
->expiresAt($time + self::EXPIRATION_TIMEOUT);
->issuedAt($now->getTimestamp())
->expiresAt($now->addHour()->getTimestamp());
foreach ($payloads as $claim => $value) {
$builder->withClaim($claim, $value);
}

View File

@@ -3,6 +3,7 @@ declare(strict_types=1);
namespace api\components\Tokens;
use Carbon\Carbon;
use common\models\Account;
use common\models\AccountSession;
use Lcobucci\JWT\Token;
@@ -20,7 +21,7 @@ class TokensFactory {
if ($session === null) {
// If we don't remember a session, the token should live longer
// so that the session doesn't end while working with the account
$payloads['exp'] = time() + 60 * 60 * 24 * 7; // 7d
$payloads['exp'] = Carbon::now()->addDays(7)->getTimestamp();
} else {
$payloads['jti'] = $session->id;
}

View File

@@ -5,10 +5,6 @@ namespace api\components\User;
use common\models\Account;
use common\models\AccountSession;
use Exception;
use InvalidArgumentException;
use Yii;
use yii\web\UnauthorizedHttpException;
use yii\web\User as YiiUserComponent;
/**
@@ -38,29 +34,11 @@ class Component extends YiiUserComponent {
*/
public $identityClass = IdentityFactory::class;
public function findIdentityByAccessToken($accessToken): ?IdentityInterface {
if (empty($accessToken)) {
return null;
}
try {
return IdentityFactory::findIdentityByAccessToken($accessToken);
} catch (UnauthorizedHttpException $e) {
// TODO: if this exception is catched there, how it forms "Token expired" exception?
// Do nothing. It's okay to catch this.
} catch (Exception $e) {
Yii::error($e);
}
return null;
}
/**
* The method searches AccountSession model, which one has been used to create current JWT token.
* null will be returned in case when any of the following situations occurred:
* - The user isn't authorized
* - There is no header with a token
* - Token validation isn't passed and some exception has been thrown
* - The user isn't authorized via JWT token
* - No session key found in the token. This is possible if the user chose not to remember me
* or just some old tokens, without the support of saving the used session
*
@@ -71,18 +49,13 @@ class Component extends YiiUserComponent {
return null;
}
$bearer = $this->getBearerToken();
if ($bearer === null) {
/** @var IdentityInterface $identity */
$identity = $this->getIdentity();
if (!$identity instanceof JwtIdentity) {
return null;
}
try {
$token = Yii::$app->tokens->parse($bearer);
} catch (InvalidArgumentException $e) {
return null;
}
$sessionId = $token->getClaim('jti', false);
$sessionId = $identity->getToken()->getClaim('jti', false);
if ($sessionId === false) {
return null;
}
@@ -111,13 +84,4 @@ class Component extends YiiUserComponent {
}
}
private function getBearerToken(): ?string {
$authHeader = Yii::$app->request->getHeaders()->get('Authorization');
if ($authHeader === null || !preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
return null;
}
return $matches[1];
}
}

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace api\components\User;
use api\components\Tokens\TokensFactory;
use Carbon\Carbon;
use common\models\Account;
use Exception;
use Lcobucci\JWT\Token;
@@ -36,22 +37,27 @@ class JwtIdentity implements IdentityInterface {
throw new UnauthorizedHttpException('Incorrect token');
}
if ($token->isExpired()) {
$now = Carbon::now();
if ($token->isExpired($now)) {
throw new UnauthorizedHttpException('Token expired');
}
if (!$token->validate(new ValidationData())) {
if (!$token->validate(new ValidationData($now->getTimestamp()))) {
throw new UnauthorizedHttpException('Incorrect token');
}
$sub = $token->getClaim('sub', false);
if ($sub !== false && strpos($sub, TokensFactory::SUB_ACCOUNT_PREFIX) !== 0) {
if ($sub !== false && strpos((string)$sub, TokensFactory::SUB_ACCOUNT_PREFIX) !== 0) {
throw new UnauthorizedHttpException('Incorrect token');
}
return new self($token);
}
public function getToken(): Token {
return $this->token;
}
public function getAccount(): ?Account {
$subject = $this->token->getClaim('sub', false);
if ($subject === false) {
@@ -77,6 +83,7 @@ class JwtIdentity implements IdentityInterface {
return (string)$this->token;
}
// @codeCoverageIgnoreStart
public function getAuthKey() {
throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth');
}
@@ -89,4 +96,6 @@ class JwtIdentity implements IdentityInterface {
throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth');
}
// @codeCoverageIgnoreEnd
}

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;

2
api/rbac/.generated/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
*
!.gitignore

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

41
api/rbac/Permissions.php Normal file
View File

@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace api\rbac;
final class Permissions {
// Top level Controller permissions
public const OBTAIN_ACCOUNT_INFO = 'obtain_account_info';
public const CHANGE_ACCOUNT_LANGUAGE = 'change_account_language';
public const CHANGE_ACCOUNT_USERNAME = 'change_account_username';
public const CHANGE_ACCOUNT_PASSWORD = 'change_account_password';
public const CHANGE_ACCOUNT_EMAIL = 'change_account_email';
public const MANAGE_TWO_FACTOR_AUTH = 'manage_two_factor_auth';
public const BLOCK_ACCOUNT = 'block_account';
public const COMPLETE_OAUTH_FLOW = 'complete_oauth_flow';
public const CREATE_OAUTH_CLIENTS = 'create_oauth_clients';
public const VIEW_OAUTH_CLIENTS = 'view_oauth_clients';
public const MANAGE_OAUTH_CLIENTS = 'manage_oauth_clients';
// Personal level controller permissions
public const OBTAIN_OWN_ACCOUNT_INFO = 'obtain_own_account_info';
public const OBTAIN_OWN_EXTENDED_ACCOUNT_INFO = 'obtain_own_extended_account_info';
public const CHANGE_OWN_ACCOUNT_LANGUAGE = 'change_own_account_language';
public const ACCEPT_NEW_PROJECT_RULES = 'accept_new_project_rules';
public const CHANGE_OWN_ACCOUNT_USERNAME = 'change_own_account_username';
public const CHANGE_OWN_ACCOUNT_PASSWORD = 'change_own_account_password';
public const CHANGE_OWN_ACCOUNT_EMAIL = 'change_own_account_email';
public const MANAGE_OWN_TWO_FACTOR_AUTH = 'manage_own_two_factor_auth';
public const MINECRAFT_SERVER_SESSION = 'minecraft_server_session';
public const VIEW_OWN_OAUTH_CLIENTS = 'view_own_oauth_clients';
public const MANAGE_OWN_OAUTH_CLIENTS = 'manage_own_oauth_clients';
// Data permissions
public const OBTAIN_ACCOUNT_EMAIL = 'obtain_account_email';
public const OBTAIN_EXTENDED_ACCOUNT_INFO = 'obtain_account_extended_info';
// Service permissions
public const ESCAPE_IDENTITY_VERIFICATION = 'escape_identity_verification';
}

10
api/rbac/Roles.php Normal file
View File

@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace api\rbac;
final class Roles {
public const ACCOUNTS_WEB_USER = 'accounts_web_user';
}

View File

@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace api\rbac\rules;
use common\models\Account;
use Webmozart\Assert\Assert;
use Yii;
use yii\rbac\Rule;
class AccountOwner extends Rule {
public $name = 'account_owner';
/**
* 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.
*
* @param string|int $accessToken
* @param \yii\rbac\Item $item
* @param array $params the "accountId" parameter must be passed as the id of the account
* to which the request is made
* the "optionalRules" parameter allows you to disable the mandatory acceptance
* of the latest version of the rules
*
* @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;
$identity = Yii::$app->user->getIdentity();
if ($identity === null) {
return false;
}
$account = $identity->getAccount();
if ($account === null) {
return false;
}
if ($account->id !== (int)$accountId) {
return false;
}
if ($account->status !== Account::STATUS_ACTIVE) {
return false;
}
$actualRulesOptional = $params['optionalRules'] ?? false;
if (!$actualRulesOptional && !$account->isAgreedWithActualRules()) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace api\rbac\rules;
use api\rbac\Permissions as P;
use common\models\OauthClient;
use Webmozart\Assert\Assert;
use Yii;
use yii\rbac\Rule;
class OauthClientOwner extends Rule {
public $name = 'oauth_client_owner';
/**
* Accepts 2 params:
* - clientId - it's the client id, that user want access to.
* - accountId - if it is passed to check the VIEW_OAUTH_CLIENTS permission, then it will
* check, that current user have access to the provided account.
*
* @param string|int $accessToken
* @param \yii\rbac\Item $item
* @param array $params
*
* @return bool a value indicating whether the rule permits the auth item it is associated with.
*/
public function execute($accessToken, $item, $params): bool {
$accountId = $params['accountId'] ?? null;
if ($accountId !== null && $item->name === P::VIEW_OWN_OAUTH_CLIENTS) {
return (new AccountOwner())->execute($accessToken, $item, ['accountId' => $accountId]);
}
Assert::keyExists($params, 'clientId');
/** @var OauthClient|null $client */
$client = OauthClient::findOne(['id' => $params['clientId']]);
if ($client === null) {
return true;
}
$identity = Yii::$app->user->getIdentity();
if ($identity === null) {
return false;
}
$account = $identity->getAccount();
if ($account === null) {
return false;
}
if ($account->id !== $client->account_id) {
return false;
}
return true;
}
}

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

@@ -16,11 +16,6 @@ class ComponentTest extends TestCase {
*/
private $component;
protected function _setUp() {
parent::_setUp();
$this->component = Yii::$app->tokens;
}
public function testCreate() {
// Run without any arguments
$token = $this->component->create();
@@ -80,6 +75,11 @@ class ComponentTest extends TestCase {
];
}
protected function _setUp() {
parent::_setUp();
$this->component = Yii::$app->tokens;
}
private function assertValidParsedToken(Token $token, string $expectedAlg) {
$this->assertSame($expectedAlg, $token->getHeader('alg'));
$this->assertSame(1564527476, $token->getClaim('iat'));

View File

@@ -4,17 +4,16 @@ declare(strict_types=1);
namespace codeception\api\unit\components\User;
use api\components\User\Component;
use api\components\User\IdentityFactory;
use api\components\User\JwtIdentity;
use api\components\User\Oauth2Identity;
use api\tests\unit\TestCase;
use common\models\Account;
use common\models\AccountSession;
use common\tests\fixtures\AccountFixture;
use common\tests\fixtures\AccountSessionFixture;
use common\tests\fixtures\MinecraftAccessKeyFixture;
use Emarref\Jwt\Claim;
use Emarref\Jwt\Jwt;
use Yii;
use yii\web\Request;
use Lcobucci\JWT\Claim\Basic;
use Lcobucci\JWT\Token;
class ComponentTest extends TestCase {
@@ -36,53 +35,37 @@ class ComponentTest extends TestCase {
];
}
// TODO: move test to refresh token form
public function testRenewJwtAuthenticationToken() {
$userIP = '192.168.0.1';
$this->mockRequest($userIP);
/** @var AccountSession $session */
$session = $this->tester->grabFixture('sessions', 'admin');
$result = $this->component->renewJwtAuthenticationToken($session);
$this->assertSame($session, $result->getSession());
$this->assertSame($session->account_id, $result->getAccount()->id);
$session->refresh(); // reload data from db
$this->assertEqualsWithDelta(time(), $session->last_refreshed_at, 3);
$this->assertSame($userIP, $session->getReadableIp());
$payloads = (new Jwt())->deserialize($result->getJwt())->getPayload();
/** @noinspection NullPointerExceptionInspection */
$this->assertEqualsWithDelta(time(), $payloads->findClaimByName(Claim\IssuedAt::NAME)->getValue(), 3);
/** @noinspection NullPointerExceptionInspection */
$this->assertEqualsWithDelta(time() + 3600, $payloads->findClaimByName('exp')->getValue(), 3);
/** @noinspection NullPointerExceptionInspection */
$this->assertSame('ely|1', $payloads->findClaimByName('sub')->getValue());
/** @noinspection NullPointerExceptionInspection */
$this->assertSame('accounts_web_user', $payloads->findClaimByName('ely-scopes')->getValue());
/** @noinspection NullPointerExceptionInspection */
$this->assertSame($session->id, $payloads->findClaimByName('jti')->getValue(), 'session has not changed');
}
public function testGetActiveSession() {
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
/** @var AccountSession $session */
$session = $this->tester->grabFixture('sessions', 'admin');
$token = $this->component->createJwtAuthenticationToken($account, $session);
$jwt = $this->component->serializeToken($token);
// User is guest
$component = new Component();
$this->assertNull($component->getActiveSession());
/** @var Component|\PHPUnit\Framework\MockObject\MockObject $component */
$component = $this->getMockBuilder(Component::class)
->setMethods(['getIsGuest'])
->getMock();
// Identity is a Oauth2Identity
$component->setIdentity(mock(Oauth2Identity::class));
$this->assertNull($component->getActiveSession());
$component
->method('getIsGuest')
->willReturn(false);
// Identity is correct, but have no jti claim
/** @var JwtIdentity|\Mockery\MockInterface $identity */
$identity = mock(JwtIdentity::class);
$identity->shouldReceive('getToken')->andReturn(new Token());
$component->setIdentity($identity);
$this->assertNull($component->getActiveSession());
$this->mockAuthorizationHeader($jwt);
// Identity is correct and has jti claim, but there is no associated session
/** @var JwtIdentity|\Mockery\MockInterface $identity */
$identity = mock(JwtIdentity::class);
$identity->shouldReceive('getToken')->andReturn(new Token([], ['jti' => new Basic('jti', 999999)]));
$component->setIdentity($identity);
$this->assertNull($component->getActiveSession());
$foundSession = $component->getActiveSession();
$this->assertInstanceOf(AccountSession::class, $foundSession);
$this->assertSame($session->id, $foundSession->id);
// Identity is correct, has jti claim and associated session exists
/** @var JwtIdentity|\Mockery\MockInterface $identity */
$identity = mock(JwtIdentity::class);
$identity->shouldReceive('getToken')->andReturn(new Token([], ['jti' => new Basic('jti', 1)]));
$component->setIdentity($identity);
$session = $component->getActiveSession();
$this->assertNotNull($session);
$this->assertSame(1, $session->id);
}
public function testTerminateSessions() {
@@ -95,7 +78,6 @@ class ComponentTest extends TestCase {
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
$component->createJwtAuthenticationToken($account);
// Dry run: no sessions should be removed
$component->terminateSessions($account, Component::KEEP_MINECRAFT_SESSIONS | Component::KEEP_SITE_SESSIONS);
@@ -119,24 +101,4 @@ class ComponentTest extends TestCase {
$this->assertEmpty($account->getMinecraftAccessKeys()->all());
}
private function mockRequest($userIP = '127.0.0.1') {
/** @var Request|\Mockery\MockInterface $request */
$request = mock(Request::class . '[getHostInfo,getUserIP]')->makePartial();
$request->shouldReceive('getHostInfo')->andReturn('http://localhost');
$request->shouldReceive('getUserIP')->andReturn($userIP);
Yii::$app->set('request', $request);
}
/**
* @param string $bearerToken
*/
private function mockAuthorizationHeader($bearerToken = null) {
if ($bearerToken !== null) {
$bearerToken = 'Bearer ' . $bearerToken;
}
Yii::$app->request->headers->set('Authorization', $bearerToken);
}
}

View File

@@ -5,9 +5,9 @@ namespace codeception\api\unit\components\User;
use api\components\User\JwtIdentity;
use api\tests\unit\TestCase;
use Carbon\Carbon;
use common\tests\fixtures\AccountFixture;
use Emarref\Jwt\Claim\Expiration as ExpirationClaim;
use Yii;
use yii\web\UnauthorizedHttpException;
class JwtIdentityTest extends TestCase {
@@ -18,40 +18,77 @@ class JwtIdentityTest extends TestCase {
}
public function testFindIdentityByAccessToken() {
$token = $this->generateToken();
$token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ.4Oidvuo4spvUf9hkpHR72eeqZUh2Zbxh_L8Od3vcgTj--0iOrcOEp6zwmEW6vF7BTHtjz2b3mXce61bqsCjXjQ';
/** @var JwtIdentity $identity */
$identity = JwtIdentity::findIdentityByAccessToken($token);
$this->assertSame($token, $identity->getId());
$this->assertSame($this->tester->grabFixture('accounts', 'admin')['id'], $identity->getAccount()->id);
}
/**
* @expectedException \yii\web\UnauthorizedHttpException
* @expectedExceptionMessage Token expired
*/
public function testFindIdentityByAccessTokenWithExpiredToken() {
$expiredToken = $this->generateToken(time() - 3600);
JwtIdentity::findIdentityByAccessToken($expiredToken);
}
/**
* @expectedException \yii\web\UnauthorizedHttpException
* @expectedExceptionMessage Incorrect token
*/
public function testFindIdentityByAccessTokenWithEmptyToken() {
JwtIdentity::findIdentityByAccessToken('');
}
private function generateToken(int $expiresAt = null): string {
/** @var \api\components\User\Component $component */
$component = Yii::$app->user;
$this->assertSame($token, (string)$identity->getToken());
/** @var \common\models\Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
$token = $component->createJwtAuthenticationToken($account);
if ($expiresAt !== null) {
$token->addClaim(new ExpirationClaim($expiresAt));
}
$this->assertSame($account->id, $identity->getAccount()->id);
}
return $component->serializeToken($token);
/**
* @dataProvider getFindIdentityByAccessTokenInvalidCases
*/
public function testFindIdentityByAccessTokenInvalidCases(string $token, string $expectedExceptionMessage) {
$this->expectException(UnauthorizedHttpException::class);
$this->expectExceptionMessage($expectedExceptionMessage);
JwtIdentity::findIdentityByAccessToken($token);
}
public function getFindIdentityByAccessTokenInvalidCases() {
yield 'expired token' => [
'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MDMzNDIsImV4cCI6MTU2NDYwNjk0Miwic3ViIjoiZWx5fDEifQ.36cDWyiXRArv-lgK_S5dyC5m_Ddytwkb78tMrxcPcbWEpoeg2VtwPC7zr6NI0cd0CuLw6InC2hZ9Ey95SSOsHw',
'Token expired',
];
yield 'iat from future' => [
'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTc3NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ._6hj6XUSmSLibgT9ZE1Pokf4oI9r-d6tEc1z2J-fBlr1710Qiso5yNcXqb3Z_xy7Qtemyq8jOlOZA8DvmkVBrg',
'Incorrect token',
];
yield 'invalid signature' => [
'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ.yth31f2PyhUkYSfBlizzUXWIgOvxxk8gNP-js0z8g1OT5rig40FPTIkgsZRctAwAAlj6QoIWW7-hxLTcSb2vmw',
'Incorrect token',
];
yield 'invalid sub' => [
'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoxMjM0fQ.yigP5nWFdX0ktbuZC_Unb9bWxpAVd7Nv8Fb1Vsa0t5WkVA88VbhPi2P-CenbDOy8ngwoGV9m3c3upMs2V3gqvw',
'Incorrect token',
];
yield 'empty token' => ['', 'Incorrect token'];
}
public function testGetAccount() {
// Token with sub claim
$identity = JwtIdentity::findIdentityByAccessToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ.4Oidvuo4spvUf9hkpHR72eeqZUh2Zbxh_L8Od3vcgTj--0iOrcOEp6zwmEW6vF7BTHtjz2b3mXce61bqsCjXjQ');
$this->assertSame(1, $identity->getAccount()->id);
// Sub presented, but account not exists
$identity = JwtIdentity::findIdentityByAccessToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDk5OTk5In0.1pAnhkR-_ZqzjLBR-PNIMJUXRSUK3aYixrFNKZg2ynPNPiDvzh8U-iBTT6XRfMP5nvfXZucRpoPVoiXtx40CUQ');
$this->assertNull($identity->getAccount());
// Token without sub claim
$identity = JwtIdentity::findIdentityByAccessToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Mn0.QxmYgSflZOQmhzYRr8bowU767yu4yKgTVaho0MPuyCmUfZO_0O0SQASMKVILf-wlT0ODTTG7vD753a2MTAmPmw');
$this->assertNull($identity->getAccount());
}
public function testGetAssignedPermissions() {
// Token with ely-scopes claim
$identity = JwtIdentity::findIdentityByAccessToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoicGVybTEscGVybTIscGVybTMiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ.MO6T92EOFcZSPIdK8VBUG0qyV-pdayzOPQmpWLPwpl1933E9ann9GdV49piX1IfLHeCHVGThm5_v7AJgyZ5Oaw');
$this->assertSame(['perm1', 'perm2', 'perm3'], $identity->getAssignedPermissions());
// Token without sub claim
$identity = JwtIdentity::findIdentityByAccessToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ.jsjv2dDetSxu4xivlHoTeDUhqsl-cxSI6SktufJhwR9wqDgQCVIONiqQCUzTzyTwyAz4Ztvel4lKjMCstdJOEw');
$this->assertSame([], $identity->getAssignedPermissions());
}
protected function _before() {
parent::_before();
Carbon::setTestNow(Carbon::create(2019, 8, 1, 1, 2, 22, 'Europe/Minsk'));
}
protected function _after() {
parent::_after();
Carbon::setTestNow();
}
}

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\IdentityFactory;
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,15 +56,4 @@ class LogoutFormTest extends TestCase {
});
}
private function getComponentArgs() {
return [
'identityClass' => IdentityFactory::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',
'publicKeyPath' => 'data/certs/public.crt',
'privateKeyPath' => 'data/certs/private.key',
];
}
}

View File

@@ -8,6 +8,8 @@ use api\tests\unit\TestCase;
use Codeception\Specify;
use common\models\AccountSession;
use common\tests\fixtures\AccountSessionFixture;
use Yii;
use yii\web\Request;
class RefreshTokenFormTest extends TestCase {
use Specify;
@@ -18,34 +20,36 @@ class RefreshTokenFormTest extends TestCase {
];
}
public function testValidateRefreshToken() {
$this->specify('error.refresh_token_not_exist if passed token not exists', function() {
/** @var RefreshTokenForm $model */
$model = new class extends RefreshTokenForm {
public function getSession() {
return null;
}
};
$model->validateRefreshToken();
$this->assertSame(['error.refresh_token_not_exist'], $model->getErrors('refresh_token'));
});
public function testRenew() {
/** @var Request|\Mockery\MockInterface $request */
$request = mock(Request::class . '[getUserIP]')->makePartial();
$request->shouldReceive('getUserIP')->andReturn('10.1.2.3');
Yii::$app->set('request', $request);
$this->specify('no errors if token exists', function() {
/** @var RefreshTokenForm $model */
$model = new class extends RefreshTokenForm {
public function getSession() {
return new AccountSession();
}
};
$model->validateRefreshToken();
$this->assertEmpty($model->getErrors('refresh_token'));
});
$model = new RefreshTokenForm();
$model->refresh_token = 'SOutIr6Seeaii3uqMVy3Wan8sKFVFrNz';
$result = $model->renew();
$this->assertNotNull($result);
$this->assertSame('SOutIr6Seeaii3uqMVy3Wan8sKFVFrNz', $result->getRefreshToken());
$token = $result->getToken();
$this->assertSame('ely|1', $token->getClaim('sub'));
$this->assertSame('accounts_web_user', $token->getClaim('ely-scopes'));
$this->assertEqualsWithDelta(time(), $token->getClaim('iat'), 5);
$this->assertEqualsWithDelta(time() + 3600, $token->getClaim('exp'), 5);
$this->assertSame(1, $token->getClaim('jti'));
/** @var AccountSession $session */
$session = AccountSession::findOne(['refresh_token' => 'SOutIr6Seeaii3uqMVy3Wan8sKFVFrNz']);
$this->assertEqualsWithDelta(time(), $session->last_refreshed_at, 5);
$this->assertSame('10.1.2.3', $session->getReadableIp());
}
public function testRenew() {
public function testRenewWithInvalidRefreshToken() {
$model = new RefreshTokenForm();
$model->refresh_token = $this->tester->grabFixture('sessions', 'admin')['refresh_token'];
$this->assertNotNull($model->renew());
$model->refresh_token = 'unknown refresh token';
$this->assertNull($model->renew());
$this->assertSame(['error.refresh_token_not_exist'], $model->getErrors('refresh_token'));
}
}

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\IdentityFactory;
use api\modules\accounts\models\ChangePasswordForm;
use api\tests\unit\TestCase;
use common\components\UserPass;
@@ -56,14 +57,7 @@ class ChangePasswordFormTest extends TestCase {
}
public function testPerformAction() {
$component = mock(Component::class . '[terminateSessions]', [[
'identityClass' => IdentityFactory::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',
'publicKeyPath' => 'data/certs/public.crt',
'privateKeyPath' => 'data/certs/private.key',
]]);
$component = mock(Component::class . '[terminateSessions]');
$component->shouldNotReceive('terminateSessions');
Yii::$app->set('user', $component);
@@ -118,14 +112,7 @@ class ChangePasswordFormTest extends TestCase {
$account->setPassword('password_0');
/** @var Component|\Mockery\MockInterface $component */
$component = mock(Component::class . '[terminateSessions]', [[
'identityClass' => IdentityFactory::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',
'publicKeyPath' => 'data/certs/public.crt',
'privateKeyPath' => 'data/certs/private.key',
]]);
$component = mock(Component::class . '[terminateSessions]');
$component->shouldReceive('terminateSessions')->once()->withArgs([$account, Component::KEEP_CURRENT_SESSION]);
Yii::$app->set('user', $component);

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\IdentityFactory;
use api\modules\accounts\models\EnableTwoFactorAuthForm;
use api\tests\unit\TestCase;
use common\helpers\Error as E;
@@ -19,14 +20,7 @@ class EnableTwoFactorAuthFormTest extends TestCase {
$account->otp_secret = 'mock secret';
/** @var Component|\Mockery\MockInterface $component */
$component = mock(Component::class . '[terminateSessions]', [[
'identityClass' => IdentityFactory::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',
'publicKeyPath' => 'data/certs/public.crt',
'privateKeyPath' => 'data/certs/private.key',
]]);
$component = mock(Component::class . '[terminateSessions]');
$component->shouldReceive('terminateSessions')->withArgs([$account, Component::KEEP_CURRENT_SESSION]);
Yii::$app->set('user', $component);

View File

@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace api\tests\unit\rbac\rules;
use api\components\User\IdentityInterface;
use api\rbac\rules\AccountOwner;
use common\models\Account;
use common\tests\unit\TestCase;
use Yii;
use yii\rbac\Item;
use const common\LATEST_RULES_VERSION;
class AccountOwnerTest extends TestCase {
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);
Yii::$app->user->setIdentity($identity);
$this->assertFalse($rule->execute('token', $item, ['accountId' => 2]));
$this->assertFalse($rule->execute('token', $item, ['accountId' => '2']));
$this->assertTrue($rule->execute('token', $item, ['accountId' => 1]));
$this->assertTrue($rule->execute('token', $item, ['accountId' => '1']));
$account->rules_agreement_version = null;
$this->assertFalse($rule->execute('token', $item, ['accountId' => 1]));
$this->assertTrue($rule->execute('token', $item, ['accountId' => 1, 'optionalRules' => true]));
$account->rules_agreement_version = LATEST_RULES_VERSION;
$account->status = Account::STATUS_BANNED;
$this->assertFalse($rule->execute('token', $item, ['accountId' => 1]));
$this->assertFalse($rule->execute('token', $item, ['accountId' => 1, 'optionalRules' => true]));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testExecuteWithoutAccountId() {
$rule = new AccountOwner();
$this->assertFalse($rule->execute('token', new Item(), []));
}
}

View File

@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace api\tests\unit\rbac\rules;
use api\components\User\IdentityInterface;
use api\rbac\Permissions as P;
use api\rbac\rules\OauthClientOwner;
use common\models\Account;
use common\tests\fixtures\OauthClientFixture;
use common\tests\unit\TestCase;
use Yii;
use yii\rbac\Item;
use const common\LATEST_RULES_VERSION;
class OauthClientOwnerTest extends TestCase {
public function _fixtures(): array {
return [
'oauthClients' => OauthClientFixture::class,
];
}
public function testExecute() {
$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;
$account->rules_agreement_version = LATEST_RULES_VERSION;
/** @var IdentityInterface|\Mockery\MockInterface $identity */
$identity = mock(IdentityInterface::class);
$identity->shouldReceive('getAccount')->andReturn($account);
Yii::$app->user->setIdentity($identity);
$this->assertTrue($rule->execute('token', $item, ['clientId' => 'admin-oauth-client']));
$this->assertTrue($rule->execute('token', $item, ['clientId' => 'not-exists-client']));
$account->id = 2;
$this->assertFalse($rule->execute('token', $item, ['clientId' => 'admin-oauth-client']));
$item->name = P::VIEW_OWN_OAUTH_CLIENTS;
$this->assertTrue($rule->execute('token', $item, ['accountId' => 2]));
$this->assertFalse($rule->execute('token', $item, ['accountId' => 1]));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testExecuteWithoutClientId() {
$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;