TokenTest.php 11.7 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Magento\Integration\Model\ResourceModel\Oauth;

use Magento\Authorization\Model\UserContextInterface;
use Magento\Integration\Model\Oauth\Token;

/**
 * Integration test for @see \Magento\Integration\Model\ResourceModel\Oauth\Token
 *
 * Also tests @see \Magento\Integration\Cron\CleanExpiredTokens
 */
class TokenTest extends \PHPUnit\Framework\TestCase
{
    const TOKEN_LIFETIME = 1; // in hours
    
    const BASE_CREATED_AT_TIMESTAMP = 100000;
    
    /**
     * @var array
     */
    private $generatedTokens;

    /**
     * @var \Magento\Framework\Stdlib\DateTime\DateTime | \PHPUnit_Framework_MockObject_MockObject
     */
    private $dateTimeMock;

    /**
     * @var \Magento\Integration\Model\ResourceModel\Oauth\Token
     */
    private $tokenResourceModel;

    /**
     * @var \Magento\Framework\ObjectManagerInterface
     */
    private $objectManager;

    /**
     * @var \Magento\Integration\Model\Oauth\TokenFactory
     */
    private $tokenFactory;

    protected function setUp()
    {
        $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
        $this->tokenFactory = $this->objectManager->create(\Magento\Integration\Model\Oauth\TokenFactory::class);

        /** Mock date model to be able to specify "current timestamp" and avoid dependency on real timestamp */
        $this->dateTimeMock = $this->getMockBuilder(\Magento\Framework\Stdlib\DateTime\DateTime::class)
            ->disableOriginalConstructor()
            ->getMock();
        /** @var \Magento\Integration\Model\ResourceModel\Oauth\Token $tokenResourceModel */
        $this->tokenResourceModel = $this->objectManager->create(
            \Magento\Integration\Model\ResourceModel\Oauth\Token::class,
            ['date' => $this->dateTimeMock]
        );

        $this->generatedTokens = $this->generateTokens();

        parent::setUp();
    }

    /**
     * @return array
     */
    private function generateTokens()
    {
        /** Generate several tokens with different user types and created at combinations */
        $tokensToBeGenerated = [
            '#1' => [
                'userType' => UserContextInterface::USER_TYPE_ADMIN,
                'createdAt' => self::BASE_CREATED_AT_TIMESTAMP
            ],
            '#2' => [
                'userType' => UserContextInterface::USER_TYPE_ADMIN,
                'createdAt' => self::BASE_CREATED_AT_TIMESTAMP + 5
            ],
            '#3' => [
                'userType' => UserContextInterface::USER_TYPE_CUSTOMER,
                'createdAt' => self::BASE_CREATED_AT_TIMESTAMP
            ],
            '#4' => [
                'userType' => UserContextInterface::USER_TYPE_CUSTOMER,
                'createdAt' => self::BASE_CREATED_AT_TIMESTAMP - 5
            ],
            '#5' => [
                'userType' => UserContextInterface::USER_TYPE_INTEGRATION,
                'createdAt' => self::BASE_CREATED_AT_TIMESTAMP
            ],
            '#6' => [
                'userType' => UserContextInterface::USER_TYPE_INTEGRATION,
                'createdAt' => self::BASE_CREATED_AT_TIMESTAMP + 5
            ],
        ];
        /** @var \Magento\Framework\Stdlib\DateTime $dateTimeUtils */
        $dateTimeUtils = $this->objectManager->get(\Magento\Framework\Stdlib\DateTime::class);
        foreach ($tokensToBeGenerated as &$tokenData) {
            $token = $this->tokenFactory->create();
            $token->setType(Token::TYPE_ACCESS)
                ->setUserType($tokenData['userType'])
                ->setToken(rand(1, PHP_INT_MAX))
                ->setCreatedAt($dateTimeUtils->formatDate($tokenData['createdAt']));
            $this->tokenResourceModel->save($token);
            $tokenData['tokenId'] = $token->getId();
        }
        return $tokensToBeGenerated;
    }

    /**
     * Make sure that @see \Magento\Integration\Cron\CleanExpiredTokens cleans tokens correctly per configuration
     *
     * 1. Generate several tokens with different user type and creation time
     * 2. Emulate current time stamp to be equal to (expiration period + some adjustment)
     * 3. Run clean up
     * 4. Make sure that clean up removed tokens that were expected to be removed,
     *    and those tokens which were not expected to be removed are still there
     *
     * @param int $secondsAfterBaseCreatedTimestamp
     * @param array $expectedRemovedTokenNumbers
     * @param array $expectedPreservedTokenNumbers
     *
     * @dataProvider deleteExpiredTokenUsingObserverDataProvider
     * @covers \Magento\Integration\Cron\CleanExpiredTokens::execute
     */
    public function testDeleteExpiredTokenUsingObserver(
        $secondsAfterBaseCreatedTimestamp,
        $expectedRemovedTokenNumbers,
        $expectedPreservedTokenNumbers
    ) {
        /** @var \Magento\Integration\Cron\CleanExpiredTokens $cleanExpiredTokensModel */
        $cleanExpiredTokensModel = $this->objectManager->create(
            \Magento\Integration\Cron\CleanExpiredTokens::class,
            ['tokenResourceModel' => $this->tokenResourceModel]
        );

        $emulatedCurrentTimestamp = self::BASE_CREATED_AT_TIMESTAMP + $secondsAfterBaseCreatedTimestamp;
        $this->dateTimeMock->method('gmtTimestamp')->willReturn($emulatedCurrentTimestamp);
        $cleanExpiredTokensModel->execute();
        $this->assertTokenCleanUp(
            $expectedRemovedTokenNumbers,
            $expectedPreservedTokenNumbers,
            $this->generatedTokens
        );
    }

    public function deleteExpiredTokenUsingObserverDataProvider()
    {
        return [
            "Clean up long before default admin and default customer token life time" => [
                3600 - 6, // time passed after base creation time
                [], // expected to be removed
                ['#1', '#2', '#3', '#4', '#5', '#6'], // expected to exist
            ],
            "Clean up just before default admin and default customer token life time" => [
                3600 - 1, // time passed after base creation time
                ['#4'], // expected to be removed
                ['#1', '#2', '#3', '#5', '#6'], // expected to exist
            ],
            "Clean up after default admin token life time, but before default customer token life time" => [
                3600 + 1, // time passed after base creation time
                ['#3', '#4'], // expected to be removed
                ['#1', '#2', '#5', '#6'], // expected to exist
            ],
            "Clean up after default customer and default admin token life time" => [
                14400 + 1, // time passed after base creation time
                ['#1', '#3', '#4'], // expected to be removed
                ['#2', '#5', '#6'], // expected to exist
            ],
        ];
    }

    /**
     * Verify that expired tokens removal works as expected, @see \Magento\Integration\Model\ResourceModel\Oauth\Token
     *
     * 1. Generate several tokens with different user type and creation time
     * 2. Emulate current time stamp to be equal to (expiration period + some adjustment)
     * 3. Run clean up for some token types
     * 4. Make sure that clean up removed tokens that were expected to be removed,
     *    and those tokens which were not expected to be removed are still there
     *
     * @param $secondsAfterBaseCreatedTimestamp
     * @param $tokenTypesToClean
     * @param $expectedRemovedTokenNumbers
     * @param $expectedPreservedTokenNumbers
     *
     * @magentoDbIsolation enabled
     * @dataProvider deleteExpiredTokensDataProvider
     * @covers \Magento\Integration\Model\ResourceModel\Oauth\Token::deleteExpiredTokens
     */
    public function testDeleteExpiredTokens(
        $secondsAfterBaseCreatedTimestamp,
        $tokenTypesToClean,
        $expectedRemovedTokenNumbers,
        $expectedPreservedTokenNumbers
    ) {
        /** Run clean up for tokens of {$tokenTypesToClean} type, created {$secondsAfterBaseCreatedTimestamp} ago */
        $emulatedCurrentTimestamp = self::BASE_CREATED_AT_TIMESTAMP + $secondsAfterBaseCreatedTimestamp;
        $this->dateTimeMock->method('gmtTimestamp')->willReturn($emulatedCurrentTimestamp);
        $this->tokenResourceModel->deleteExpiredTokens(self::TOKEN_LIFETIME, $tokenTypesToClean);
        $this->assertTokenCleanUp(
            $expectedRemovedTokenNumbers,
            $expectedPreservedTokenNumbers,
            $this->generatedTokens
        );
    }

    public function deleteExpiredTokensDataProvider()
    {
        return [
          "Clean up for admin tokens which were created ('token_lifetime' + 1 second) ago" => [
              self::TOKEN_LIFETIME * 60 * 60 + 1, // time passed after base creation time
              [UserContextInterface::USER_TYPE_ADMIN], // token types to clean up
              ['#1'], // expected to be removed
              ['#2', '#3', '#4', '#5', '#6'], // expected to exist
          ],
          "Clean up for admin, integration, guest tokens which were created ('token_lifetime' + 6 second) ago" => [
              self::TOKEN_LIFETIME * 60 * 60 + 6, // time passed after base creation time
              [ // token types to clean up
                  UserContextInterface::USER_TYPE_ADMIN,
                  UserContextInterface::USER_TYPE_INTEGRATION,
                  UserContextInterface::USER_TYPE_GUEST
              ],
              ['#1', '#2', '#5', '#6'], // expected to be removed
              ['#3', '#4'], // expected to exist
          ],
          "Clean up for admin, integration, customer tokens which were created ('token_lifetime' + 6 second) ago" => [
              self::TOKEN_LIFETIME * 60 * 60 + 6, // time passed after base creation time
              [ // token types to clean up
                  UserContextInterface::USER_TYPE_ADMIN,
                  UserContextInterface::USER_TYPE_INTEGRATION,
                  UserContextInterface::USER_TYPE_CUSTOMER
              ],
              ['#1', '#2', '#3', '#4', '#5', '#6'], // expected to be removed
              [], // expected to exist
          ],
          "Clean up for admin, integration, customer tokens which were created ('token_lifetime' + 1 second) ago" => [
              self::TOKEN_LIFETIME * 60 * 60 + 1, // time passed after base creation time
              [ // token types to clean up
                  UserContextInterface::USER_TYPE_ADMIN,
                  UserContextInterface::USER_TYPE_INTEGRATION,
                  UserContextInterface::USER_TYPE_CUSTOMER
              ],
              ['#1', '#3', '#4', '#5'], // expected to be removed
              ['#2', '#6'], // expected to exist
          ],
        ];
    }

    /**
     * Make that only expired tokens were cleaned up
     *
     * @param array $expectedRemovedTokenNumbers
     * @param array $expectedPreservedTokenNumbers
     * @param array $generatedTokens
     */
    private function assertTokenCleanUp(
        $expectedRemovedTokenNumbers,
        $expectedPreservedTokenNumbers,
        $generatedTokens
    ) {
        foreach ($expectedRemovedTokenNumbers as $tokenNumber) {
            $token = $this->tokenFactory->create();
            $this->tokenResourceModel->load($token, $generatedTokens[$tokenNumber]['tokenId']);
            $this->assertEmpty(
                $token->getId(),
                "Token {$tokenNumber} was expected to be deleted after clean up"
            );
        }
        foreach ($expectedPreservedTokenNumbers as $tokenNumber) {
            $token = $this->tokenFactory->create();
            $this->tokenResourceModel->load($token, $generatedTokens[$tokenNumber]['tokenId']);
            $this->assertEquals(
                $generatedTokens[$tokenNumber]['tokenId'],
                $token->getId(),
                "Token {$tokenNumber} was NOT expected to be deleted after clean up"
            );
        }
    }
}