diff --git a/src/Credential/CredentialModel.php b/src/Credential/CredentialModel.php index ab0fd02..8d516d9 100644 --- a/src/Credential/CredentialModel.php +++ b/src/Credential/CredentialModel.php @@ -28,6 +28,9 @@ public function toMap() if (null !== $this->type) { $res['type'] = $this->type; } + if (null !== $this->providerName) { + $res['providerName'] = $this->providerName; + } return $res; } /** @@ -52,6 +55,9 @@ public static function fromMap($map = []) if (isset($map['type'])) { $model->type = $map['type']; } + if(isset($map['providerName'])){ + $model->providerName = $map['providerName']; + } return $model; } /** @@ -85,6 +91,13 @@ public static function fromMap($map = []) */ public $type; + /** + * @description provider name + * @example cli_profile/static_ak + * @var string + */ + public $providerName; + /** * @return string */ @@ -122,4 +135,9 @@ public function getType() return $this->type; } + public function getProviderName() + { + return $this->providerName; + } + } diff --git a/src/Credential/RefreshResult.php b/src/Credential/RefreshResult.php index db926f5..fd83446 100644 --- a/src/Credential/RefreshResult.php +++ b/src/Credential/RefreshResult.php @@ -4,17 +4,24 @@ use AlibabaCloud\Credentials\Providers\Credentials; +use function PHPUnit\Framework\isNull; + class RefreshResult { - public function __construct($credentials = [], $staleTime = null, $prefetchTime = null) + + /** + * RefreshResult constructor. + * @param Credentials $params + * @param int $staleTime + * @param int $prefetchTime + */ + public function __construct($credentials = null, $staleTime = PHP_INT_MAX, $prefetchTime = PHP_INT_MAX) { $this->credentials = $credentials; - $this->staleTime = $staleTime ? $staleTime : PHP_INT_MAX; - $this->prefetchTime = $prefetchTime ? $prefetchTime : PHP_INT_MAX; - } - public function validate() - { + $this->staleTime = $staleTime; + $this->prefetchTime = $prefetchTime; } + public function validate() {} public function toMap() { $res = []; @@ -89,5 +96,4 @@ public function prefetchTime() { return $this->prefetchTime; } - } diff --git a/src/CredentialsProviderWrap.php b/src/CredentialsProviderWrap.php index 23b399e..4e8611e 100644 --- a/src/CredentialsProviderWrap.php +++ b/src/CredentialsProviderWrap.php @@ -46,6 +46,7 @@ public function getCredential() 'accessKeySecret' => $credentials->getAccessKeySecret(), 'securityToken' => $credentials->getSecurityToken(), 'type' => $this->typeName, + 'providerName' => $credentials->getProviderName(), ]); } diff --git a/src/Providers/CLIProfileCredentialsProvider.php b/src/Providers/CLIProfileCredentialsProvider.php index a8d8716..f627668 100644 --- a/src/Providers/CLIProfileCredentialsProvider.php +++ b/src/Providers/CLIProfileCredentialsProvider.php @@ -97,7 +97,10 @@ protected function reloadCredentialsProvider($profileFile, $profileName) 'roleArn' => Helper::unsetReturnNull($profile, 'ram_role_arn'), 'roleSessionName' => Helper::unsetReturnNull($profile, 'ram_session_name'), 'durationSeconds' => Helper::unsetReturnNull($profile, 'expired_seconds'), + 'policy' => Helper::unsetReturnNull($profile, 'policy'), + 'externalId' => Helper::unsetReturnNull($profile, 'external_id'), 'stsRegionId' => Helper::unsetReturnNull($profile, 'sts_region'), + 'enableVpc' => Helper::unsetReturnNull($profile, 'enable_vpc'), ]); case 'EcsRamRole': return new EcsRamRoleCredentialsProvider([ @@ -110,7 +113,9 @@ protected function reloadCredentialsProvider($profileFile, $profileName) 'oidcTokenFilePath' => Helper::unsetReturnNull($profile, 'oidc_token_file'), 'roleSessionName' => Helper::unsetReturnNull($profile, 'ram_session_name'), 'durationSeconds' => Helper::unsetReturnNull($profile, 'expired_seconds'), + 'policy' => Helper::unsetReturnNull($profile, 'policy'), 'stsRegionId' => Helper::unsetReturnNull($profile, 'sts_region'), + 'enableVpc' => Helper::unsetReturnNull($profile, 'enable_vpc'), ]); case 'ChainableRamRoleArn': $previousProvider = $this->reloadCredentialsProvider($profileFile, Helper::unsetReturnNull($profile, 'source_profile')); @@ -119,7 +124,10 @@ protected function reloadCredentialsProvider($profileFile, $profileName) 'roleArn' => Helper::unsetReturnNull($profile, 'ram_role_arn'), 'roleSessionName' => Helper::unsetReturnNull($profile, 'ram_session_name'), 'durationSeconds' => Helper::unsetReturnNull($profile, 'expired_seconds'), + 'policy' => Helper::unsetReturnNull($profile, 'policy'), + 'externalId' => Helper::unsetReturnNull($profile, 'external_id'), 'stsRegionId' => Helper::unsetReturnNull($profile, 'sts_region'), + 'enableVpc' => Helper::unsetReturnNull($profile, 'enable_vpc'), ]); default: throw new RuntimeException('Unsupported credential mode from CLI credentials file: ' . Helper::unsetReturnNull($profile, 'mode')); diff --git a/src/Providers/DefaultCredentialsProvider.php b/src/Providers/DefaultCredentialsProvider.php index 8713f21..c4725b9 100644 --- a/src/Providers/DefaultCredentialsProvider.php +++ b/src/Providers/DefaultCredentialsProvider.php @@ -79,12 +79,10 @@ private function createDefaultChain() self::$defaultProviders, new ProfileCredentialsProvider() ); - if (Helper::envNotEmpty('ALIBABA_CLOUD_ECS_METADATA')) { - array_push( - self::$defaultProviders, - new EcsRamRoleCredentialsProvider() - ); - } + array_push( + self::$defaultProviders, + new EcsRamRoleCredentialsProvider() + ); if (Helper::envNotEmpty('ALIBABA_CLOUD_CREDENTIALS_URI')) { array_push( self::$defaultProviders, diff --git a/src/Providers/EcsRamRoleCredentialsProvider.php b/src/Providers/EcsRamRoleCredentialsProvider.php index 05d9056..8dffb50 100644 --- a/src/Providers/EcsRamRoleCredentialsProvider.php +++ b/src/Providers/EcsRamRoleCredentialsProvider.php @@ -52,12 +52,12 @@ class EcsRamRoleCredentialsProvider extends SessionCredentialsProvider /** * @var int */ - private $connectTimeout = 5; + private $connectTimeout = 1; /** * @var int */ - private $readTimeout = 5; + private $readTimeout = 1; /** @@ -97,10 +97,6 @@ private function filterRoleName(array $params) if (isset($params['roleName'])) { $this->roleName = $params['roleName']; } - - if (is_null($this->roleName) || $this->roleName === '') { - $this->roleName = $this->getRoleNameFromMeta(); - } } private function filterDisableECSIMDSv1($params) @@ -124,6 +120,14 @@ private function filterDisableECSIMDSv1($params) */ public function refreshCredentials() { + if (Helper::envNotEmpty('ALIBABA_CLOUD_ECS_METADATA_DISABLED') && Helper::env('ALIBABA_CLOUD_ECS_METADATA_DISABLED') === true) { + throw new RuntimeException('IMDS credentials is disabled'); + } + + if (is_null($this->roleName) || $this->roleName === '') { + $this->roleName = $this->getRoleNameFromMeta(); + } + $url = $this->metadataHost . $this->ecsUri . $this->roleName; $options = Request::commonOptions(); $options['read_timeout'] = $this->readTimeout; @@ -231,7 +235,8 @@ private function getMetadataToken() /** * @var int */ - public function getPrefetchTime($expiration) { + public function getPrefetchTime($expiration) + { return $expiration <= 0 ? time() + (5 * 60) : time() + (60 * 60); diff --git a/src/Providers/EnvironmentVariableCredentialsProvider.php b/src/Providers/EnvironmentVariableCredentialsProvider.php index 5baad30..b6dd579 100644 --- a/src/Providers/EnvironmentVariableCredentialsProvider.php +++ b/src/Providers/EnvironmentVariableCredentialsProvider.php @@ -16,9 +16,7 @@ class EnvironmentVariableCredentialsProvider implements CredentialsProvider /** * EnvironmentVariableCredentialsProvider constructor. */ - public function __construct() - { - } + public function __construct() {} /** * Get credential. @@ -42,11 +40,17 @@ public function getCredentials() if (Helper::envNotEmpty('ALIBABA_CLOUD_SECURITY_TOKEN')) { $securityToken = Helper::env('ALIBABA_CLOUD_SECURITY_TOKEN'); + return new Credentials([ + 'accessKeyId' => $accessKeyId, + 'accessKeySecret' => $accessKeySecret, + 'securityToken' => $securityToken, + 'providerName' => $this->getProviderName(), + ]); } + return new Credentials([ 'accessKeyId' => $accessKeyId, 'accessKeySecret' => $accessKeySecret, - 'securityToken' => $securityToken, 'providerName' => $this->getProviderName(), ]); } @@ -58,4 +62,4 @@ public function getProviderName() { return "env"; } -} \ No newline at end of file +} diff --git a/src/Providers/SessionCredentialsProvider.php b/src/Providers/SessionCredentialsProvider.php index fc1cf76..60b92de 100644 --- a/src/Providers/SessionCredentialsProvider.php +++ b/src/Providers/SessionCredentialsProvider.php @@ -54,10 +54,7 @@ protected function cache(RefreshResult $credential) */ public function getCredentials() { - if ($this->cacheIsStale()) { - $result = $this->refreshCredentials(); - $this->cache($result); - }else if ($this->shouldInitiateCachePrefetch()) { + if ($this->cacheIsStale() || $this->shouldInitiateCachePrefetch()) { $result = $this->refreshCache(); $this->cache($result); } @@ -68,38 +65,42 @@ public function getCredentials() } /** - * @var RefreshResult + * @return RefreshResult */ - public function refreshCache() + protected function refreshCache() { - try{ - return($this->handleFetchedSuccess($this->refreshCredentials())); - }catch (\Exception $e){ - $this->handleFetchedFailure($e); + try { + return $this->handleFetchedSuccess($this->refreshCredentials()); + } catch (\Exception $e) { + return $this->handleFetchedFailure($e); } } + /** + * @return RefreshResult + * @throws \Exception + */ protected function handleFetchedFailure(\Exception $e) { $currentCachedValue = $this->getCredentialsInCache(); - if(is_null($currentCachedValue)){ + if (is_null($currentCachedValue)) { throw $e; } - - if(time() < $currentCachedValue->staleTime()){ + + if (time() < $currentCachedValue->staleTime()) { return $currentCachedValue; } throw $e; } /** - * @var RefreshResult + * @return RefreshResult */ protected function handleFetchedSuccess(RefreshResult $value) { $now = time(); // 过期时间大于15分钟,不用管 - if($now < $value->staleTime()){ + if ($now < $value->staleTime()) { return $value; } // 不足或等于15分钟,但未过期,下次会再次刷新 @@ -108,8 +109,8 @@ protected function handleFetchedSuccess(RefreshResult $value) return $value; } // 已过期,看缓存,缓存若大于15分钟,返回缓存,若小于15分钟,则稍后重试 - if (is_null( $this->getCredentialsInCache())){ - throw new \Exception("No cached value was found."); + if (is_null($this->getCredentialsInCache())) { + throw new \Exception("The fetched credentials have expired and no cache is available."); } else if ($now < $this->getCredentialsInCache()->staleTime()) { return $this->getCredentialsInCache(); } else { @@ -121,29 +122,31 @@ protected function handleFetchedSuccess(RefreshResult $value) } /** - * @var bool + * @return bool */ - public function cacheIsStale() + protected function cacheIsStale() { - return $this->getCredentialsInCache() === null || time() >= $this->getCredentialsInCache()->staleTime(); + return is_null($this->getCredentialsInCache()) || time() >= $this->getCredentialsInCache()->staleTime(); } /** - * @var bool + * @return bool */ - private function shouldInitiateCachePrefetch() { - return $this->getCredentialsInCache() === null || time() >= $this->getCredentialsInCache()->prefetchTime(); + protected function shouldInitiateCachePrefetch() + { + return is_null($this->getCredentialsInCache()) || time() >= $this->getCredentialsInCache()->prefetchTime(); } /** - * @var int + * @return int */ - public function getStaleTime($expiration) { + public function getStaleTime($expiration) + { return $expiration <= 0 ? - time() + (60 * 60) : + time() + (60 * 60) : $expiration - (15 * 60); } - + /** * @return RefreshResult */ diff --git a/tests/Feature/CredentialTest.php b/tests/Feature/CredentialTest.php index f6084f1..c6c81fa 100644 --- a/tests/Feature/CredentialTest.php +++ b/tests/Feature/CredentialTest.php @@ -35,9 +35,9 @@ public function testEcsRamRoleCredential() $this->expectException(\GuzzleHttp\Exception\ConnectException::class); if (method_exists($this, 'expectExceptionMessageMatches')) { - $this->expectExceptionMessageMatches('/Connection timeout/'); + $this->expectExceptionMessageMatches('/Timeout was reached/'); } elseif (method_exists($this, 'expectExceptionMessageRegExp')) { - $this->expectExceptionMessageRegExp('/Connection timeout/'); + $this->expectExceptionMessageRegExp('/Timeout was reached/'); } // Assert diff --git a/tests/Unit/EcsRamRoleCredentialTest.php b/tests/Unit/EcsRamRoleCredentialTest.php index 84fb770..a92ecee 100644 --- a/tests/Unit/EcsRamRoleCredentialTest.php +++ b/tests/Unit/EcsRamRoleCredentialTest.php @@ -102,9 +102,15 @@ public function testDefault() Credentials::mockResponse(200, [], 'Token'); Credentials::mockResponse(200, [], 'RoleName'); Credentials::mockResponse(200, [], 'Token'); + Credentials::mockResponse(200, [], $result); + Credentials::mockResponse(200, [], 'Token'); Credentials::mockResponse(200, [], 'RoleName'); Credentials::mockResponse(200, [], 'Token'); + Credentials::mockResponse(200, [], $result); + Credentials::mockResponse(200, [], 'Token'); Credentials::mockResponse(200, [], 'RoleName'); + Credentials::mockResponse(200, [], 'Token'); + Credentials::mockResponse(200, [], $result); $this->credential = new EcsRamRoleCredential(); self::assertEquals('foo', $this->credential->getAccessKeyId()); @@ -114,6 +120,9 @@ public function testDefault() Credentials::mockResponse(200, [], 'Token'); Credentials::mockResponse(200, [], 'RoleName'); + Credentials::mockResponse(200, [], 'Token'); + Credentials::mockResponse(200, [], $result); + $credentialModel = $this->credential->getCredential(); $this->assertEquals('foo', $credentialModel->getAccessKeyId()); $this->assertEquals('bar', $credentialModel->getAccessKeySecret()); @@ -336,9 +345,9 @@ public function testStsWithoutMock() $this->expectException(RuntimeException::class); if (method_exists($this, 'expectExceptionMessageMatches')) { - $this->expectExceptionMessageMatches('/Connection timeout/'); + $this->expectExceptionMessageMatches('/Timeout was reached/'); } elseif (method_exists($this, 'expectExceptionMessageRegExp')) { - $this->expectExceptionMessageRegExp('/Connection timeout/'); + $this->expectExceptionMessageRegExp('/Timeout was reached/'); } // Test self::assertEquals('foo', $credential->getAccessKeyId()); @@ -375,7 +384,6 @@ public function testGetRoleNameFromMeta404() $this->expectExceptionMessage('The role name was not found in the instance'); $provider->getRoleNameFromMeta(); - } public function testRoleNameFromMetaError() diff --git a/tests/Unit/Ini/VirtualCLIConfig.php b/tests/Unit/Ini/VirtualCLIConfig.php index 0710c9c..c86b90e 100644 --- a/tests/Unit/Ini/VirtualCLIConfig.php +++ b/tests/Unit/Ini/VirtualCLIConfig.php @@ -144,7 +144,10 @@ public static function full() "ram_role_arn": "ram_role_arn", "ram_session_name": "ram_session_name", "expired_seconds": 3600, - "sts_region": "cn-hangzhou" + "policy": "policy", + "external_id": "external_id", + "sts_region": "cn-hangzhou", + "enable_vpc": false }, { "name": "EcsRamRole", @@ -159,7 +162,9 @@ public static function full() "oidc_provider_arn": "oidc_provider_arn", "ram_session_name": "ram_session_name", "expired_seconds": 3600, - "sts_region": "cn-hangzhou" + "policy": "policy", + "sts_region": "cn-hangzhou", + "enable_vpc": false }, { "name": "ChainableRamRoleArn", @@ -168,7 +173,10 @@ public static function full() "ram_role_arn": "ram_role_arn", "ram_session_name": "ram_session_name", "expired_seconds": 3600, - "sts_region": "cn-hangzhou" + "policy": "policy", + "external_id": "external_id", + "sts_region": "cn-hangzhou", + "enable_vpc": false } ] } diff --git a/tests/Unit/Providers/DefaultCredentialsProviderTest.php b/tests/Unit/Providers/DefaultCredentialsProviderTest.php index 914d005..5769acd 100644 --- a/tests/Unit/Providers/DefaultCredentialsProviderTest.php +++ b/tests/Unit/Providers/DefaultCredentialsProviderTest.php @@ -60,12 +60,17 @@ public function testDefaultProviderWithEnv() { putenv("ALIBABA_CLOUD_ACCESS_KEY_ID=id"); putenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET=secret"); - putenv("ALIBABA_CLOUD_SECURITY_TOKEN=token"); $provider = new DefaultCredentialsProvider(); $credentials = $provider->getCredentials(); self::assertEquals("id", $credentials->getAccessKeyId()); self::assertEquals("secret", $credentials->getAccessKeySecret()); + self::assertEquals("default/env", $credentials->getProviderName()); + + putenv("ALIBABA_CLOUD_SECURITY_TOKEN=token"); + $credentials = $provider->getCredentials(); + self::assertEquals("id", $credentials->getAccessKeyId()); + self::assertEquals("secret", $credentials->getAccessKeySecret()); self::assertEquals("token", $credentials->getSecurityToken()); self::assertEquals("default/env", $credentials->getProviderName()); @@ -147,6 +152,7 @@ public function testDefaultProviderWithIMDS() public function testDefaultProviderWithURI() { + putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED=true"); putenv("ALIBABA_CLOUD_CREDENTIALS_URI=http://localhost:8080/token"); $provider = new DefaultCredentialsProvider(); @@ -164,6 +170,7 @@ public function testDefaultProviderWithURI() self::assertEquals("default/credential_uri", $credentials->getProviderName()); putenv("ALIBABA_CLOUD_CREDENTIALS_URI="); + putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED="); } public function testDefaultProviderWithReuseLast() @@ -175,6 +182,7 @@ public function testDefaultProviderWithReuseLast() $url = $vf->url("token-file"); putenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE=$url"); putenv("ALIBABA_CLOUD_CREDENTIALS_URI=http://localhost:8080/token"); + putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED=true"); $provider = new DefaultCredentialsProvider(); $result = [ @@ -214,6 +222,7 @@ public function testDefaultProviderWithReuseLast() putenv("ALIBABA_CLOUD_ROLE_ARN="); putenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN="); putenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE="); + putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED="); } public function testDefaultProviderWithUnReuseLast() @@ -225,6 +234,7 @@ public function testDefaultProviderWithUnReuseLast() $url = $vf->url("token-file"); putenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE=$url"); putenv("ALIBABA_CLOUD_CREDENTIALS_URI=http://localhost:8080/token"); + putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED=true"); $provider = new DefaultCredentialsProvider([ 'reuseLastProviderEnabled' => false, @@ -266,5 +276,6 @@ public function testDefaultProviderWithUnReuseLast() putenv("ALIBABA_CLOUD_ROLE_ARN="); putenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN="); putenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE="); + putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED="); } } diff --git a/tests/Unit/Providers/EcsRamRoleCredentialsProviderTest.php b/tests/Unit/Providers/EcsRamRoleCredentialsProviderTest.php index e82ddf0..186dc83 100644 --- a/tests/Unit/Providers/EcsRamRoleCredentialsProviderTest.php +++ b/tests/Unit/Providers/EcsRamRoleCredentialsProviderTest.php @@ -38,7 +38,8 @@ private function getPrivateField($instance, $field) /** * @throws Exception */ - private function invokeProtectedFunc($instance, $method) { + private function invokeProtectedFunc($instance, $method) + { $reflection = new ReflectionClass(EcsRamRoleCredentialsProvider::class); $method = $reflection->getMethod($method); $method->setAccessible(true); @@ -80,6 +81,27 @@ public function testConstruct() putenv("ALIBABA_CLOUD_IMDSV1_DISABLED="); } + /** + * @expectedException RuntimeException + * @expectedExceptionMessage IMDS credentials is disabled + */ + public function testEnvDisabled() + { + + putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED=true"); + $provider = new EcsRamRoleCredentialsProvider([], []); + + $this->expectException(RuntimeException::class); + if (method_exists($this, 'expectExceptionMessageMatches')) { + $this->expectExceptionMessageMatches('/IMDS credentials is disabled/'); + } elseif (method_exists($this, 'expectExceptionMessageRegExp')) { + $this->expectExceptionMessageRegExp('/IMDS credentials is disabled/'); + } + $provider->getCredentials(); + + putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED="); + } + public function testGetDisableECSIMDSv1() { // Setup @@ -103,7 +125,7 @@ public function testGetDisableECSIMDSv1() self::assertEquals(false, $this->invokeProtectedFunc($provider, 'isDisableIMDSv1')); putenv('ALIBABA_CLOUD_IMDSV1_DISABLED=true'); - + $provider = new EcsRamRoleCredentialsProvider($params); self::assertEquals(true, $this->invokeProtectedFunc($provider, 'isDisableIMDSv1')); @@ -184,7 +206,6 @@ public function testGetMetadataToken404() $this->expectExceptionMessage('Failed to get token from ECS Metadata Service. HttpCode= 404'); $this->invokeProtectedFunc($provider, 'getMetadataToken'); - } public function testEnableV1404() @@ -206,5 +227,4 @@ public function testEnableV1404() $request = end($histroy)['request']; self::assertEquals(null, $token); } - } diff --git a/tests/Unit/Providers/ProfileCredentialsProviderTest.php b/tests/Unit/Providers/ProfileCredentialsProviderTest.php index 0d634e4..864ae2a 100644 --- a/tests/Unit/Providers/ProfileCredentialsProviderTest.php +++ b/tests/Unit/Providers/ProfileCredentialsProviderTest.php @@ -179,6 +179,7 @@ public function testRamRoleArnError() public function testEcsRamRole() { $vf = VirtualEcsRamRoleCredential::client(); + putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED=false"); putenv("ALIBABA_CLOUD_CREDENTIALS_FILE=$vf"); putenv("ALIBABA_CLOUD_PROFILE=phpunit"); $provider = new ProfileCredentialsProvider(); @@ -200,6 +201,7 @@ public function testEcsRamRole() self::assertEquals('profile/ecs_ram_role', $credentials->getProviderName()); putenv("ALIBABA_CLOUD_PROFILE="); putenv("ALIBABA_CLOUD_CREDENTIALS_FILE="); + putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED="); } public function testOIDCRoleArn() diff --git a/tests/Unit/Providers/SessionCredentialsProviderTest.php b/tests/Unit/Providers/SessionCredentialsProviderTest.php new file mode 100644 index 0000000..d577a80 --- /dev/null +++ b/tests/Unit/Providers/SessionCredentialsProviderTest.php @@ -0,0 +1,209 @@ + 'testAccessKeyId', + 'accessKeySecret' => 'testAccessKeySecret', + 'securityToken' => 'testSecurityToken', + 'providerName' => $this->getProviderName(), + ]), time() + 3600); + } + + public function clearCache() + { + unset(self::$credentialsCache[$this->key()]); + } + + public function getProviderName() + { + return 'test'; + } + + public function key() + { + return 'testKey'; + } + + public function handleFetchedFailure(\Exception $e) + { + return parent::handleFetchedFailure($e); + } + + public function handleFetchedSuccess(RefreshResult $value) + { + return parent::handleFetchedSuccess($value); + } + + public function refreshCache() + { + return parent::refreshCache(); + } + + /** + * Cache credentials. + * + * @param RefreshResult $credential|null + */ + public function cache(RefreshResult $value) + { + return parent::cache($value); + } + + public function cacheIsStale() + { + return parent::cacheIsStale(); + } + + public function shouldInitiateCachePrefetch() + { + return parent::shouldInitiateCachePrefetch(); + } + + public function getCredentialsInCache() + { + return parent::getCredentialsInCache(); + } +} + +/** + * Class SessionCredentialsProviderTest + * + * @package AlibabaCloud\Credentials\Tests\Unit\Providers + */ +class SessionCredentialsProviderTest extends TestCase +{ + + protected $provider; + + /** + * @before + */ + protected function initialize() + { + parent::setUp(); + $this->provider = new TestSessionCredentialsProvider(); + } + + public function testGetCredentialsInCache() + { + $this->assertNull($this->provider->getCredentialsInCache()); + + $refreshResult = new RefreshResult(new Credentials([ + 'accessKeyId' => 'testAccessKeyId', + 'accessKeySecret' => 'testAccessKeySecret', + 'securityToken' => 'testSecurityToken', + ]), time() + 3600); + $this->provider->cache($refreshResult); + + $cachedResult = $this->provider->getCredentialsInCache(); + $this->assertInstanceOf(RefreshResult::class, $cachedResult); + $this->assertEquals('testAccessKeyId', $cachedResult->credentials()->getAccessKeyId()); + $this->provider->clearCache(); + } + + public function testCache() + { + $refreshResult = new RefreshResult(new Credentials([ + 'accessKeyId' => 'testAccessKeyId', + 'accessKeySecret' => 'testAccessKeySecret', + 'securityToken' => 'testSecurityToken', + ]), time() + 3600); + $this->provider->cache($refreshResult); + + $this->assertNotNull($this->provider->getCredentialsInCache()); + $this->provider->clearCache(); + } + + public function testGetCredentials() + { + $credentials = $this->provider->getCredentials(); + $this->assertEquals('testAccessKeyId', $credentials->getAccessKeyId()); + } + + public function testRefreshCache() + { + $refreshResult = $this->provider->refreshCache(); + $this->assertInstanceOf(RefreshResult::class, $refreshResult); + $this->assertEquals('testAccessKeyId', $refreshResult->credentials()->getAccessKeyId()); + } + + public function testHandleFetchedFailure() + { + $this->provider->clearCache(); + $exception = new \Exception('Test exception'); + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Test exception'); + + $this->provider->handleFetchedFailure($exception); + } + + public function testHandleFetchedSuccess() + { + $refreshResult = new RefreshResult(new Credentials([ + 'accessKeyId' => 'testAccessKeyId', + 'accessKeySecret' => 'testAccessKeySecret', + 'securityToken' => 'testSecurityToken', + ]), time() + 3600); + $result = $this->provider->handleFetchedSuccess($refreshResult); + $this->assertInstanceOf(RefreshResult::class, $result); + $this->assertEquals('testAccessKeyId', $result->credentials()->getAccessKeyId()); + $this->provider->clearCache(); + } + + public function testCacheIsStale() + { + $this->assertTrue($this->provider->cacheIsStale()); + + $refreshResult = new RefreshResult(new Credentials([ + 'accessKeyId' => 'testAccessKeyId', + 'accessKeySecret' => 'testAccessKeySecret', + 'securityToken' => 'testSecurityToken', + ]), time() + 3600); + $this->provider->cache($refreshResult); + + $this->assertFalse($this->provider->cacheIsStale()); + $this->provider->clearCache(); + } + + public function testShouldInitiateCachePrefetch() + { + $this->assertTrue($this->provider->shouldInitiateCachePrefetch()); + + $refreshResult = new RefreshResult(new Credentials([ + 'accessKeyId' => 'testAccessKeyId', + 'accessKeySecret' => 'testAccessKeySecret', + 'securityToken' => 'testSecurityToken', + ]), time() + 3600); + $this->provider->cache($refreshResult); + + $this->assertFalse($this->provider->shouldInitiateCachePrefetch()); + $this->provider->clearCache(); + + $refreshResult = new RefreshResult(new Credentials([ + 'accessKeyId' => 'aaa', + 'accessKeySecret' => 'aaa', + 'securityToken' => 'aaa', + ]), time() + 3600, time() - 3600); + $this->provider->cache($refreshResult); + + $this->assertTrue($this->provider->shouldInitiateCachePrefetch()); + $this->provider->clearCache(); + } + + public function testGetStaleTime() + { + $this->assertEquals(2700, $this->provider->getStaleTime(3600)); + $this->assertEquals(time() + 3600, $this->provider->getStaleTime(0)); + } +} diff --git a/tests/Unit/RamRoleArnCredentialTest.php b/tests/Unit/RamRoleArnCredentialTest.php index 39476b6..040791f 100644 --- a/tests/Unit/RamRoleArnCredentialTest.php +++ b/tests/Unit/RamRoleArnCredentialTest.php @@ -71,7 +71,7 @@ public function testSts() "Credentials": { "AccessKeySecret": "********************", "AccessKeyId": "STS.**************", - "Expiration": "2020-02-25T03:56:19Z", + "Expiration": "2049-02-25T03:56:19Z", "SecurityToken": "**************" } }'; @@ -90,7 +90,7 @@ public function testSts() self::assertEquals('STS.**************', $credential->getAccessKeyId()); self::assertEquals('********************', $credential->getAccessKeySecret()); self::assertEquals('**************', $credential->getSecurityToken()); - self::assertEquals(strtotime('2020-02-25T03:56:19Z'), $credential->getExpiration()); + self::assertEquals(strtotime('2049-02-25T03:56:19Z'), $credential->getExpiration()); Credentials::mockResponse(200, [], $result); $credentialModel = $credential->getCredential(); diff --git a/tests/Unit/RsaKeyPairCredentialTest.php b/tests/Unit/RsaKeyPairCredentialTest.php index ba9e483..f174c7d 100644 --- a/tests/Unit/RsaKeyPairCredentialTest.php +++ b/tests/Unit/RsaKeyPairCredentialTest.php @@ -101,7 +101,7 @@ public function testSts() "RequestId": "F702286E-F231-4F40-BB86-XXXXXX", "SessionAccessKey": { "SessionAccessKeyId": "TMPSK.**************", - "Expiration": "2023-02-19T07:02:36.225Z", + "Expiration": "2049-02-19T07:02:36.225Z", "SessionAccessKeySecret": "**************" } }'; @@ -116,7 +116,7 @@ public function testSts() self::assertEquals('TMPSK.**************', $credential->getAccessKeyId()); self::assertEquals('**************', $credential->getAccessKeySecret()); self::assertEquals('', $credential->getSecurityToken()); - self::assertEquals(strtotime('2023-02-19T07:02:36.225Z'), $credential->getExpiration()); + self::assertEquals(strtotime('2049-02-19T07:02:36.225Z'), $credential->getExpiration()); Credentials::mockResponse(200, [], $result); $credentialModel = $this->credential->getCredential();