Replace emarref/jwt with lcobucci/jwt

Refactor all JWT-related components
Replace RS256 with ES256 as a preferred JWT algorithm
This commit is contained in:
ErickSkrauch 2019-08-01 12:17:12 +03:00
parent 4c2a9cc172
commit 45c2ed601d
47 changed files with 805 additions and 621 deletions

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,96 @@
<?php
declare(strict_types=1);
namespace api\components\Tokens;
use Exception;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Token;
use yii\base\Component as BaseComponent;
class Component extends BaseComponent {
private const EXPIRATION_TIMEOUT = 3600; // 1h
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 create(array $payloads = [], array $headers = []): Token {
$time = time();
$builder = (new Builder())
->issuedAt($time)
->expiresAt($time + self::EXPIRATION_TIMEOUT);
foreach ($payloads as $claim => $value) {
$builder->withClaim($claim, $value);
}
foreach ($headers as $claim => $value) {
$builder->withHeader($claim, $value);
}
/** @noinspection PhpUnhandledExceptionInspection */
$algorithm = $this->getAlgorithmManager()->get(self::PREFERRED_ALGORITHM);
return $builder->getToken($algorithm->getSigner(), $algorithm->getPrivateKey());
}
/**
* @param string $jwt
*
* @return Token
* @throws \InvalidArgumentException
*/
public function parse(string $jwt): Token {
return (new Parser())->parse($jwt);
}
public function verify(Token $token): bool {
try {
$algorithm = $this->getAlgorithmManager()->get($token->getHeader('alg'));
return $token->verify($algorithm->getSigner(), $algorithm->getPublicKey());
} catch (Exception $e) {
return false;
}
}
private function getAlgorithmManager(): AlgorithmsManager {
if ($this->algorithmManager === null) {
$this->algorithmManager = new AlgorithmsManager([
new Algorithms\HS256($this->hmacKey),
new Algorithms\ES256(
"file://{$this->privateKeyPath}",
$this->privateKeyPass,
"file://{$this->publicKeyPath}"
),
]);
}
return $this->algorithmManager;
}
}

View File

@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace api\components\Tokens;
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'] = time() + 60 * 60 * 24 * 7; // 7d
} 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

@ -3,28 +3,11 @@ declare(strict_types=1);
namespace api\components\User; namespace api\components\User;
use api\exceptions\ThisShouldNotHappenException;
use common\models\Account; use common\models\Account;
use common\models\AccountSession; use common\models\AccountSession;
use common\rbac\Roles as R;
use DateInterval;
use DateTime;
use Emarref\Jwt\Algorithm\AlgorithmInterface;
use Emarref\Jwt\Algorithm\Hs256;
use Emarref\Jwt\Algorithm\Rs256;
use Emarref\Jwt\Claim;
use Emarref\Jwt\Encryption\Asymmetric as AsymmetricEncryption;
use Emarref\Jwt\Encryption\EncryptionInterface;
use Emarref\Jwt\Encryption\Factory as EncryptionFactory;
use Emarref\Jwt\Exception\VerificationException;
use Emarref\Jwt\HeaderParameter\Custom;
use Emarref\Jwt\Token;
use Emarref\Jwt\Verification\Context as VerificationContext;
use Exception; use Exception;
use InvalidArgumentException; use InvalidArgumentException;
use Webmozart\Assert\Assert;
use Yii; use Yii;
use yii\base\InvalidConfigException;
use yii\web\UnauthorizedHttpException; use yii\web\UnauthorizedHttpException;
use yii\web\User as YiiUserComponent; use yii\web\User as YiiUserComponent;
@ -41,52 +24,29 @@ class Component extends YiiUserComponent {
public const KEEP_SITE_SESSIONS = 2; public const KEEP_SITE_SESSIONS = 2;
public const KEEP_CURRENT_SESSION = 4; public const KEEP_CURRENT_SESSION = 4;
public const JWT_SUBJECT_PREFIX = 'ely|';
private const LATEST_JWT_VERSION = 1;
public $enableSession = false; public $enableSession = false;
public $loginUrl = null; public $loginUrl = null;
public $identityClass = Identity::class;
public $secret;
public $publicKeyPath;
public $privateKeyPath;
public $expirationTimeout = 'PT1H';
public $sessionTimeout = 'P7D';
private $publicKey;
private $privateKey;
/** /**
* @var Token[] * We don't use the standard web authorization mechanism via cookies.
* Therefore, only one static method findIdentityByAccessToken is used from
* the whole IdentityInterface interface, which is implemented in the factory.
* The method only used from loginByAccessToken from base class.
*
* @var string
*/ */
private static $parsedTokensCache = []; public $identityClass = IdentityFactory::class;
public function init() {
parent::init();
Assert::notEmpty($this->secret, 'secret must be specified');
Assert::notEmpty($this->publicKeyPath, 'public key path must be specified');
Assert::notEmpty($this->privateKeyPath, 'private key path must be specified');
}
public function findIdentityByAccessToken($accessToken): ?IdentityInterface { public function findIdentityByAccessToken($accessToken): ?IdentityInterface {
if (empty($accessToken)) { if (empty($accessToken)) {
return null; return null;
} }
/** @var \api\components\User\IdentityInterface|string $identityClass */
$identityClass = $this->identityClass;
try { try {
return $identityClass::findIdentityByAccessToken($accessToken); return IdentityFactory::findIdentityByAccessToken($accessToken);
} catch (UnauthorizedHttpException $e) { } catch (UnauthorizedHttpException $e) {
// TODO: if this exception is catched there, how it forms "Token expired" exception?
// Do nothing. It's okay to catch this. // Do nothing. It's okay to catch this.
} catch (Exception $e) { } catch (Exception $e) {
Yii::error($e); Yii::error($e);
@ -95,77 +55,6 @@ class Component extends YiiUserComponent {
return null; return null;
} }
public function createJwtAuthenticationToken(Account $account, AccountSession $session = null): Token {
$token = $this->createToken($account);
if ($session !== null) {
$token->addClaim(new Claim\JwtId($session->id));
} else {
// If we don't remember a session, the token should live longer
// so that the session doesn't end while working with the account
$token->addClaim(new Claim\Expiration((new DateTime())->add(new DateInterval($this->sessionTimeout))));
}
return $token;
}
public function renewJwtAuthenticationToken(AccountSession $session): AuthenticationResult {
$transaction = Yii::$app->db->beginTransaction();
$account = $session->account;
$token = $this->createToken($account);
$token->addClaim(new Claim\JwtId($session->id));
$jwt = $this->serializeToken($token);
$result = new AuthenticationResult($account, $jwt, $session);
$session->setIp(Yii::$app->request->userIP);
$session->last_refreshed_at = time();
if (!$session->save()) {
throw new ThisShouldNotHappenException('Cannot update session info');
}
$transaction->commit();
return $result;
}
public function serializeToken(Token $token): string {
$encryption = $this->getEncryptionForVersion(self::LATEST_JWT_VERSION);
$this->prepareEncryptionForEncoding($encryption);
return (new Jwt())->serialize($token, $encryption);
}
/**
* @param string $jwtString
* @return Token
* @throws VerificationException in case when some Claim not pass the validation
*/
public function parseToken(string $jwtString): Token {
$token = &self::$parsedTokensCache[$jwtString];
if ($token === null) {
$jwt = new Jwt();
try {
$notVerifiedToken = $jwt->deserialize($jwtString);
} catch (Exception $e) {
throw new VerificationException('Incorrect token encoding', 0, $e);
}
$versionHeader = $notVerifiedToken->getHeader()->findParameterByName('v');
$version = $versionHeader ? $versionHeader->getValue() : 0;
$encryption = $this->getEncryptionForVersion($version);
$this->prepareEncryptionForDecoding($encryption);
$context = new VerificationContext($encryption);
$context->setSubject(self::JWT_SUBJECT_PREFIX);
$jwt->verify($notVerifiedToken, $context);
$token = $notVerifiedToken;
}
return $token;
}
/** /**
* The method searches AccountSession model, which one has been used to create current JWT token. * 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: * null will be returned in case when any of the following situations occurred:
@ -188,17 +77,17 @@ class Component extends YiiUserComponent {
} }
try { try {
$token = $this->parseToken($bearer); $token = Yii::$app->tokens->parse($bearer);
} catch (VerificationException $e) { } catch (InvalidArgumentException $e) {
return null; return null;
} }
$sessionId = $token->getPayload()->findClaimByName(Claim\JwtId::NAME); $sessionId = $token->getClaim('jti', false);
if ($sessionId === null) { if ($sessionId === false) {
return null; return null;
} }
return AccountSession::findOne($sessionId->getValue()); return AccountSession::findOne($sessionId);
} }
public function terminateSessions(Account $account, int $mode = 0): void { public function terminateSessions(Account $account, int $mode = 0): void {
@ -222,66 +111,6 @@ class Component extends YiiUserComponent {
} }
} }
private function getPublicKey() {
if (empty($this->publicKey)) {
if (!($this->publicKey = file_get_contents($this->publicKeyPath))) {
throw new InvalidConfigException('invalid public key path');
}
}
return $this->publicKey;
}
private function getPrivateKey() {
if (empty($this->privateKey)) {
if (!($this->privateKey = file_get_contents($this->privateKeyPath))) {
throw new InvalidConfigException('invalid private key path');
}
}
return $this->privateKey;
}
private function createToken(Account $account): Token {
$token = new Token();
$token->addHeader(new Custom('v', 1));
foreach ($this->getClaims($account) as $claim) {
$token->addClaim($claim);
}
return $token;
}
/**
* @param Account $account
* @return Claim\AbstractClaim[]
*/
private function getClaims(Account $account): array {
$currentTime = new DateTime();
return [
new ScopesClaim([R::ACCOUNTS_WEB_USER]),
new Claim\IssuedAt($currentTime),
new Claim\Expiration($currentTime->add(new DateInterval($this->expirationTimeout))),
new Claim\Subject(self::JWT_SUBJECT_PREFIX . $account->id),
];
}
private function getEncryptionForVersion(int $version): EncryptionInterface {
return EncryptionFactory::create($this->getAlgorithm($version ?? 0));
}
private function getAlgorithm(int $version): AlgorithmInterface {
switch ($version) {
case 0:
return new Hs256($this->secret);
case 1:
return new Rs256();
}
throw new InvalidArgumentException('Unsupported token version');
}
private function getBearerToken(): ?string { private function getBearerToken(): ?string {
$authHeader = Yii::$app->request->getHeaders()->get('Authorization'); $authHeader = Yii::$app->request->getHeaders()->get('Authorization');
if ($authHeader === null || !preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) { if ($authHeader === null || !preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
@ -291,16 +120,4 @@ class Component extends YiiUserComponent {
return $matches[1]; return $matches[1];
} }
private function prepareEncryptionForEncoding(EncryptionInterface $encryption): void {
if ($encryption instanceof AsymmetricEncryption) {
$encryption->setPrivateKey($this->getPrivateKey());
}
}
private function prepareEncryptionForDecoding(EncryptionInterface $encryption) {
if ($encryption instanceof AsymmetricEncryption) {
$encryption->setPublicKey($this->getPublicKey());
}
}
} }

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,82 +1,80 @@
<?php <?php
declare(strict_types=1);
namespace api\components\User; namespace api\components\User;
use api\components\Tokens\TokensFactory;
use common\models\Account; use common\models\Account;
use Emarref\Jwt\Claim\Subject;
use Emarref\Jwt\Exception\ExpiredException;
use Emarref\Jwt\Token;
use Exception; use Exception;
use Lcobucci\JWT\Token;
use Lcobucci\JWT\ValidationData;
use Webmozart\Assert\Assert;
use Yii; use Yii;
use yii\base\NotSupportedException; use yii\base\NotSupportedException;
use yii\helpers\StringHelper;
use yii\web\UnauthorizedHttpException; use yii\web\UnauthorizedHttpException;
class JwtIdentity implements IdentityInterface { class JwtIdentity implements IdentityInterface {
/**
* @var string
*/
private $rawToken;
/** /**
* @var Token * @var Token
*/ */
private $token; private $token;
private function __construct(string $rawToken, Token $token) { private function __construct(Token $token) {
$this->rawToken = $rawToken;
$this->token = $token; $this->token = $token;
} }
public static function findIdentityByAccessToken($rawToken, $type = null): IdentityInterface { public static function findIdentityByAccessToken($rawToken, $type = null): IdentityInterface {
/** @var \api\components\User\Component $component */
$component = Yii::$app->user;
try { try {
$token = $component->parseToken($rawToken); $token = Yii::$app->tokens->parse($rawToken);
} catch (ExpiredException $e) {
throw new UnauthorizedHttpException('Token expired');
} catch (Exception $e) { } catch (Exception $e) {
Yii::error($e); Yii::error($e);
throw new UnauthorizedHttpException('Incorrect token'); throw new UnauthorizedHttpException('Incorrect token');
} }
return new self($rawToken, $token); if (!Yii::$app->tokens->verify($token)) {
throw new UnauthorizedHttpException('Incorrect token');
}
if ($token->isExpired()) {
throw new UnauthorizedHttpException('Token expired');
}
if (!$token->validate(new ValidationData())) {
throw new UnauthorizedHttpException('Incorrect token');
}
$sub = $token->getClaim('sub', false);
if ($sub !== false && strpos($sub, TokensFactory::SUB_ACCOUNT_PREFIX) !== 0) {
throw new UnauthorizedHttpException('Incorrect token');
}
return new self($token);
} }
public function getAccount(): ?Account { public function getAccount(): ?Account {
/** @var Subject $subject */ $subject = $this->token->getClaim('sub', false);
$subject = $this->token->getPayload()->findClaimByName(Subject::NAME); if ($subject === false) {
if ($subject === null) {
return null; return null;
} }
$value = $subject->getValue(); Assert::startsWith($subject, TokensFactory::SUB_ACCOUNT_PREFIX);
if (!StringHelper::startsWith($value, Component::JWT_SUBJECT_PREFIX)) { $accountId = (int)mb_substr($subject, mb_strlen(TokensFactory::SUB_ACCOUNT_PREFIX));
Yii::warning('Unknown jwt subject: ' . $value);
return null;
}
$accountId = (int)mb_substr($value, mb_strlen(Component::JWT_SUBJECT_PREFIX)); return Account::findOne(['id' => $accountId]);
$account = Account::findOne($accountId);
if ($account === null) {
return null;
}
return $account;
} }
public function getAssignedPermissions(): array { public function getAssignedPermissions(): array {
/** @var Subject $scopesClaim */ $scopesClaim = $this->token->getClaim('ely-scopes', false);
$scopesClaim = $this->token->getPayload()->findClaimByName(ScopesClaim::NAME); if ($scopesClaim === false) {
if ($scopesClaim === null) {
return []; return [];
} }
return explode(',', $scopesClaim->getValue()); return explode(',', $scopesClaim);
} }
public function getId(): string { public function getId(): string {
return $this->rawToken; return (string)$this->token;
} }
public function getAuthKey() { public function getAuthKey() {

View File

@ -1,4 +1,6 @@
<?php <?php
declare(strict_types=1);
namespace api\components\User; namespace api\components\User;
use api\components\OAuth2\Entities\AccessTokenEntity; use api\components\OAuth2\Entities\AccessTokenEntity;
@ -8,10 +10,7 @@ use Yii;
use yii\base\NotSupportedException; use yii\base\NotSupportedException;
use yii\web\UnauthorizedHttpException; use yii\web\UnauthorizedHttpException;
/** class Oauth2Identity implements IdentityInterface {
* @property Account $account
*/
class Identity implements IdentityInterface {
/** /**
* @var AccessTokenEntity * @var AccessTokenEntity
@ -24,19 +23,10 @@ class Identity implements IdentityInterface {
/** /**
* @inheritdoc * @inheritdoc
* @throws \yii\web\UnauthorizedHttpException * @throws UnauthorizedHttpException
* @return IdentityInterface * @return IdentityInterface
*/ */
public static function findIdentityByAccessToken($token, $type = null): 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 */ /** @var AccessTokenEntity|null $model */
$model = Yii::$app->oauth->getAccessTokenStorage()->get($token); $model = Yii::$app->oauth->getAccessTokenStorage()->get($token);
if ($model === null) { if ($model === null) {

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 <?php
return [ return [
'components' => [ 'components' => [
'user' => [ 'tokens' => [
'secret' => 'tests-secret-key', 'hmacKey' => 'tests-secret-key',
'privateKeyPath' => codecept_data_dir('certs/private.pem'),
'privateKeyPass' => null,
'publicKeyPath' => codecept_data_dir('certs/public.pem'),
], ],
'reCaptcha' => [ 'reCaptcha' => [
'public' => 'public-key', 'public' => 'public-key',

View File

@ -10,9 +10,13 @@ return [
'components' => [ 'components' => [
'user' => [ 'user' => [
'class' => api\components\User\Component::class, 'class' => api\components\User\Component::class,
'secret' => getenv('JWT_USER_SECRET'), ],
'publicKeyPath' => getenv('JWT_PUBLIC_KEY') ?: 'data/certs/public.crt', 'tokens' => [
'privateKeyPath' => getenv('JWT_PRIVATE_KEY') ?: 'data/certs/private.key', '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' => [ 'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0, 'traceLevel' => YII_DEBUG ? 3 : 0,

View File

@ -51,7 +51,7 @@ class AuthenticationController extends Controller {
public function actionLogin() { public function actionLogin() {
$model = new LoginForm(); $model = new LoginForm();
$model->load(Yii::$app->request->post()); $model->load(Yii::$app->request->post());
if (($result = $model->login()) === false) { if (($result = $model->login()) === null) {
$data = [ $data = [
'success' => false, 'success' => false,
'errors' => $model->getFirstErrors(), 'errors' => $model->getFirstErrors(),
@ -66,7 +66,7 @@ class AuthenticationController extends Controller {
return array_merge([ return array_merge([
'success' => true, 'success' => true,
], $result->getAsResponse()); ], $result->formatAsOAuth2Response());
} }
public function actionLogout() { public function actionLogout() {
@ -117,7 +117,7 @@ class AuthenticationController extends Controller {
public function actionRecoverPassword() { public function actionRecoverPassword() {
$model = new RecoverPasswordForm(); $model = new RecoverPasswordForm();
$model->load(Yii::$app->request->post()); $model->load(Yii::$app->request->post());
if (($result = $model->recoverPassword()) === false) { if (($result = $model->recoverPassword()) === null) {
return [ return [
'success' => false, 'success' => false,
'errors' => $model->getFirstErrors(), 'errors' => $model->getFirstErrors(),
@ -126,20 +126,20 @@ class AuthenticationController extends Controller {
return array_merge([ return array_merge([
'success' => true, 'success' => true,
], $result->getAsResponse()); ], $result->formatAsOAuth2Response());
} }
public function actionRefreshToken() { public function actionRefreshToken() {
$model = new RefreshTokenForm(); $model = new RefreshTokenForm();
$model->load(Yii::$app->request->post()); $model->load(Yii::$app->request->post());
if (($result = $model->renew()) === false) { if (($result = $model->renew()) === null) {
return [ return [
'success' => false, 'success' => false,
'errors' => $model->getFirstErrors(), 'errors' => $model->getFirstErrors(),
]; ];
} }
$response = $result->getAsResponse(); $response = $result->formatAsOAuth2Response();
unset($response['refresh_token']); unset($response['refresh_token']);
return array_merge([ return array_merge([

View File

@ -89,7 +89,7 @@ class SignupController extends Controller {
return array_merge([ return array_merge([
'success' => true, '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,7 +4,7 @@ declare(strict_types=1);
namespace api\models\authentication; namespace api\models\authentication;
use api\aop\annotations\CollectModelMetrics; use api\aop\annotations\CollectModelMetrics;
use api\components\User\AuthenticationResult; use api\components\Tokens\TokensFactory;
use api\models\base\ApiForm; use api\models\base\ApiForm;
use api\validators\EmailActivationKeyValidator; use api\validators\EmailActivationKeyValidator;
use common\models\Account; use common\models\Account;
@ -25,12 +25,10 @@ class ConfirmEmailForm extends ApiForm {
/** /**
* @CollectModelMetrics(prefix="signup.confirmEmail") * @CollectModelMetrics(prefix="signup.confirmEmail")
* @return AuthenticationResult|bool
* @throws \Throwable
*/ */
public function confirm() { public function confirm(): ?AuthenticationResult {
if (!$this->validate()) { if (!$this->validate()) {
return false; return null;
} }
$transaction = Yii::$app->db->beginTransaction(); $transaction = Yii::$app->db->beginTransaction();
@ -39,6 +37,7 @@ class ConfirmEmailForm extends ApiForm {
$confirmModel = $this->key; $confirmModel = $this->key;
$account = $confirmModel->account; $account = $confirmModel->account;
$account->status = Account::STATUS_ACTIVE; $account->status = Account::STATUS_ACTIVE;
/** @noinspection PhpUnhandledExceptionInspection */
Assert::notSame($confirmModel->delete(), false, 'Unable remove activation key.'); Assert::notSame($confirmModel->delete(), false, 'Unable remove activation key.');
Assert::true($account->save(), 'Unable activate user account.'); Assert::true($account->save(), 'Unable activate user account.');
@ -49,12 +48,11 @@ class ConfirmEmailForm extends ApiForm {
$session->generateRefreshToken(); $session->generateRefreshToken();
Assert::true($session->save(), 'Cannot save account session model'); Assert::true($session->save(), 'Cannot save account session model');
$token = Yii::$app->user->createJwtAuthenticationToken($account, $session); $token = TokensFactory::createForAccount($account, $session);
$jwt = Yii::$app->user->serializeToken($token);
$transaction->commit(); $transaction->commit();
return new AuthenticationResult($account, $jwt, $session); return new AuthenticationResult($token, $session->refresh_token);
} }
} }

View File

@ -4,7 +4,7 @@ declare(strict_types=1);
namespace api\models\authentication; namespace api\models\authentication;
use api\aop\annotations\CollectModelMetrics; use api\aop\annotations\CollectModelMetrics;
use api\components\User\AuthenticationResult; use api\components\Tokens\TokensFactory;
use api\models\base\ApiForm; use api\models\base\ApiForm;
use api\traits\AccountFinder; use api\traits\AccountFinder;
use api\validators\TotpValidator; use api\validators\TotpValidator;
@ -30,12 +30,12 @@ class LoginForm extends ApiForm {
['login', 'required', 'message' => E::LOGIN_REQUIRED], ['login', 'required', 'message' => E::LOGIN_REQUIRED],
['login', 'validateLogin'], ['login', 'validateLogin'],
['password', 'required', 'when' => function(self $model) { ['password', 'required', 'when' => function(self $model): bool {
return !$model->hasErrors(); return !$model->hasErrors();
}, 'message' => E::PASSWORD_REQUIRED], }, 'message' => E::PASSWORD_REQUIRED],
['password', 'validatePassword'], ['password', 'validatePassword'],
['totp', 'required', 'when' => function(self $model) { ['totp', 'required', 'when' => function(self $model): bool {
return !$model->hasErrors() && $model->getAccount()->is_otp_enabled; return !$model->hasErrors() && $model->getAccount()->is_otp_enabled;
}, 'message' => E::TOTP_REQUIRED], }, 'message' => E::TOTP_REQUIRED],
['totp', 'validateTotp'], ['totp', 'validateTotp'],
@ -97,11 +97,10 @@ class LoginForm extends ApiForm {
/** /**
* @CollectModelMetrics(prefix="authentication.login") * @CollectModelMetrics(prefix="authentication.login")
* @return AuthenticationResult|bool
*/ */
public function login() { public function login(): ?AuthenticationResult {
if (!$this->validate()) { if (!$this->validate()) {
return false; return null;
} }
$transaction = Yii::$app->db->beginTransaction(); $transaction = Yii::$app->db->beginTransaction();
@ -113,21 +112,22 @@ class LoginForm extends ApiForm {
Assert::true($account->save(), 'Unable to upgrade user\'s password'); Assert::true($account->save(), 'Unable to upgrade user\'s password');
} }
$session = null; $refreshToken = null;
if ($this->rememberMe) { if ($this->rememberMe) {
$session = new AccountSession(); $session = new AccountSession();
$session->account_id = $account->id; $session->account_id = $account->id;
$session->setIp(Yii::$app->request->userIP); $session->setIp(Yii::$app->request->userIP);
$session->generateRefreshToken(); $session->generateRefreshToken();
Assert::true($session->save(), 'Cannot save account session model'); Assert::true($session->save(), 'Cannot save account session model');
$refreshToken = $session->refresh_token;
} }
$token = Yii::$app->user->createJwtAuthenticationToken($account, $session); $token = TokensFactory::createForAccount($account, $session);
$jwt = Yii::$app->user->serializeToken($token);
$transaction->commit(); $transaction->commit();
return new AuthenticationResult($account, $jwt, $session); return new AuthenticationResult($token, $refreshToken);
} }
} }

View File

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace api\models\authentication; namespace api\models\authentication;
use api\aop\annotations\CollectModelMetrics; use api\aop\annotations\CollectModelMetrics;
use api\components\Tokens\TokensFactory;
use api\models\base\ApiForm; use api\models\base\ApiForm;
use api\validators\EmailActivationKeyValidator; use api\validators\EmailActivationKeyValidator;
use common\helpers\Error as E; use common\helpers\Error as E;
@ -38,12 +39,10 @@ class RecoverPasswordForm extends ApiForm {
/** /**
* @CollectModelMetrics(prefix="authentication.recoverPassword") * @CollectModelMetrics(prefix="authentication.recoverPassword")
* @return \api\components\User\AuthenticationResult|bool
* @throws \Throwable
*/ */
public function recoverPassword() { public function recoverPassword(): ?AuthenticationResult {
if (!$this->validate()) { if (!$this->validate()) {
return false; return null;
} }
$transaction = Yii::$app->db->beginTransaction(); $transaction = Yii::$app->db->beginTransaction();
@ -52,16 +51,16 @@ class RecoverPasswordForm extends ApiForm {
$confirmModel = $this->key; $confirmModel = $this->key;
$account = $confirmModel->account; $account = $confirmModel->account;
$account->password = $this->newPassword; $account->password = $this->newPassword;
/** @noinspection PhpUnhandledExceptionInspection */
Assert::notSame($confirmModel->delete(), false, 'Unable remove activation key.'); Assert::notSame($confirmModel->delete(), false, 'Unable remove activation key.');
Assert::true($account->save(), 'Unable activate user account.'); Assert::true($account->save(), 'Unable activate user account.');
$token = Yii::$app->user->createJwtAuthenticationToken($account); $token = TokensFactory::createForAccount($account);
$jwt = Yii::$app->user->serializeToken($token);
$transaction->commit(); $transaction->commit();
return new \api\components\User\AuthenticationResult($account, $jwt, null); return new AuthenticationResult($token);
} }
} }

View File

@ -1,10 +1,14 @@
<?php <?php
declare(strict_types=1);
namespace api\models\authentication; namespace api\models\authentication;
use api\aop\annotations\CollectModelMetrics; use api\aop\annotations\CollectModelMetrics;
use api\components\Tokens\TokensFactory;
use api\models\base\ApiForm; use api\models\base\ApiForm;
use common\helpers\Error as E; use common\helpers\Error as E;
use common\models\AccountSession; use common\models\AccountSession;
use Webmozart\Assert\Assert;
use Yii; use Yii;
class RefreshTokenForm extends ApiForm { class RefreshTokenForm extends ApiForm {
@ -16,41 +20,45 @@ class RefreshTokenForm extends ApiForm {
*/ */
private $session; private $session;
public function rules() { public function rules(): array {
return [ return [
['refresh_token', 'required', 'message' => E::REFRESH_TOKEN_REQUIRED], ['refresh_token', 'required', 'message' => E::REFRESH_TOKEN_REQUIRED],
['refresh_token', 'validateRefreshToken'], ['refresh_token', 'validateRefreshToken'],
]; ];
} }
public function validateRefreshToken() { public function validateRefreshToken(): void {
if (!$this->hasErrors()) { if (!$this->hasErrors() && $this->findSession() === null) {
/** @var AccountSession|null $token */
if ($this->getSession() === null) {
$this->addError('refresh_token', E::REFRESH_TOKEN_NOT_EXISTS); $this->addError('refresh_token', E::REFRESH_TOKEN_NOT_EXISTS);
} }
} }
}
/** /**
* @CollectModelMetrics(prefix="authentication.renew") * @CollectModelMetrics(prefix="authentication.renew")
* @return \api\components\User\AuthenticationResult|bool
*/ */
public function renew() { public function renew(): ?AuthenticationResult {
if (!$this->validate()) { if (!$this->validate()) {
return false; return null;
} }
/** @var \api\components\User\Component $component */ /** @var AccountSession $session */
$component = Yii::$app->user; $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);
} }
/** private function findSession(): ?AccountSession {
* @return AccountSession|null
*/
public function getSession() {
if ($this->session === null) { if ($this->session === null) {
$this->session = AccountSession::findOne(['refresh_token' => $this->refresh_token]); $this->session = AccountSession::findOne(['refresh_token' => $this->refresh_token]);
} }

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; namespace api\tests;
use api\components\Tokens\TokensFactory;
use api\tests\_generated\FunctionalTesterActions; use api\tests\_generated\FunctionalTesterActions;
use Codeception\Actor; use Codeception\Actor;
use common\models\Account; use common\models\Account;
@ -12,16 +13,15 @@ use Yii;
class FunctionalTester extends Actor { class FunctionalTester extends Actor {
use FunctionalTesterActions; use FunctionalTesterActions;
public function amAuthenticated(string $asUsername = 'admin') { public function amAuthenticated(string $asUsername = 'admin'): int {
/** @var Account $account */ /** @var Account $account */
$account = Account::findOne(['username' => $asUsername]); $account = Account::findOne(['username' => $asUsername]);
if ($account === null) { if ($account === null) {
throw new InvalidArgumentException("Cannot find account for username \"{$asUsername}\""); throw new InvalidArgumentException("Cannot find account with username \"{$asUsername}\"");
} }
$token = Yii::$app->user->createJwtAuthenticationToken($account); $token = TokensFactory::createForAccount($account);
$jwt = Yii::$app->user->serializeToken($token); $this->amBearerAuthenticated((string)$token);
$this->amBearerAuthenticated($jwt);
return $account->id; return $account->id;
} }
@ -31,10 +31,10 @@ class FunctionalTester extends Actor {
Yii::$app->user->logout(); Yii::$app->user->logout();
} }
public function canSeeAuthCredentials($expectRefresh = false): void { public function canSeeAuthCredentials($expectRefreshToken = false): void {
$this->canSeeResponseJsonMatchesJsonPath('$.access_token'); $this->canSeeResponseJsonMatchesJsonPath('$.access_token');
$this->canSeeResponseJsonMatchesJsonPath('$.expires_in'); $this->canSeeResponseJsonMatchesJsonPath('$.expires_in');
if ($expectRefresh) { if ($expectRefreshToken) {
$this->canSeeResponseJsonMatchesJsonPath('$.refresh_token'); $this->canSeeResponseJsonMatchesJsonPath('$.refresh_token');
} else { } else {
$this->cantSeeResponseJsonMatchesJsonPath('$.refresh_token'); $this->cantSeeResponseJsonMatchesJsonPath('$.refresh_token');

View File

@ -0,0 +1,92 @@
<?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;
protected function _setUp() {
parent::_setUp();
$this->component = Yii::$app->tokens;
}
public function testCreate() {
// Run without any arguments
$token = $this->component->create();
$this->assertSame('ES256', $token->getHeader('alg'));
$this->assertEmpty(array_diff(array_keys($token->getClaims()), ['iat', 'exp']));
$this->assertEqualsWithDelta(time(), $token->getClaim('iat'), 1);
$this->assertEqualsWithDelta(time() + 3600, $token->getClaim('exp'), 2);
// Pass custom payloads
$token = $this->component->create(['find' => 'me']);
$this->assertArrayHasKey('find', $token->getClaims());
$this->assertSame('me', $token->getClaim('find'));
// Pass custom headers
$token = $this->component->create([], ['find' => 'me']);
$this->assertArrayHasKey('find', $token->getHeaders());
$this->assertSame('me', $token->getHeader('find'));
}
public function testParse() {
// Valid token signed with HS256
$token = $this->component->parse('eyJhbGciOiJIUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.ixapBbhaUCejbcPTnFi5nqk75XKd1_lQJd1ZPgGTLEc');
$this->assertValidParsedToken($token, 'HS256');
// Valid token signed with ES256
$token = $this->component->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.M8Kam9bv0BXui3k7Posq_vc0I95Kb_Tw7L2vPdEPlwsHqh1VJHoWtlQc32_SlsotttL7j6RYbffBkRFX2wDGFQ');
$this->assertValidParsedToken($token, 'ES256');
// Valid token signed with ES256, but the signature is invalid
$token = $this->component->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.xxx');
$this->assertValidParsedToken($token, 'ES256');
// Completely invalid token
$this->expectException(InvalidArgumentException::class);
$this->component->parse('How do you tame a horse in Minecraft?');
}
/**
* @dataProvider getVerifyCases
*/
public function testVerify(Token $token, bool $shouldBeValid) {
$this->assertSame($shouldBeValid, $this->component->verify($token));
}
public function getVerifyCases() {
yield 'HS256' => [
(new Parser())->parse('eyJhbGciOiJIUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.ixapBbhaUCejbcPTnFi5nqk75XKd1_lQJd1ZPgGTLEc'),
true,
];
yield 'ES256' => [
(new Parser())->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.M8Kam9bv0BXui3k7Posq_vc0I95Kb_Tw7L2vPdEPlwsHqh1VJHoWtlQc32_SlsotttL7j6RYbffBkRFX2wDGFQ'),
true,
];
yield 'ES256 with an invalid signature' => [
(new Parser())->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.xxx'),
false,
];
}
private function assertValidParsedToken(Token $token, string $expectedAlg) {
$this->assertSame($expectedAlg, $token->getHeader('alg'));
$this->assertSame(1564527476, $token->getClaim('iat'));
$this->assertSame(1564531076, $token->getClaim('exp'));
$this->assertSame('ely|1', $token->getClaim('sub'));
$this->assertSame(3069592, $token->getClaim('jti'));
$this->assertSame('accounts_web_user', $token->getClaim('ely-scopes'));
}
}

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

@ -4,7 +4,7 @@ declare(strict_types=1);
namespace codeception\api\unit\components\User; namespace codeception\api\unit\components\User;
use api\components\User\Component; use api\components\User\Component;
use api\components\User\Identity; use api\components\User\IdentityFactory;
use api\tests\unit\TestCase; use api\tests\unit\TestCase;
use common\models\Account; use common\models\Account;
use common\models\AccountSession; use common\models\AccountSession;
@ -36,29 +36,7 @@ class ComponentTest extends TestCase {
]; ];
} }
public function testCreateJwtAuthenticationToken() { // TODO: move test to refresh token form
$this->mockRequest();
// Token without session
$account = new Account(['id' => 1]);
$token = $this->component->createJwtAuthenticationToken($account);
$payloads = $token->getPayload();
$this->assertEqualsWithDelta(time(), $payloads->findClaimByName('iat')->getValue(), 3);
$this->assertEqualsWithDelta(time() + 60 * 60 * 24 * 7, $payloads->findClaimByName('exp')->getValue(), 3);
$this->assertSame('ely|1', $payloads->findClaimByName('sub')->getValue());
$this->assertSame('accounts_web_user', $payloads->findClaimByName('ely-scopes')->getValue());
$this->assertNull($payloads->findClaimByName('jti'));
$session = new AccountSession(['id' => 2]);
$token = $this->component->createJwtAuthenticationToken($account, $session);
$payloads = $token->getPayload();
$this->assertEqualsWithDelta(time(), $payloads->findClaimByName('iat')->getValue(), 3);
$this->assertEqualsWithDelta(time() + 3600, $payloads->findClaimByName('exp')->getValue(), 3);
$this->assertSame('ely|1', $payloads->findClaimByName('sub')->getValue());
$this->assertSame('accounts_web_user', $payloads->findClaimByName('ely-scopes')->getValue());
$this->assertSame(2, $payloads->findClaimByName('jti')->getValue());
}
public function testRenewJwtAuthenticationToken() { public function testRenewJwtAuthenticationToken() {
$userIP = '192.168.0.1'; $userIP = '192.168.0.1';
$this->mockRequest($userIP); $this->mockRequest($userIP);
@ -83,14 +61,6 @@ class ComponentTest extends TestCase {
$this->assertSame($session->id, $payloads->findClaimByName('jti')->getValue(), 'session has not changed'); $this->assertSame($session->id, $payloads->findClaimByName('jti')->getValue(), 'session has not changed');
} }
public function testParseToken() {
$this->mockRequest();
$account = new Account(['id' => 1]);
$token = $this->component->createJwtAuthenticationToken($account);
$jwt = $this->component->serializeToken($token);
$this->component->parseToken($jwt);
}
public function testGetActiveSession() { public function testGetActiveSession() {
/** @var Account $account */ /** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin'); $account = $this->tester->grabFixture('accounts', 'admin');
@ -172,7 +142,7 @@ class ComponentTest extends TestCase {
private function getComponentConfig() { private function getComponentConfig() {
return [ return [
'identityClass' => Identity::class, 'identityClass' => IdentityFactory::class,
'enableSession' => false, 'enableSession' => false,
'loginUrl' => null, 'loginUrl' => null,
'secret' => 'secret', 'secret' => 'secret',

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,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 <?php
declare(strict_types=1);
namespace api\tests\_support\models\authentication; namespace api\tests\_support\models\authentication;
use api\components\User\AuthenticationResult;
use api\models\authentication\ConfirmEmailForm; use api\models\authentication\ConfirmEmailForm;
use api\tests\unit\TestCase; use api\tests\unit\TestCase;
use common\models\Account; use common\models\Account;
use common\models\AccountSession;
use common\models\EmailActivation; use common\models\EmailActivation;
use common\tests\fixtures\EmailActivationFixture; use common\tests\fixtures\EmailActivationFixture;
@ -21,8 +21,8 @@ class ConfirmEmailFormTest extends TestCase {
$fixture = $this->tester->grabFixture('emailActivations', 'freshRegistrationConfirmation'); $fixture = $this->tester->grabFixture('emailActivations', 'freshRegistrationConfirmation');
$model = $this->createModel($fixture['key']); $model = $this->createModel($fixture['key']);
$result = $model->confirm(); $result = $model->confirm();
$this->assertInstanceOf(AuthenticationResult::class, $result); $this->assertNotNull($result);
$this->assertInstanceOf(AccountSession::class, $result->getSession(), 'session was generated'); $this->assertNotNull($result->getRefreshToken(), 'session was generated');
$activationExists = EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists(); $activationExists = EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists();
$this->assertFalse($activationExists, 'email activation key is not exist'); $this->assertFalse($activationExists, 'email activation key is not exist');
/** @var Account $account */ /** @var Account $account */

View File

@ -1,7 +1,8 @@
<?php <?php
declare(strict_types=1);
namespace api\tests\_support\models\authentication; namespace api\tests\_support\models\authentication;
use api\components\User\AuthenticationResult;
use api\models\authentication\LoginForm; use api\models\authentication\LoginForm;
use api\tests\unit\TestCase; use api\tests\unit\TestCase;
use Codeception\Specify; use Codeception\Specify;
@ -135,7 +136,7 @@ class LoginFormTest extends TestCase {
'status' => Account::STATUS_ACTIVE, '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'); $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'], 'login' => $this->tester->grabFixture('accounts', 'user-with-old-password-type')['username'],
'password' => '12345678', 'password' => '12345678',
]); ]);
$this->assertInstanceOf(AuthenticationResult::class, $model->login()); $this->assertNotNull($model->login());
$this->assertEmpty($model->getErrors()); $this->assertEmpty($model->getErrors());
$this->assertSame( $this->assertSame(
Account::PASS_HASH_STRATEGY_YII2, Account::PASS_HASH_STRATEGY_YII2,

View File

@ -2,7 +2,7 @@
namespace api\tests\_support\models\authentication; namespace api\tests\_support\models\authentication;
use api\components\User\Component; use api\components\User\Component;
use api\components\User\Identity; use api\components\User\IdentityFactory;
use api\models\authentication\LogoutForm; use api\models\authentication\LogoutForm;
use api\tests\unit\TestCase; use api\tests\unit\TestCase;
use Codeception\Specify; use Codeception\Specify;
@ -59,7 +59,7 @@ class LogoutFormTest extends TestCase {
private function getComponentArgs() { private function getComponentArgs() {
return [ return [
'identityClass' => Identity::class, 'identityClass' => IdentityFactory::class,
'enableSession' => false, 'enableSession' => false,
'loginUrl' => null, 'loginUrl' => null,
'secret' => 'secret', 'secret' => 'secret',

View File

@ -1,7 +1,8 @@
<?php <?php
declare(strict_types=1);
namespace api\tests\_support\models\authentication; namespace api\tests\_support\models\authentication;
use api\components\User\AuthenticationResult;
use api\models\authentication\RecoverPasswordForm; use api\models\authentication\RecoverPasswordForm;
use api\tests\unit\TestCase; use api\tests\unit\TestCase;
use common\models\Account; use common\models\Account;
@ -24,8 +25,8 @@ class RecoverPasswordFormTest extends TestCase {
'newRePassword' => '12345678', 'newRePassword' => '12345678',
]); ]);
$result = $model->recoverPassword(); $result = $model->recoverPassword();
$this->assertInstanceOf(AuthenticationResult::class, $result); $this->assertNotNull($result);
$this->assertNull($result->getSession(), 'session was not generated'); $this->assertNull($result->getRefreshToken(), 'session was not generated');
$this->assertFalse(EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists()); $this->assertFalse(EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists());
/** @var Account $account */ /** @var Account $account */
$account = Account::findOne($fixture['account_id']); $account = Account::findOne($fixture['account_id']);

View File

@ -1,7 +1,8 @@
<?php <?php
declare(strict_types=1);
namespace codeception\api\unit\models\authentication; namespace codeception\api\unit\models\authentication;
use api\components\User\AuthenticationResult;
use api\models\authentication\RefreshTokenForm; use api\models\authentication\RefreshTokenForm;
use api\tests\unit\TestCase; use api\tests\unit\TestCase;
use Codeception\Specify; use Codeception\Specify;
@ -44,7 +45,7 @@ class RefreshTokenFormTest extends TestCase {
public function testRenew() { public function testRenew() {
$model = new RefreshTokenForm(); $model = new RefreshTokenForm();
$model->refresh_token = $this->tester->grabFixture('sessions', 'admin')['refresh_token']; $model->refresh_token = $this->tester->grabFixture('sessions', 'admin')['refresh_token'];
$this->assertInstanceOf(AuthenticationResult::class, $model->renew()); $this->assertNotNull($model->renew());
} }
} }

View File

@ -2,7 +2,7 @@
namespace api\tests\unit\modules\accounts\models; namespace api\tests\unit\modules\accounts\models;
use api\components\User\Component; use api\components\User\Component;
use api\components\User\Identity; use api\components\User\IdentityFactory;
use api\modules\accounts\models\ChangePasswordForm; use api\modules\accounts\models\ChangePasswordForm;
use api\tests\unit\TestCase; use api\tests\unit\TestCase;
use common\components\UserPass; use common\components\UserPass;
@ -57,7 +57,7 @@ class ChangePasswordFormTest extends TestCase {
public function testPerformAction() { public function testPerformAction() {
$component = mock(Component::class . '[terminateSessions]', [[ $component = mock(Component::class . '[terminateSessions]', [[
'identityClass' => Identity::class, 'identityClass' => IdentityFactory::class,
'enableSession' => false, 'enableSession' => false,
'loginUrl' => null, 'loginUrl' => null,
'secret' => 'secret', 'secret' => 'secret',
@ -119,7 +119,7 @@ class ChangePasswordFormTest extends TestCase {
/** @var Component|\Mockery\MockInterface $component */ /** @var Component|\Mockery\MockInterface $component */
$component = mock(Component::class . '[terminateSessions]', [[ $component = mock(Component::class . '[terminateSessions]', [[
'identityClass' => Identity::class, 'identityClass' => IdentityFactory::class,
'enableSession' => false, 'enableSession' => false,
'loginUrl' => null, 'loginUrl' => null,
'secret' => 'secret', 'secret' => 'secret',

View File

@ -2,7 +2,7 @@
namespace api\tests\unit\modules\accounts\models; namespace api\tests\unit\modules\accounts\models;
use api\components\User\Component; use api\components\User\Component;
use api\components\User\Identity; use api\components\User\IdentityFactory;
use api\modules\accounts\models\EnableTwoFactorAuthForm; use api\modules\accounts\models\EnableTwoFactorAuthForm;
use api\tests\unit\TestCase; use api\tests\unit\TestCase;
use common\helpers\Error as E; use common\helpers\Error as E;
@ -20,7 +20,7 @@ class EnableTwoFactorAuthFormTest extends TestCase {
/** @var Component|\Mockery\MockInterface $component */ /** @var Component|\Mockery\MockInterface $component */
$component = mock(Component::class . '[terminateSessions]', [[ $component = mock(Component::class . '[terminateSessions]', [[
'identityClass' => Identity::class, 'identityClass' => IdentityFactory::class,
'enableSession' => false, 'enableSession' => false,
'loginUrl' => null, 'loginUrl' => null,
'secret' => 'secret', 'secret' => 'secret',

View File

@ -25,6 +25,7 @@ class Yii extends \yii\BaseYii {
* @property \api\components\OAuth2\Component $oauth * @property \api\components\OAuth2\Component $oauth
* @property \common\components\StatsD $statsd * @property \common\components\StatsD $statsd
* @property \yii\queue\Queue $queue * @property \yii\queue\Queue $queue
* @property \api\components\Tokens\Component $tokens
*/ */
abstract class BaseApplication extends yii\base\Application { abstract class BaseApplication extends yii\base\Application {
} }

View File

@ -6,6 +6,9 @@ return [
'fromEmail' => 'ely@ely.by', 'fromEmail' => 'ely@ely.by',
], ],
'components' => [ 'components' => [
'cache' => [
'class' => \yii\caching\FileCache::class,
],
'security' => [ 'security' => [
// It's allows us to increase tests speed by decreasing password hashing algorithm complexity // It's allows us to increase tests speed by decreasing password hashing algorithm complexity
'passwordHashCost' => 4, 'passwordHashCost' => 4,

View File

@ -19,6 +19,7 @@
"emarref/jwt": "~1.0.3", "emarref/jwt": "~1.0.3",
"goaop/framework": "^2.2.0", "goaop/framework": "^2.2.0",
"guzzlehttp/guzzle": "^6.0.0", "guzzlehttp/guzzle": "^6.0.0",
"lcobucci/jwt": "^3.3",
"league/oauth2-server": "^4.1", "league/oauth2-server": "^4.1",
"mito/yii2-sentry": "^1.0", "mito/yii2-sentry": "^1.0",
"paragonie/constant_time_encoding": "^2.0", "paragonie/constant_time_encoding": "^2.0",

79
composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "80ccf8b828493911307a9daa95021dfc", "content-hash": "2dfa204a51a82cd7c7d6a5b7d1ccbc0c",
"packages": [ "packages": [
{ {
"name": "bacon/bacon-qr-code", "name": "bacon/bacon-qr-code",
@ -54,16 +54,16 @@
}, },
{ {
"name": "beberlei/assert", "name": "beberlei/assert",
"version": "v3.2.0", "version": "v3.2.1",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/beberlei/assert.git", "url": "https://github.com/beberlei/assert.git",
"reference": "fd82f4c8592c8128dd74481034c31da71ebafc56" "reference": "ce139b6bf8f07fb8389d2c8e15b98dc24fdd93c7"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/beberlei/assert/zipball/fd82f4c8592c8128dd74481034c31da71ebafc56", "url": "https://api.github.com/repos/beberlei/assert/zipball/ce139b6bf8f07fb8389d2c8e15b98dc24fdd93c7",
"reference": "fd82f4c8592c8128dd74481034c31da71ebafc56", "reference": "ce139b6bf8f07fb8389d2c8e15b98dc24fdd93c7",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -72,7 +72,7 @@
"require-dev": { "require-dev": {
"friendsofphp/php-cs-fixer": "*", "friendsofphp/php-cs-fixer": "*",
"phpstan/phpstan-shim": "*", "phpstan/phpstan-shim": "*",
"phpunit/phpunit": "*" "phpunit/phpunit": ">=6.0.0 <8"
}, },
"type": "library", "type": "library",
"autoload": { "autoload": {
@ -90,13 +90,13 @@
"authors": [ "authors": [
{ {
"name": "Benjamin Eberlei", "name": "Benjamin Eberlei",
"email": "kontakt@beberlei.de", "role": "Lead Developer",
"role": "Lead Developer" "email": "kontakt@beberlei.de"
}, },
{ {
"name": "Richard Quadling", "name": "Richard Quadling",
"email": "rquadling@gmail.com", "role": "Collaborator",
"role": "Collaborator" "email": "rquadling@gmail.com"
} }
], ],
"description": "Thin assertion library for input validation in business models.", "description": "Thin assertion library for input validation in business models.",
@ -105,7 +105,7 @@
"assertion", "assertion",
"validation" "validation"
], ],
"time": "2018-12-24T15:25:25+00:00" "time": "2019-05-28T15:18:28+00:00"
}, },
{ {
"name": "bower-asset/inputmask", "name": "bower-asset/inputmask",
@ -151,7 +151,7 @@
"version": "v1.3.2", "version": "v1.3.2",
"source": { "source": {
"type": "git", "type": "git",
"url": "git@github.com:bestiejs/punycode.js.git", "url": "https://github.com/bestiejs/punycode.js.git",
"reference": "38c8d3131a82567bfef18da09f7f4db68c84f8a3" "reference": "38c8d3131a82567bfef18da09f7f4db68c84f8a3"
}, },
"dist": { "dist": {
@ -1146,6 +1146,61 @@
], ],
"time": "2013-01-29T21:29:14+00:00" "time": "2013-01-29T21:29:14+00:00"
}, },
{
"name": "lcobucci/jwt",
"version": "3.3.1",
"source": {
"type": "git",
"url": "https://github.com/lcobucci/jwt.git",
"reference": "a11ec5f4b4d75d1fcd04e133dede4c317aac9e18"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/lcobucci/jwt/zipball/a11ec5f4b4d75d1fcd04e133dede4c317aac9e18",
"reference": "a11ec5f4b4d75d1fcd04e133dede4c317aac9e18",
"shasum": ""
},
"require": {
"ext-mbstring": "*",
"ext-openssl": "*",
"php": "^5.6 || ^7.0"
},
"require-dev": {
"mikey179/vfsstream": "~1.5",
"phpmd/phpmd": "~2.2",
"phpunit/php-invoker": "~1.1",
"phpunit/phpunit": "^5.7 || ^7.3",
"squizlabs/php_codesniffer": "~2.3"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.1-dev"
}
},
"autoload": {
"psr-4": {
"Lcobucci\\JWT\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Luís Otávio Cobucci Oblonczyk",
"email": "lcobucci@gmail.com",
"role": "Developer"
}
],
"description": "A simple library to work with JSON Web Token and JSON Web Signature",
"keywords": [
"JWS",
"jwt"
],
"time": "2019-05-24T18:30:49+00:00"
},
{ {
"name": "league/event", "name": "league/event",
"version": "2.2.0", "version": "2.2.0",

View File

@ -1,28 +0,0 @@
-----BEGIN PRIVATE KEY-----
MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQDbTqmRpLg3XjDH
3Z97uHdNq4F5j77Rp+M7ctyfUhtb+U7VWppjk2Dxyp2/iPzKK3K0lC91zlnxO4HT
jFCWTIQzSfiFx/Z6nbUXYFZunzRkbt6UgXjUhnYLSIVvNDneph/BZTSxNThky7a8
weng1+1e7cYcYx7pJWUXB9XINEKdyZ/pF+kB8UPK/LCLY4jFTm7t+N1Rm1R6VpEy
VqhwoDTefkiP9H/QZBp4Ihy48v/NTtgHdsc3Yz+//M6km39MmxIh4wBrZiIictzg
5Xmd1vXamDYFbGZHpKRuujCSufZaglrjGvgaAq1lSS+Cwc5eNCDTlw8OWGJyeSMy
AvYKK5pnAgMBAAECggEBAKcg02kCtsC7L0GhS6Dle0XdpdYWDb2IzErJxghEckUt
QT6mxXGNJxwc5QrKQptvcQLcyy5kC3cjelTVYbSoqzbK8HJDaTsYZKFj8XpsKWlA
dK+H26Vasyr2IXoVuuRKhXjEv9ssS8XE2YYP4URQSb1GRuvrPes/bEKY3fqsmPfU
/rpaUNG9OvskfIDzT+VoEe5RfPW0+uchHZHypWdnhSxLC/oH8KjcUxmCdQ3q46fT
2GhDJnDLXC8MGbyUp7Nw+eSg+4UTCjaNqV7c4vOSXqSBPch7nYFf1YqYuseok21t
UK1G55JrBfsUAmldSi1UVdnAanVRNZiC2LsdDe9PpUECgYEA7kVk7nFqtHqx6EOz
4p6AeDlslrPEWz996AgV1qezBboGlpPkDv+of5cOG4ZMpDJD5KbSIJXTPC06G+3V
VgYpg7cYO9il3I5vaxo64dC9Ib5HQe8UTreVI5763S7Zq7V0jWKOzrlKzA/KQl3x
1kHXS5levDp1uuwAdRBn6DvXnv0CgYEA66ALVI1BUU+OhqSGRQu9pZATfyB5hJaD
1iICiOgl1LRwMJW7/uWUTQ+h5H3lYDmyf+y9/8x8jTfEVZYEwV2bw9wzII87YA9R
pKQl+HMlynrgYWZ2Z94mRFs3poxU8AgpU9MDN84b2cHyP3TGhQjkdtdyFE4lcCiQ
yQqnWa+BBjMCgYEArKeKQKHcoVT7D4PnmIIkM3ng7r7qvPggAv/A219/gNnQplIa
AqhM78+EgHtrk9t8iPY88zG99DANmGlZmlEyyefl3o/ZeB2aLPC/1BvOwOHBfsyA
WZ37qukrfRTS0/LTtxPAyZlI0t9qP3cVo5zoJjbHh/uQjdcvaaRutsCOOP0CgYEA
10TB9T6UdVgM6+A2N7CxVCicV2HxA3yL+D/cNv55SaqMcSbrucY/xmPI0btfq5kr
BorhT2mgRVi0zEiiEZOXMsrj/xQ899cnDRdXBXUWCrZWd0YoWV7xcTQxVL0TALVE
JKw9XWe1tC3oR6dFk9d6+0R8miaHN8An/zT3jg21AFcCgYEAslWiTkT1ULAAhlHa
KLbSW1slYJR8/i9mwIDOoD2BvVJUSqbowAogD4mXRm6S77AxoQX4nygzE6XscR4V
h+fINRJeh7yrFk5x/GUjh7tQo9EITjY89X0s35hZ27i61l66eZ5u06j4xE5+Y424
HMsBjKAmKFNPebTWFcAlXXaeCPU=
-----END PRIVATE KEY-----

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

View File

@ -1,16 +0,0 @@
-----BEGIN CERTIFICATE-----
MIICljCCAX4CCQDA6sdDyK1Y/zANBgkqhkiG9w0BAQsFADANMQswCQYDVQQGEwJC
WTAeFw0xOTA3MjQxMDI5NTdaFw0yMTA3MjMxMDI5NTdaMA0xCzAJBgNVBAYTAkJZ
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA206pkaS4N14wx92fe7h3
TauBeY++0afjO3Lcn1IbW/lO1VqaY5Ng8cqdv4j8yitytJQvdc5Z8TuB04xQlkyE
M0n4hcf2ep21F2BWbp80ZG7elIF41IZ2C0iFbzQ53qYfwWU0sTU4ZMu2vMHp4Nft
Xu3GHGMe6SVlFwfVyDRCncmf6RfpAfFDyvywi2OIxU5u7fjdUZtUelaRMlaocKA0
3n5Ij/R/0GQaeCIcuPL/zU7YB3bHN2M/v/zOpJt/TJsSIeMAa2YiInLc4OV5ndb1
2pg2BWxmR6Skbrowkrn2WoJa4xr4GgKtZUkvgsHOXjQg05cPDlhicnkjMgL2Ciua
ZwIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQB+i6Q3Ltg5MPEqHZ3GCpsFMV+xWKp5
TSgguFr422az9v/Da01VHOX884D0dZt1r6W+zzfIQzIXpRqQkl4YuS1N17Q/KN3E
7rJ0R7gsXM7+KiGVrZyoZlxRaRXCiErUWBOxamIPy07zOWLnWa1kZZNDvgiurMbF
yaREQargFM8G91zkA6XiMXFoermARYB6RLtyHD0EC3I2DSZpOuMD9Kg1k/uw6f3W
xwsQY6kpzoZkYfTqoM4ky16yNPRf9vsej2dYlRr1YPWWQOicY1TrwFJMKoogylTD
lN61u8WED7Z8M00F6FYuuFffzt2Si9GrYeTuf8ZShpKiDqK0P22oiAao
-----END CERTIFICATE-----

4
data/certs/public.pem Normal file
View File

@ -0,0 +1,4 @@
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEv6ENZA59mzFvoDKTX3BI3Nx6di+x
WnsOAo9+zx0hnMnfzdhOS930ocFTBcyZmmF7iM7nhGicfiDfJKIyV8w+BA==
-----END PUBLIC KEY-----