RefreshTokenTest.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. namespace YdbPlatform\Ydb\Test;
  3. use PHPUnit\Framework\TestCase;
  4. use YdbPlatform\Ydb\Auth\Auth;
  5. use YdbPlatform\Ydb\Auth\TokenInfo;
  6. use YdbPlatform\Ydb\Ydb;
  7. class FakeCredentials extends Auth {
  8. /**
  9. * @var int
  10. */
  11. protected $counter;
  12. protected $tokenLiveTime;
  13. public function __construct(&$counter, &$tokenLiveTime)
  14. {
  15. $this->counter = &$counter;
  16. $this->tokenLiveTime = &$tokenLiveTime;
  17. }
  18. public function getTokenInfo(): TokenInfo
  19. {
  20. $this->counter++;
  21. if ($this->counter==2){
  22. throw new \Exception("Some error");
  23. }
  24. return new TokenInfo(time()+$this->tokenLiveTime,time()+$this->tokenLiveTime);
  25. }
  26. public function getName(): string
  27. {
  28. return "FakeCredentials";
  29. }
  30. }
  31. class MetaGetter extends \YdbPlatform\Ydb\Session{
  32. public static function getMeta(\YdbPlatform\Ydb\Session $session){
  33. return $session->meta;
  34. }
  35. }
  36. class RefreshTokenTest extends TestCase
  37. {
  38. public function testRefreshToken(){
  39. $counter = 0;
  40. $TOKEN_LIVE_TIME = 10;
  41. $config = [
  42. // Database path
  43. 'database' => '/local',
  44. // Database endpoint
  45. 'endpoint' => 'localhost:2136',
  46. // Auto discovery (dedicated server only)
  47. 'discovery' => false,
  48. // IAM config
  49. 'iam_config' => [
  50. 'insecure' => true,
  51. ],
  52. 'credentials' => new FakeCredentials($counter, $TOKEN_LIVE_TIME)
  53. ];
  54. $ydb = new Ydb($config);
  55. $table = $ydb->table();
  56. $session = $table->createSession();
  57. $token = MetaGetter::getMeta($session)["x-ydb-auth-ticket"][0];
  58. self::assertEquals(
  59. 1,
  60. $counter
  61. );
  62. // Check that the token will not be updated until a refresh time
  63. $session->query('select 1 as res');
  64. self::assertEquals(
  65. 1,
  66. $counter
  67. );
  68. self::assertEquals(
  69. $token,
  70. MetaGetter::getMeta($session)["x-ydb-auth-ticket"][0]
  71. );
  72. // Check that sdk used old token when failed refreshing
  73. usleep($ydb->iam()->config('credentials')->getRefreshTokenRatio()*$TOKEN_LIVE_TIME*1000*1000); // waiting 10% from token live time
  74. $session->query('select 1 as res');
  75. self::assertEquals(
  76. 2,
  77. $counter
  78. );
  79. self::assertEquals(
  80. $token,
  81. MetaGetter::getMeta($session)["x-ydb-auth-ticket"][0]
  82. );
  83. // Check that token refreshed
  84. $session->query('select 1 as res');
  85. self::assertEquals(
  86. 3,
  87. $counter
  88. );
  89. self::assertNotEquals(
  90. $token,
  91. MetaGetter::getMeta($session)["x-ydb-auth-ticket"][0]
  92. );
  93. }
  94. }