Skip to content

support env to turn off imds && add some test cases && fix some bugs #34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/Credential/CredentialModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
/**
Expand All @@ -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;
}
/**
Expand Down Expand Up @@ -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
*/
Expand Down Expand Up @@ -122,4 +135,9 @@ public function getType()
return $this->type;
}

public function getProviderName()
{
return $this->providerName;
}

}
20 changes: 13 additions & 7 deletions src/Credential/RefreshResult.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [];
Expand Down Expand Up @@ -89,5 +96,4 @@ public function prefetchTime()
{
return $this->prefetchTime;
}

}
1 change: 1 addition & 0 deletions src/CredentialsProviderWrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public function getCredential()
'accessKeySecret' => $credentials->getAccessKeySecret(),
'securityToken' => $credentials->getSecurityToken(),
'type' => $this->typeName,
'providerName' => $credentials->getProviderName(),
]);
}

Expand Down
8 changes: 8 additions & 0 deletions src/Providers/CLIProfileCredentialsProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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([
Expand All @@ -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'));
Expand All @@ -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'));
Expand Down
10 changes: 4 additions & 6 deletions src/Providers/DefaultCredentialsProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
19 changes: 12 additions & 7 deletions src/Providers/EcsRamRoleCredentialsProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,12 @@ class EcsRamRoleCredentialsProvider extends SessionCredentialsProvider
/**
* @var int
*/
private $connectTimeout = 5;
private $connectTimeout = 1;

/**
* @var int
*/
private $readTimeout = 5;
private $readTimeout = 1;


/**
Expand Down Expand Up @@ -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)
Expand All @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
14 changes: 9 additions & 5 deletions src/Providers/EnvironmentVariableCredentialsProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ class EnvironmentVariableCredentialsProvider implements CredentialsProvider
/**
* EnvironmentVariableCredentialsProvider constructor.
*/
public function __construct()
{
}
public function __construct() {}

/**
* Get credential.
Expand All @@ -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(),
]);
}
Expand All @@ -58,4 +62,4 @@ public function getProviderName()
{
return "env";
}
}
}
57 changes: 30 additions & 27 deletions src/Providers/SessionCredentialsProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand All @@ -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分钟,但未过期,下次会再次刷新
Expand All @@ -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 {
Expand All @@ -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
*/
Expand Down
4 changes: 2 additions & 2 deletions tests/Feature/CredentialTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading