diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 096f9a6..605a06a 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,9 +1,9 @@ diff --git a/.github/ISSUE_TEMPLATE/3-help.md b/.github/ISSUE_TEMPLATE/3-help.md index 731f2d8..2ca0d0a 100644 --- a/.github/ISSUE_TEMPLATE/3-help.md +++ b/.github/ISSUE_TEMPLATE/3-help.md @@ -1,10 +1,10 @@ --- -name: "⁉️ Need help with Alibaba Cloud?" +name: "⁉️ Need help?" about: Please submit a work order in our work order system --- If you have a question about Alibaba Cloud that is not a bug report or feature -request, please post it in https://selfservice.console.aliyun.com/ticket/createIndex +request, please post it Questions posted to this repository will be closed. diff --git a/.github/ISSUE_TEMPLATE/6-help-cn.md b/.github/ISSUE_TEMPLATE/6-help-cn.md index f63c808..0e210b6 100644 --- a/.github/ISSUE_TEMPLATE/6-help-cn.md +++ b/.github/ISSUE_TEMPLATE/6-help-cn.md @@ -1,10 +1,10 @@ --- -name: "⁉️ 需要阿里云的帮助?" +name: "⁉️ 需要帮助?" about: 请在我们的工单系统提出工单 --- 如果您对阿里云 SDK 的问题不是 Bug 或希望添加新功能, -请在我们的工单系统提出工单:https://selfservice.console.aliyun.com/ticket/createIndex +请在我们的工单系统提出工单 此类问题将被关闭。 diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 849f5b5..08fa6fd 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -4,7 +4,6 @@ the requirements below. Bug fixes and new features should include tests and possibly benchmarks. -Contributors guide: https://github.com/aliyun/credentials-php/blob/master/CONTRIBUTING.md --> ##### You need to complete diff --git a/composer.json b/composer.json index 81f9745..0283032 100644 --- a/composer.json +++ b/composer.json @@ -1,31 +1,19 @@ { - "name": "alibabacloud/credentials", - "homepage": "https://www.alibabacloud.com/", - "description": "Alibaba Cloud Credentials for PHP", + "name": "{{ipdt}}/credentials", "keywords": [ "sdk", "tool", "cloud", "client", - "aliyun", "library", - "alibaba", - "Credentials", - "alibabacloud" + "credentials" ], "type": "library", "license": "Apache-2.0", "support": { - "source": "https://github.com/aliyun/credentials-php", - "issues": "https://github.com/aliyun/credentials-php/issues" + "source": "https://github.com/{{ipdt}}/credentials-php", + "issues": "https://github.com/{{ipdt}}/credentials-php/issues" }, - "authors": [ - { - "name": "Alibaba Cloud SDK", - "email": "sdk-team@alibabacloud.com", - "homepage": "http://www.alibabacloud.com" - } - ], "require": { "php": ">=5.6", "ext-curl": "*", diff --git a/src/AccessKeyCredential.php b/src/AccessKeyCredential.php deleted file mode 100644 index 05a0132..0000000 --- a/src/AccessKeyCredential.php +++ /dev/null @@ -1,86 +0,0 @@ -accessKeyId = $access_key_id; - $this->accessKeySecret = $access_key_secret; - } - - /** - * @return string - */ - public function getAccessKeyId() - { - return $this->accessKeyId; - } - - /** - * @return string - */ - public function getAccessKeySecret() - { - return $this->accessKeySecret; - } - - /** - * @return string - */ - public function __toString() - { - return "$this->accessKeyId#$this->accessKeySecret"; - } - - /** - * @return ShaHmac1Signature - */ - public function getSignature() - { - return new ShaHmac1Signature(); - } - - public function getSecurityToken() - { - return ''; - } - /** - * @inheritDoc - */ - public function getCredential() - { - return new CredentialModel([ - 'accessKeyId' => $this->accessKeyId, - 'accessKeySecret' => $this->accessKeySecret, - 'type' => 'access_key', - ]); - } -} diff --git a/src/Configure/Config.php b/src/Configure/Config.php new file mode 100644 index 0000000..5b8dac9 --- /dev/null +++ b/src/Configure/Config.php @@ -0,0 +1,17 @@ + $config->policy, 'durationSeconds' => $config->roleSessionExpiration, 'externalId' => $config->externalId, - 'stsEndpoint' => $config->STSEndpoint, + 'stsEndpoint' => $config->stsEndpoint, ], [ 'connectTimeout' => $config->connectTimeout, 'readTimeout' => $config->readTimeout, @@ -135,7 +129,7 @@ private function getCredentials($config) 'publicKeyId' => $config->publicKeyId, 'privateKeyFile' => $config->privateKeyFile, 'durationSeconds' => $config->roleSessionExpiration, - 'stsEndpoint' => $config->STSEndpoint, + 'stsEndpoint' => $config->stsEndpoint, ], [ 'connectTimeout' => $config->connectTimeout, 'readTimeout' => $config->readTimeout, @@ -158,7 +152,7 @@ private function getCredentials($config) 'roleSessionName' => $config->roleSessionName, 'policy' => $config->policy, 'durationSeconds' => $config->roleSessionExpiration, - 'stsEndpoint' => $config->STSEndpoint, + 'stsEndpoint' => $config->stsEndpoint, ], [ 'connectTimeout' => $config->connectTimeout, 'readTimeout' => $config->readTimeout, @@ -166,7 +160,7 @@ private function getCredentials($config) return new CredentialsProviderWrap('oidc_role_arn', $provider); case "credentials_uri": $provider = new URLCredentialsProvider([ - 'credentialsURI' => $config->credentialsURI, + 'credentialsURI' => $config->credentialsUri, ], [ 'connectTimeout' => $config->connectTimeout, 'readTimeout' => $config->readTimeout, @@ -195,66 +189,6 @@ public function getConfig() return $this->config->toMap(); } - /** - * @deprecated use getCredential() instead - * - * @return string - * @throws RuntimeException - * @throws GuzzleException - */ - public function getType() - { - return $this->credential->getCredential()->getType(); - } - - /** - * @deprecated use getCredential() instead - * - * @return string - * @throws RuntimeException - * @throws GuzzleException - */ - public function getAccessKeyId() - { - return $this->credential->getCredential()->getAccessKeyId(); - } - - /** - * @deprecated use getCredential() instead - * - * @return string - * @throws RuntimeException - * @throws GuzzleException - */ - public function getAccessKeySecret() - { - return $this->credential->getCredential()->getAccessKeySecret(); - } - - /** - * @deprecated use getCredential() instead - * - * @return string - * @throws RuntimeException - * @throws GuzzleException - */ - public function getSecurityToken() - { - return $this->credential->getCredential()->getSecurityToken(); - } - - /** - * @deprecated use getCredential() instead - * - * @return string - * @throws RuntimeException - * @throws GuzzleException - */ - public function getBearerToken() - { - return $this->credential->getCredential()->getBearerToken(); - } - /** * @param string $name * @param array $arguments diff --git a/src/Credential/Config.php b/src/Credential/Config.php index 1fb57e3..3157691 100644 --- a/src/Credential/Config.php +++ b/src/Credential/Config.php @@ -24,9 +24,6 @@ public function toMap() if (null !== $this->bearerToken) { $res['bearerToken'] = $this->bearerToken; } - if (null !== $this->durationSeconds) { - $res['durationSeconds'] = $this->durationSeconds; - } if (null !== $this->roleArn) { $res['roleArn'] = $this->roleArn; } @@ -48,14 +45,14 @@ public function toMap() if (null !== $this->roleName) { $res['roleName'] = $this->roleName; } - if (null !== $this->credentialsURI) { - $res['credentialsURI'] = $this->credentialsURI; + if (null !== $this->credentialsUri) { + $res['credentialsUri'] = $this->credentialsUri; } if (null !== $this->type) { $res['type'] = $this->type; } - if (null !== $this->STSEndpoint) { - $res['STSEndpoint'] = $this->STSEndpoint; + if (null !== $this->stsEndpoint) { + $res['stsEndpoint'] = $this->stsEndpoint; } if (null !== $this->externalId) { $res['externalId'] = $this->externalId; @@ -81,9 +78,6 @@ public static function fromMap($map = []) if (isset($map['bearerToken'])) { $model->bearerToken = $map['bearerToken']; } - if (isset($map['durationSeconds'])) { - $model->durationSeconds = $map['durationSeconds']; - } if (isset($map['roleArn'])) { $model->roleArn = $map['roleArn']; } @@ -105,14 +99,14 @@ public static function fromMap($map = []) if (isset($map['roleName'])) { $model->roleName = $map['roleName']; } - if (isset($map['credentialsURI'])) { - $model->credentialsURI = $map['credentialsURI']; + if (isset($map['credentialsUri'])) { + $model->credentialsUri = $map['credentialsUri']; } if (isset($map['type'])) { $model->type = $map['type']; } - if (isset($map['STSEndpoint'])) { - $model->STSEndpoint = $map['STSEndpoint']; + if (isset($map['stsEndpoint'])) { + $model->stsEndpoint = $map['stsEndpoint']; } if (isset($map['externalId'])) { $model->externalId = $map['externalId']; @@ -203,7 +197,7 @@ public static function fromMap($map = []) * @description sts endpoint * @var string */ - public $STSEndpoint; + public $stsEndpoint; public $publicKeyId; @@ -231,37 +225,7 @@ public static function fromMap($map = []) * @description credentials URI * @var string */ - public $credentialsURI; - - /** - * @deprecated - */ - public $metadataTokenDuration; - - /** - * @deprecated - */ - public $durationSeconds; - - /** - * @deprecated - */ - public $host; - - /** - * @deprecated - */ - public $expiration; - - /** - * @deprecated - */ - public $certFile = ""; - - /** - * @deprecated - */ - public $certPassword = ""; + public $credentialsUri; /** * @internal diff --git a/src/Credentials.php b/src/Credentials.php index f064b86..cdcecf5 100644 --- a/src/Credentials.php +++ b/src/Credentials.php @@ -8,11 +8,6 @@ use ReflectionException; use RuntimeException; -/** - * Class Credentials - * - * @package AlibabaCloud\Credentials - */ class Credentials { use MockTrait; diff --git a/src/CredentialsInterface.php b/src/CredentialsInterface.php index 0d109e2..463d82d 100644 --- a/src/CredentialsInterface.php +++ b/src/CredentialsInterface.php @@ -3,14 +3,7 @@ namespace AlibabaCloud\Credentials; use AlibabaCloud\Credentials\Credential\CredentialModel; -use AlibabaCloud\Credentials\Signature\SignatureInterface; -/** - * @internal This class is intended for internal use within the package. - * Interface CredentialsInterface - * - * @codeCoverageIgnore - */ interface CredentialsInterface { /** @@ -19,12 +12,6 @@ interface CredentialsInterface */ public function __toString(); - /** - * @deprecated - * @return SignatureInterface - */ - public function getSignature(); - /** * @return CredentialModel */ diff --git a/src/CredentialsProviderWrap.php b/src/CredentialsProviderWrap.php index 4e8611e..9d623b3 100644 --- a/src/CredentialsProviderWrap.php +++ b/src/CredentialsProviderWrap.php @@ -5,12 +5,6 @@ use AlibabaCloud\Credentials\Credential\CredentialModel; use AlibabaCloud\Credentials\Providers\CredentialsProvider; -/** - * @internal This class is intended for internal use within the package. - * Class CredentialsProviderWrap - * - * @package AlibabaCloud\Credentials - */ class CredentialsProviderWrap implements CredentialsInterface { /** @@ -65,12 +59,4 @@ public function __toString() { return "credentialsProviderWrap#$this->typeName"; } - - /** - * @return ShaHmac1Signature - */ - public function getSignature() - { - return null; - } } \ No newline at end of file diff --git a/src/EcsRamRoleCredential.php b/src/EcsRamRoleCredential.php deleted file mode 100644 index ba66c0d..0000000 --- a/src/EcsRamRoleCredential.php +++ /dev/null @@ -1,199 +0,0 @@ -roleName = $role_name; - - Filter::disableIMDSv1($disable_imdsv1); - - $this->disableIMDSv1 = $disable_imdsv1; - - $this->metadataTokenDuration = $metadata_token_duration; - } - - /** - * @return string - * @throws GuzzleException - * @throws Exception - */ - public function getRoleName() - { - if ($this->roleName !== null) { - return $this->roleName; - } - - $this->roleName = $this->getRoleNameFromMeta(); - - return $this->roleName; - } - - /** - * @return string - * @throws Exception - */ - public function getRoleNameFromMeta() - { - $options = [ - 'http_errors' => false, - 'timeout' => 1, - 'connect_timeout' => 1, - ]; - - $result = Request::createClient()->request( - 'GET', - 'http://100.100.100.200/latest/meta-data/ram/security-credentials/', - $options - ); - - if ($result->getStatusCode() === 404) { - throw new InvalidArgumentException('The role name was not found in the instance'); - } - - if ($result->getStatusCode() !== 200) { - throw new RuntimeException('Error retrieving credentials from result: ' . $result->getBody()); - } - - $role_name = (string) $result; - if (!$role_name) { - throw new RuntimeException('Error retrieving credentials from result is empty'); - } - - return $role_name; - } - - /** - * @return string - */ - public function __toString() - { - return "roleName#$this->roleName"; - } - - /** - * @return ShaHmac1Signature - */ - public function getSignature() - { - return new ShaHmac1Signature(); - } - - /** - * @return string - * @throws Exception - * @throws GuzzleException - */ - public function getAccessKeyId() - { - return $this->getSessionCredential()->getAccessKeyId(); - } - - /** - * @return AlibabaCloud\Credentials\Providers\Credentials - * @throws Exception - * @throws GuzzleException - */ - protected function getSessionCredential() - { - $params = [ - "roleName" => $this->roleName, - 'disableIMDSv1' => $this->disableIMDSv1, - 'metadataTokenDuration' => $this->metadataTokenDuration, - ]; - return (new EcsRamRoleCredentialsProvider($params))->getCredentials(); - } - - /** - * @return string - * @throws Exception - * @throws GuzzleException - */ - public function getAccessKeySecret() - { - return $this->getSessionCredential()->getAccessKeySecret(); - } - - /** - * @return string - * @throws Exception - * @throws GuzzleException - */ - public function getSecurityToken() - { - return $this->getSessionCredential()->getSecurityToken(); - } - - /** - * @return int - * @throws Exception - * @throws GuzzleException - */ - public function getExpiration() - { - return $this->getSessionCredential()->getExpiration(); - } - - /** - * @return bool - */ - public function isDisableIMDSv1() - { - return $this->disableIMDSv1; - } - - /** - * @inheritDoc - */ - public function getCredential() - { - $credentials = $this->getSessionCredential(); - return new CredentialModel([ - 'accessKeyId' => $credentials->getAccessKeyId(), - 'accessKeySecret' => $credentials->getAccessKeySecret(), - 'securityToken' => $credentials->getSecurityToken(), - 'type' => 'ecs_ram_role', - ]); - } - -} diff --git a/src/Providers/CLIProfileCredentialsProvider.php b/src/Providers/CLIProfileCredentialsProvider.php index f627668..0ce305d 100644 --- a/src/Providers/CLIProfileCredentialsProvider.php +++ b/src/Providers/CLIProfileCredentialsProvider.php @@ -4,13 +4,8 @@ use AlibabaCloud\Credentials\Utils\Helper; use RuntimeException; +use AlibabaCloud\Configure\Config; -/** - * @internal This class is intended for internal use within the package. - * Class CLIProfileCredentialsProvider - * - * @package AlibabaCloud\Credentials\Providers - */ class CLIProfileCredentialsProvider implements CredentialsProvider { @@ -37,8 +32,8 @@ public function __construct(array $params = []) private function filterProfileName(array $params) { - if (Helper::envNotEmpty('ALIBABA_CLOUD_PROFILE')) { - $this->profileName = Helper::env('ALIBABA_CLOUD_PROFILE'); + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'PROFILE')) { + $this->profileName = Helper::env(Config::ENV_PREFIX . 'PROFILE'); } if (isset($params['profileName'])) { @@ -146,7 +141,7 @@ protected function reloadCredentialsProvider($profileFile, $profileName) */ public function getCredentials() { - if (Helper::envNotEmpty('ALIBABA_CLOUD_CLI_PROFILE_DISABLED') && Helper::env('ALIBABA_CLOUD_CLI_PROFILE_DISABLED') === true) { + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'CLI_PROFILE_DISABLED') && Helper::env(Config::ENV_PREFIX . 'CLI_PROFILE_DISABLED') === true) { throw new RuntimeException('CLI credentials file is disabled'); } $cliProfileFile = self::getDefaultFile(); @@ -172,7 +167,7 @@ private function getDefaultFile() { return Helper::getHomeDirectory() . DIRECTORY_SEPARATOR . - '.aliyun' . + Config::CLI_CONFIG_DIR . DIRECTORY_SEPARATOR . 'config.json'; } diff --git a/src/Providers/ChainProvider.php b/src/Providers/ChainProvider.php deleted file mode 100644 index d6c1540..0000000 --- a/src/Providers/ChainProvider.php +++ /dev/null @@ -1,188 +0,0 @@ - 'access_key', - 'access_key_id' => $accessKeyId, - 'access_key_secret' => $accessKeySecret, - ] - ); - } - }; - } - - /** - * @return string - */ - public static function getDefaultName() - { - $name = Helper::envNotEmpty('ALIBABA_CLOUD_PROFILE'); - - if ($name) { - return $name; - } - - return 'default'; - } - - /** - * @return Closure - */ - public static function ini() - { - return static function () { - $filename = Helper::envNotEmpty('ALIBABA_CLOUD_CREDENTIALS_FILE'); - if (!$filename) { - $filename = self::getDefaultFile(); - } - - if (!Helper::inOpenBasedir($filename)) { - return; - } - - if ($filename !== self::getDefaultFile() && (!\is_readable($filename) || !\is_file($filename))) { - throw new RuntimeException( - 'Credentials file is not readable: ' . $filename - ); - } - - $file_array = \parse_ini_file($filename, true); - - if (\is_array($file_array) && !empty($file_array)) { - foreach (\array_change_key_case($file_array) as $name => $configures) { - Credentials::set($name, $configures); - } - } - }; - } - - /** - * Get the default credential file. - * - * @return string - */ - public static function getDefaultFile() - { - return Helper::getHomeDirectory() . - DIRECTORY_SEPARATOR . - '.alibabacloud' . - DIRECTORY_SEPARATOR . - 'credentials'; - } - - /** - * @return Closure - */ - public static function instance() - { - return static function () { - $instance = Helper::envNotEmpty('ALIBABA_CLOUD_ECS_METADATA'); - if ($instance) { - Credentials::set( - self::getDefaultName(), - [ - 'type' => 'ecs_ram_role', - 'role_name' => $instance, - ] - ); - } - }; - } -} \ No newline at end of file diff --git a/src/Providers/Credentials.php b/src/Providers/Credentials.php index bfd4fe3..56e4e5a 100644 --- a/src/Providers/Credentials.php +++ b/src/Providers/Credentials.php @@ -2,12 +2,6 @@ namespace AlibabaCloud\Credentials\Providers; -/** - * @internal This class is intended for internal use within the package. - * Class Credentials - * - * @package AlibabaCloud\Credentials\Providers - */ class Credentials { diff --git a/src/Providers/CredentialsProvider.php b/src/Providers/CredentialsProvider.php index ddbd1a1..cd7f6fd 100644 --- a/src/Providers/CredentialsProvider.php +++ b/src/Providers/CredentialsProvider.php @@ -2,13 +2,6 @@ namespace AlibabaCloud\Credentials\Providers; - -/** - * @internal This class is intended for internal use within the package. - * Interface CredentialsInterface - * - * @codeCoverageIgnore - */ interface CredentialsProvider { diff --git a/src/Providers/DefaultCredentialsProvider.php b/src/Providers/DefaultCredentialsProvider.php index c4725b9..caf215f 100644 --- a/src/Providers/DefaultCredentialsProvider.php +++ b/src/Providers/DefaultCredentialsProvider.php @@ -7,13 +7,8 @@ use InvalidArgumentException; use RuntimeException; use Exception; +use AlibabaCloud\Configure\Config; -/** - * @internal This class is intended for internal use within the package. - * Class DefaultCredentialsProvider - * - * @package AlibabaCloud\Credentials\Providers - */ class DefaultCredentialsProvider implements CredentialsProvider { @@ -62,9 +57,9 @@ private function createDefaultChain() new EnvironmentVariableCredentialsProvider(), ]; if ( - Helper::envNotEmpty('ALIBABA_CLOUD_ROLE_ARN') - && Helper::envNotEmpty('ALIBABA_CLOUD_OIDC_PROVIDER_ARN') - && Helper::envNotEmpty('ALIBABA_CLOUD_OIDC_TOKEN_FILE') + Helper::envNotEmpty(Config::ENV_PREFIX . 'ROLE_ARN') + && Helper::envNotEmpty(Config::ENV_PREFIX . 'OIDC_PROVIDER_ARN') + && Helper::envNotEmpty(Config::ENV_PREFIX . 'OIDC_TOKEN_FILE') ) { array_push( self::$defaultProviders, @@ -83,7 +78,7 @@ private function createDefaultChain() self::$defaultProviders, new EcsRamRoleCredentialsProvider() ); - if (Helper::envNotEmpty('ALIBABA_CLOUD_CREDENTIALS_URI')) { + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'CREDENTIALS_URI')) { array_push( self::$defaultProviders, new URLCredentialsProvider() diff --git a/src/Providers/EcsRamRoleCredentialsProvider.php b/src/Providers/EcsRamRoleCredentialsProvider.php index 8dffb50..50ad656 100644 --- a/src/Providers/EcsRamRoleCredentialsProvider.php +++ b/src/Providers/EcsRamRoleCredentialsProvider.php @@ -9,20 +9,15 @@ use InvalidArgumentException; use RuntimeException; use AlibabaCloud\Credentials\Credential\RefreshResult; +use AlibabaCloud\Configure\Config; -/** - * @internal This class is intended for internal use within the package. - * Class EcsRamRoleCredentialsProvider - * - * @package AlibabaCloud\Credentials\Providers - */ class EcsRamRoleCredentialsProvider extends SessionCredentialsProvider { /** * @var string */ - private $metadataHost = 'http://100.100.100.200'; + private $metadataHost = 'http://' . Config::ECS_METADATA_HOST; /** * @var string @@ -90,8 +85,8 @@ private function filterOptions(array $options) private function filterRoleName(array $params) { - if (Helper::envNotEmpty('ALIBABA_CLOUD_ECS_METADATA')) { - $this->roleName = Helper::env('ALIBABA_CLOUD_ECS_METADATA'); + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'ECS_METADATA')) { + $this->roleName = Helper::env(Config::ENV_PREFIX . 'ECS_METADATA'); } if (isset($params['roleName'])) { @@ -101,8 +96,8 @@ private function filterRoleName(array $params) private function filterDisableECSIMDSv1($params) { - if (Helper::envNotEmpty('ALIBABA_CLOUD_IMDSV1_DISABLED')) { - $this->disableIMDSv1 = Helper::env('ALIBABA_CLOUD_IMDSV1_DISABLED') === true ? true : false; + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'IMDSV1_DISABLED')) { + $this->disableIMDSv1 = Helper::env(Config::ENV_PREFIX . 'IMDSV1_DISABLED') === true ? true : false; } if (isset($params['disableIMDSv1'])) { @@ -120,7 +115,7 @@ private function filterDisableECSIMDSv1($params) */ public function refreshCredentials() { - if (Helper::envNotEmpty('ALIBABA_CLOUD_ECS_METADATA_DISABLED') && Helper::env('ALIBABA_CLOUD_ECS_METADATA_DISABLED') === true) { + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'ECS_METADATA_DISABLED') && Helper::env(Config::ENV_PREFIX . 'ECS_METADATA_DISABLED') === true) { throw new RuntimeException('IMDS credentials is disabled'); } @@ -135,7 +130,7 @@ public function refreshCredentials() $metadataToken = $this->getMetadataToken(); if (!is_null($metadataToken)) { - $options['headers']['X-aliyun-ecs-metadata-token'] = $metadataToken; + $options['headers'][Config::ECS_METADATA_HEADER_PREFIX . 'ecs-metadata-token'] = $metadataToken; } $result = Request::createClient()->request('GET', $url, $options); @@ -181,12 +176,12 @@ private function getRoleNameFromMeta() $metadataToken = $this->getMetadataToken(); if (!is_null($metadataToken)) { - $options['headers']['X-aliyun-ecs-metadata-token'] = $metadataToken; + $options['headers'][Config::ECS_METADATA_HEADER_PREFIX . 'ecs-metadata-token'] = $metadataToken; } $result = Request::createClient()->request( 'GET', - 'http://100.100.100.200/latest/meta-data/ram/security-credentials/', + $this->metadataHost . $this->ecsUri, $options ); @@ -219,7 +214,7 @@ private function getMetadataToken() $options = Request::commonOptions(); $options['read_timeout'] = $this->readTimeout; $options['connect_timeout'] = $this->connectTimeout; - $options['headers']['X-aliyun-ecs-metadata-token-ttl-seconds'] = $this->metadataTokenDuration; + $options['headers'][Config::ECS_METADATA_HEADER_PREFIX . 'ecs-metadata-token-ttl-seconds'] = $this->metadataTokenDuration; $result = Request::createClient()->request('PUT', $url, $options); diff --git a/src/Providers/EnvironmentVariableCredentialsProvider.php b/src/Providers/EnvironmentVariableCredentialsProvider.php index b6dd579..3873e05 100644 --- a/src/Providers/EnvironmentVariableCredentialsProvider.php +++ b/src/Providers/EnvironmentVariableCredentialsProvider.php @@ -4,13 +4,8 @@ use AlibabaCloud\Credentials\Utils\Helper; use InvalidArgumentException; +use AlibabaCloud\Configure\Config; -/** - * @internal This class is intended for internal use within the package. - * Class EnvironmentVariableCredentialsProvider - * - * @package AlibabaCloud\Credentials\Providers - */ class EnvironmentVariableCredentialsProvider implements CredentialsProvider { /** @@ -26,20 +21,20 @@ public function __construct() {} */ public function getCredentials() { - if (Helper::envNotEmpty('ALIBABA_CLOUD_ACCESS_KEY_ID')) { - $accessKeyId = Helper::env('ALIBABA_CLOUD_ACCESS_KEY_ID'); + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'ACCESS_KEY_ID')) { + $accessKeyId = Helper::env(Config::ENV_PREFIX . 'ACCESS_KEY_ID'); } else { - throw new InvalidArgumentException('Access key ID must be specified via environment variable (ALIBABA_CLOUD_ACCESS_KEY_ID)'); + throw new InvalidArgumentException('Access key ID must be specified via environment variable (' . Config::ENV_PREFIX . 'ACCESS_KEY_ID)'); } - if (Helper::envNotEmpty('ALIBABA_CLOUD_ACCESS_KEY_SECRET')) { - $accessKeySecret = Helper::env('ALIBABA_CLOUD_ACCESS_KEY_SECRET'); + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'ACCESS_KEY_SECRET')) { + $accessKeySecret = Helper::env(Config::ENV_PREFIX . 'ACCESS_KEY_SECRET'); } else { - throw new InvalidArgumentException('Access key Secret must be specified via environment variable (ALIBABA_CLOUD_ACCESS_KEY_SECRET)'); + throw new InvalidArgumentException('Access key Secret must be specified via environment variable (' . Config::ENV_PREFIX . 'ACCESS_KEY_SECRET)'); } - if (Helper::envNotEmpty('ALIBABA_CLOUD_SECURITY_TOKEN')) { - $securityToken = Helper::env('ALIBABA_CLOUD_SECURITY_TOKEN'); + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'SECURITY_TOKEN')) { + $securityToken = Helper::env(Config::ENV_PREFIX . 'SECURITY_TOKEN'); return new Credentials([ 'accessKeyId' => $accessKeyId, 'accessKeySecret' => $accessKeySecret, diff --git a/src/Providers/OIDCRoleArnCredentialsProvider.php b/src/Providers/OIDCRoleArnCredentialsProvider.php index 18fe6ec..378d2d9 100644 --- a/src/Providers/OIDCRoleArnCredentialsProvider.php +++ b/src/Providers/OIDCRoleArnCredentialsProvider.php @@ -11,13 +11,8 @@ use RuntimeException; use Exception; use AlibabaCloud\Credentials\Credential\RefreshResult; +use AlibabaCloud\Configure\Config; -/** - * @internal This class is intended for internal use within the package. - * Class OIDCRoleArnCredentialsProvider - * - * @package AlibabaCloud\Credentials\Providers - */ class OIDCRoleArnCredentialsProvider extends SessionCredentialsProvider { @@ -88,8 +83,8 @@ public function __construct(array $params = [], array $options = []) private function filterRoleArn(array $params) { - if (Helper::envNotEmpty('ALIBABA_CLOUD_ROLE_ARN')) { - $this->roleArn = Helper::env('ALIBABA_CLOUD_ROLE_ARN'); + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'ROLE_ARN')) { + $this->roleArn = Helper::env(Config::ENV_PREFIX . 'ROLE_ARN'); } if (isset($params['roleArn'])) { @@ -101,8 +96,8 @@ private function filterRoleArn(array $params) private function filterOIDCProviderArn(array $params) { - if (Helper::envNotEmpty('ALIBABA_CLOUD_OIDC_PROVIDER_ARN')) { - $this->oidcProviderArn = Helper::env('ALIBABA_CLOUD_OIDC_PROVIDER_ARN'); + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'OIDC_PROVIDER_ARN')) { + $this->oidcProviderArn = Helper::env(Config::ENV_PREFIX . 'OIDC_PROVIDER_ARN'); } if (isset($params['oidcProviderArn'])) { @@ -114,8 +109,8 @@ private function filterOIDCProviderArn(array $params) private function filterOIDCTokenFilePath(array $params) { - if (Helper::envNotEmpty('ALIBABA_CLOUD_OIDC_TOKEN_FILE')) { - $this->oidcTokenFilePath = Helper::env('ALIBABA_CLOUD_OIDC_TOKEN_FILE'); + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'OIDC_TOKEN_FILE')) { + $this->oidcTokenFilePath = Helper::env(Config::ENV_PREFIX . 'OIDC_TOKEN_FILE'); } if (isset($params['oidcTokenFilePath'])) { @@ -127,8 +122,8 @@ private function filterOIDCTokenFilePath(array $params) private function filterRoleSessionName(array $params) { - if (Helper::envNotEmpty('ALIBABA_CLOUD_ROLE_SESSION_NAME')) { - $this->roleSessionName = Helper::env('ALIBABA_CLOUD_ROLE_SESSION_NAME'); + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'ROLE_SESSION_NAME')) { + $this->roleSessionName = Helper::env(Config::ENV_PREFIX . 'ROLE_SESSION_NAME'); } if (isset($params['roleSessionName'])) { @@ -168,15 +163,15 @@ private function filterPolicy(array $params) private function filterSTSEndpoint(array $params) { $prefix = 'sts'; - if (Helper::envNotEmpty('ALIBABA_CLOUD_VPC_ENDPOINT_ENABLED') || (isset($params['enableVpc']) && $params['enableVpc'] === true)) { + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'VPC_ENDPOINT_ENABLED') || (isset($params['enableVpc']) && $params['enableVpc'] === true)) { $prefix = 'sts-vpc'; } - if (Helper::envNotEmpty('ALIBABA_CLOUD_STS_REGION')) { - $this->stsEndpoint = $prefix . '.' . Helper::env('ALIBABA_CLOUD_STS_REGION') . '.aliyuncs.com'; + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'STS_REGION')) { + $this->stsEndpoint = $prefix . '.' . Helper::env(Config::ENV_PREFIX . 'STS_REGION') . '.' . Config::ENDPOINT_SUFFIX; } if (isset($params['stsRegionId'])) { - $this->stsEndpoint = $prefix . '.' . $params['stsRegionId'] . '.aliyuncs.com'; + $this->stsEndpoint = $prefix . '.' . $params['stsRegionId'] . '.' . Config::ENDPOINT_SUFFIX; } if (isset($params['stsEndpoint'])) { @@ -184,7 +179,7 @@ private function filterSTSEndpoint(array $params) } if (is_null($this->stsEndpoint) || $this->stsEndpoint === '') { - $this->stsEndpoint = 'sts.aliyuncs.com'; + $this->stsEndpoint = Config::STS_DEFAULT_ENDPOINT; } } diff --git a/src/Providers/ProfileCredentialsProvider.php b/src/Providers/ProfileCredentialsProvider.php index ab07efe..8c2e147 100644 --- a/src/Providers/ProfileCredentialsProvider.php +++ b/src/Providers/ProfileCredentialsProvider.php @@ -4,13 +4,8 @@ use AlibabaCloud\Credentials\Utils\Helper; use RuntimeException; +use AlibabaCloud\Configure\Config; -/** - * @internal This class is intended for internal use within the package. - * Class ProfileCredentialsProvider - * - * @package AlibabaCloud\Credentials\Providers - */ class ProfileCredentialsProvider implements CredentialsProvider { @@ -43,8 +38,8 @@ public function __construct(array $params = []) private function filterProfileName(array $params) { - if (Helper::envNotEmpty('ALIBABA_CLOUD_PROFILE')) { - $this->profileName = Helper::env('ALIBABA_CLOUD_PROFILE'); + if (Helper::envNotEmpty(Config::ENV_PREFIX + 'PROFILE')) { + $this->profileName = Helper::env(Config::ENV_PREFIX + 'PROFILE'); } if (isset($params['profileName'])) { @@ -58,7 +53,7 @@ private function filterProfileName(array $params) private function filterProfileFile() { - $this->profileFile = Helper::envNotEmpty('ALIBABA_CLOUD_CREDENTIALS_FILE'); + $this->profileFile = Helper::envNotEmpty(Config::ENV_PREFIX + 'CREDENTIALS_FILE'); if (!$this->profileFile) { $this->profileFile = self::getDefaultFile(); @@ -173,7 +168,7 @@ private function getDefaultFile() { return Helper::getHomeDirectory() . DIRECTORY_SEPARATOR . - '.alibabacloud' . + Config::CREDENTIAL_FILE_PATH . DIRECTORY_SEPARATOR . 'credentials'; } diff --git a/src/Providers/RamRoleArnCredentialsProvider.php b/src/Providers/RamRoleArnCredentialsProvider.php index b69f6c5..aba4a09 100644 --- a/src/Providers/RamRoleArnCredentialsProvider.php +++ b/src/Providers/RamRoleArnCredentialsProvider.php @@ -10,13 +10,8 @@ use InvalidArgumentException; use RuntimeException; use AlibabaCloud\Credentials\Credential\RefreshResult; +use AlibabaCloud\Configure\Config; -/** - * @internal This class is intended for internal use within the package. - * Class RamRoleArnCredentialsProvider - * - * @package AlibabaCloud\Credentials\Providers - */ class RamRoleArnCredentialsProvider extends SessionCredentialsProvider { @@ -87,8 +82,8 @@ public function __construct(array $params = [], array $options = []) private function filterRoleArn(array $params) { - if (Helper::envNotEmpty('ALIBABA_CLOUD_ROLE_ARN')) { - $this->roleArn = Helper::env('ALIBABA_CLOUD_ROLE_ARN'); + if (Helper::envNotEmpty(Config::ENV_PREFIX + 'ROLE_ARN')) { + $this->roleArn = Helper::env(Config::ENV_PREFIX + 'ROLE_ARN'); } if (isset($params['roleArn'])) { @@ -100,8 +95,8 @@ private function filterRoleArn(array $params) private function filterRoleSessionName(array $params) { - if (Helper::envNotEmpty('ALIBABA_CLOUD_ROLE_SESSION_NAME')) { - $this->roleSessionName = Helper::env('ALIBABA_CLOUD_ROLE_SESSION_NAME'); + if (Helper::envNotEmpty(Config::ENV_PREFIX + 'ROLE_SESSION_NAME')) { + $this->roleSessionName = Helper::env(Config::ENV_PREFIX + 'ROLE_SESSION_NAME'); } if (isset($params['roleSessionName'])) { @@ -150,15 +145,15 @@ private function filterExternalId(array $params) private function filterSTSEndpoint(array $params) { $prefix = 'sts'; - if (Helper::envNotEmpty('ALIBABA_CLOUD_VPC_ENDPOINT_ENABLED') || (isset($params['enableVpc']) && $params['enableVpc'] === true)) { + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'VPC_ENDPOINT_ENABLED') || (isset($params['enableVpc']) && $params['enableVpc'] === true)) { $prefix = 'sts-vpc'; } - if (Helper::envNotEmpty('ALIBABA_CLOUD_STS_REGION')) { - $this->stsEndpoint = $prefix . '.' . Helper::env('ALIBABA_CLOUD_STS_REGION') . '.aliyuncs.com'; + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'STS_REGION')) { + $this->stsEndpoint = $prefix . '.' . Helper::env(Config::ENV_PREFIX . 'STS_REGION') . '.' . Config::ENDPOINT_SUFFIX; } if (isset($params['stsRegionId'])) { - $this->stsEndpoint = $prefix . '.' . $params['stsRegionId'] . '.aliyuncs.com'; + $this->stsEndpoint = $prefix . '.' . $params['stsRegionId'] . '.' . Config::ENDPOINT_SUFFIX; } if (isset($params['stsEndpoint'])) { @@ -166,7 +161,7 @@ private function filterSTSEndpoint(array $params) } if (is_null($this->stsEndpoint) || $this->stsEndpoint === '') { - $this->stsEndpoint = 'sts.aliyuncs.com'; + $this->stsEndpoint = Config::STS_DEFAULT_ENDPOINT; } } @@ -215,13 +210,12 @@ public function refreshCredentials() $options['read_timeout'] = $this->readTimeout; $options['connect_timeout'] = $this->connectTimeout; - $options['query']['Action'] = 'AssumeRole'; - $options['query']['Version'] = '2015-04-01'; - $options['query']['Format'] = 'JSON'; - $options['query']['Timestamp'] = gmdate('Y-m-d\TH:i:s\Z'); - $options['query']['SignatureMethod'] = 'HMAC-SHA1'; - $options['query']['SignatureVersion'] = '1.0'; - $options['query']['SignatureNonce'] = Request::uuid(json_encode($options['query'])); + $date = gmdate('Y-m-d\TH:i:s\Z'); + $options['headers']['x-acs-action'] = 'AssumeRole'; + $options['headers']['x-acs-action'] = '2015-04-01'; + $options['query']['accept'] = 'application/json'; + $options['headers']['x-acs-date'] = $date; + $options['query']['RoleArn'] = $this->roleArn; $options['query']['RoleSessionName'] = $this->roleSessionName; $options['query']['DurationSeconds'] = (string) $this->durationSeconds; @@ -232,15 +226,23 @@ public function refreshCredentials() $options['query']['ExternalId'] = $this->externalId; } + $options['headers']['x-acs-signature-nonce'] = Request::uuid(json_encode($options['query'])); + $sessionCredentials = $this->credentialsProvider->getCredentials(); - $options['query']['AccessKeyId'] = $sessionCredentials->getAccessKeyId(); if (!is_null($sessionCredentials->getSecurityToken())) { - $options['query']['SecurityToken'] = $sessionCredentials->getSecurityToken(); + $options['headers']['x-acs-accesskey-id'] = $sessionCredentials->getAccessKeyId(); + $options['headers']['x-acs-security-token'] = $sessionCredentials->getSecurityToken(); } - $options['query']['Signature'] = Request::shaHmac1sign( - Request::signString('GET', $options['query']), - $sessionCredentials->getAccessKeySecret() . '&' + + $dateNew = substr($date, 0, 11); + $dateNew = str_replace( + "-", + "", + $dateNew ); + $region = $this->getRegion($request->productId, $config->endpoint, $config->regionId); + $signingkey = $this->getSigningkey($signatureAlgorithm, $accessKeySecret, $request->productId, $region, $dateNew); + $request->headers["Authorization"] = $this->getAuthorization($request->pathname, $request->method, $request->query, $request->headers, $signatureAlgorithm, $hashedRequestPayload, $accessKeyId, $signingkey, $request->productId, $region, $dateNew); $url = (new Uri())->withScheme('https')->withHost($this->stsEndpoint); diff --git a/src/Providers/RsaKeyPairCredentialsProvider.php b/src/Providers/RsaKeyPairCredentialsProvider.php deleted file mode 100644 index 8c85db6..0000000 --- a/src/Providers/RsaKeyPairCredentialsProvider.php +++ /dev/null @@ -1,200 +0,0 @@ -filterOptions($options); - $this->filterDurationSeconds($params); - $this->filterSTSEndpoint($params); - $this->publicKeyId = isset($params['publicKeyId']) ? $params['publicKeyId'] : null; - $privateKeyFile = isset($params['privateKeyFile']) ? $params['privateKeyFile'] : null; - Filter::publicKeyId($this->publicKeyId); - Filter::privateKeyFile($privateKeyFile); - - try { - $this->privateKey = file_get_contents($privateKeyFile); - } catch (Exception $exception) { - throw new InvalidArgumentException($exception->getMessage()); - } - } - - private function filterOptions(array $options) - { - if (isset($options['connectTimeout'])) { - $this->connectTimeout = $options['connectTimeout']; - } - - if (isset($options['readTimeout'])) { - $this->readTimeout = $options['readTimeout']; - } - - Filter::timeout($this->connectTimeout, $this->readTimeout); - } - - private function filterDurationSeconds(array $params) - { - if (isset($params['durationSeconds'])) { - if (is_int($params['durationSeconds'])) { - $this->durationSeconds = $params['durationSeconds']; - } - } - if ($this->durationSeconds < 900) { - throw new InvalidArgumentException('Role session expiration should be in the range of 900s - max session duration'); - } - } - - private function filterSTSEndpoint(array $params) - { - if (isset($params['stsEndpoint'])) { - $this->stsEndpoint = $params['stsEndpoint']; - } - - if (is_null($this->stsEndpoint) || $this->stsEndpoint === '') { - $this->stsEndpoint = 'sts.ap-northeast-1.aliyuncs.com'; - } - } - - - /** - * Get credentials by request. - * - * @return RefreshResult - * @throws RuntimeException - * @throws GuzzleException - */ - public function refreshCredentials() - { - $options = Request::commonOptions(); - $options['read_timeout'] = $this->readTimeout; - $options['connect_timeout'] = $this->connectTimeout; - - $options['query']['Action'] = 'GenerateSessionAccessKey'; - $options['query']['Version'] = '2015-04-01'; - $options['query']['Format'] = 'JSON'; - $options['query']['Timestamp'] = gmdate('Y-m-d\TH:i:s\Z'); - $options['query']['SignatureMethod'] = 'SHA256withRSA'; - $options['query']['SignatureType'] = 'PRIVATEKEY'; - $options['query']['SignatureVersion'] = '1.0'; - $options['query']['SignatureNonce'] = Request::uuid(json_encode($options['query'])); - $options['query']['DurationSeconds'] = (string) $this->durationSeconds; - $options['query']['AccessKeyId'] = $this->publicKeyId; - $options['query']['Signature'] = Request::shaHmac256WithRsasign( - Request::signString('GET', $options['query']), - $this->privateKey - ); - - $url = (new Uri())->withScheme('https')->withHost($this->stsEndpoint); - - $result = Request::createClient()->request('GET', $url, $options); - - if ($result->getStatusCode() !== 200) { - throw new RuntimeException('Error refreshing credentials from RsaKeyPair, statusCode: ' . $result->getStatusCode() . ', result: ' . (string) $result); - } - - $json = $result->toArray(); - - if (!isset($json['SessionAccessKey']['SessionAccessKeyId']) || !isset($json['SessionAccessKey']['SessionAccessKeySecret'])) { - throw new RuntimeException('Error retrieving credentials from RsaKeyPair result:' . $result->toJson()); - } - - $credentials = []; - $credentials['AccessKeyId'] = $json['SessionAccessKey']['SessionAccessKeyId']; - $credentials['AccessKeySecret'] = $json['SessionAccessKey']['SessionAccessKeySecret']; - $credentials['Expiration'] = $json['SessionAccessKey']['Expiration']; - $credentials['SecurityToken'] = null; - - - return new RefreshResult(new Credentials([ - 'accessKeyId' => $credentials['AccessKeyId'], - 'accessKeySecret' => $credentials['AccessKeySecret'], - 'securityToken' => $credentials['SecurityToken'], - 'expiration' => \strtotime($credentials['Expiration']), - 'providerName' => $this->getProviderName(), - ]), $this->getStaleTime(strtotime($credentials['Expiration']))); - } - - public function key() - { - return 'rsa_key_pair#publicKeyId#' . $this->publicKeyId; - } - - public function getProviderName() - { - return 'rsa_key_pair'; - } - - /** - * @return string - */ - public function getPublicKeyId() - { - return $this->publicKeyId; - } - - /** - * @return mixed - */ - public function getPrivateKey() - { - return $this->privateKey; - } -} diff --git a/src/Providers/StaticAKCredentialsProvider.php b/src/Providers/StaticAKCredentialsProvider.php index 7e73cd0..c821642 100644 --- a/src/Providers/StaticAKCredentialsProvider.php +++ b/src/Providers/StaticAKCredentialsProvider.php @@ -4,13 +4,8 @@ use AlibabaCloud\Credentials\Utils\Helper; use AlibabaCloud\Credentials\Utils\Filter; +use AlibabaCloud\Configure\Config; -/** - * @internal This class is intended for internal use within the package. - * Class StaticAKCredentialsProvider - * - * @package AlibabaCloud\Credentials\Providers - */ class StaticAKCredentialsProvider implements CredentialsProvider { @@ -36,12 +31,12 @@ public function __construct(array $params = []) private function filterAK(array $params) { - if (Helper::envNotEmpty('ALIBABA_CLOUD_ACCESS_KEY_ID')) { - $this->accessKeyId = Helper::env('ALIBABA_CLOUD_ACCESS_KEY_ID'); + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'ACCESS_KEY_ID')) { + $this->accessKeyId = Helper::env(Config::ENV_PREFIX . 'ACCESS_KEY_ID'); } - if (Helper::envNotEmpty('ALIBABA_CLOUD_ACCESS_KEY_SECRET')) { - $this->accessKeySecret = Helper::env('ALIBABA_CLOUD_ACCESS_KEY_SECRET'); + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'ACCESS_KEY_SECRET')) { + $this->accessKeySecret = Helper::env(Config::ENV_PREFIX . 'ACCESS_KEY_SECRET'); } if (isset($params['accessKeyId'])) { diff --git a/src/Providers/StaticSTSCredentialsProvider.php b/src/Providers/StaticSTSCredentialsProvider.php index 957b25d..4205bc3 100644 --- a/src/Providers/StaticSTSCredentialsProvider.php +++ b/src/Providers/StaticSTSCredentialsProvider.php @@ -4,13 +4,8 @@ use AlibabaCloud\Credentials\Utils\Helper; use AlibabaCloud\Credentials\Utils\Filter; +use AlibabaCloud\Configure\Config; -/** - * @internal This class is intended for internal use within the package. - * Class StaticSTSCredentialsProvider - * - * @package AlibabaCloud\Credentials\Providers - */ class StaticSTSCredentialsProvider implements CredentialsProvider { @@ -41,16 +36,16 @@ public function __construct(array $params = []) private function filterSTS(array $params) { - if (Helper::envNotEmpty('ALIBABA_CLOUD_ACCESS_KEY_ID')) { - $this->accessKeyId = Helper::env('ALIBABA_CLOUD_ACCESS_KEY_ID'); + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'ACCESS_KEY_ID')) { + $this->accessKeyId = Helper::env(Config::ENV_PREFIX . 'ACCESS_KEY_ID'); } - if (Helper::envNotEmpty('ALIBABA_CLOUD_ACCESS_KEY_SECRET')) { - $this->accessKeySecret = Helper::env('ALIBABA_CLOUD_ACCESS_KEY_SECRET'); + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'ACCESS_KEY_SECRET')) { + $this->accessKeySecret = Helper::env(Config::ENV_PREFIX . 'ACCESS_KEY_SECRET'); } - if (Helper::envNotEmpty('ALIBABA_CLOUD_SECURITY_TOKEN')) { - $this->securityToken = Helper::env('ALIBABA_CLOUD_SECURITY_TOKEN'); + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'SECURITY_TOKEN')) { + $this->securityToken = Helper::env(Config::ENV_PREFIX . 'SECURITY_TOKEN'); } if (isset($params['accessKeyId'])) { diff --git a/src/Providers/URLCredentialsProvider.php b/src/Providers/URLCredentialsProvider.php index 617c19f..43c0a58 100644 --- a/src/Providers/URLCredentialsProvider.php +++ b/src/Providers/URLCredentialsProvider.php @@ -9,13 +9,8 @@ use InvalidArgumentException; use RuntimeException; use AlibabaCloud\Credentials\Credential\RefreshResult; +use AlibabaCloud\Configure\Config; -/** - * @internal This class is intended for internal use within the package. - * Class URLCredentialsProvider - * - * @package AlibabaCloud\Credentials\Providers - */ class URLCredentialsProvider extends SessionCredentialsProvider { @@ -61,12 +56,12 @@ private function filterOptions(array $options) private function filterCredentialsURI(array $params) { - if (Helper::envNotEmpty('ALIBABA_CLOUD_CREDENTIALS_URI')) { - $this->credentialsURI = Helper::env('ALIBABA_CLOUD_CREDENTIALS_URI'); + if (Helper::envNotEmpty(Config::ENV_PREFIX . 'CREDENTIALS_URI')) { + $this->credentialsURI = Helper::env(Config::ENV_PREFIX . 'CREDENTIALS_URI'); } - if (isset($params['credentialsURI'])) { - $this->credentialsURI = $params['credentialsURI']; + if (isset($params['credentialsUri'])) { + $this->credentialsURI = $params['credentialsUri']; } Filter::credentialsURI($this->credentialsURI); diff --git a/src/RamRoleArnCredential.php b/src/RamRoleArnCredential.php deleted file mode 100644 index ed75640..0000000 --- a/src/RamRoleArnCredential.php +++ /dev/null @@ -1,242 +0,0 @@ -filterParameters($credential); - $this->filterPolicy($credential); - - Filter::accessKey($credential['access_key_id'], $credential['access_key_secret']); - - $this->config = $config; - $this->accessKeyId = $credential['access_key_id']; - $this->accessKeySecret = $credential['access_key_secret']; - $this->roleArn = $credential['role_arn']; - $this->roleSessionName = $credential['role_session_name']; - } - - /** - * @param array $credential - */ - private function filterParameters(array $credential) - { - if (!isset($credential['access_key_id'])) { - throw new InvalidArgumentException('Missing required access_key_id option in config for ram_role_arn'); - } - - if (!isset($credential['access_key_secret'])) { - throw new InvalidArgumentException('Missing required access_key_secret option in config for ram_role_arn'); - } - - if (!isset($credential['role_arn'])) { - throw new InvalidArgumentException('Missing required role_arn option in config for ram_role_arn'); - } - - if (!isset($credential['role_session_name'])) { - throw new InvalidArgumentException('Missing required role_session_name option in config for ram_role_arn'); - } - } - - /** - * @param array $credential - */ - private function filterPolicy(array $credential) - { - if (isset($credential['policy'])) { - if (is_string($credential['policy'])) { - $this->policy = $credential['policy']; - } - - if (is_array($credential['policy'])) { - $this->policy = json_encode($credential['policy']); - } - } - } - - /** - * @return array - */ - public function getConfig() - { - return $this->config; - } - - /** - * @return string - */ - public function getRoleArn() - { - return $this->roleArn; - } - - /** - * @return string - */ - public function getRoleSessionName() - { - return $this->roleSessionName; - } - - /** - * @return string - */ - public function getPolicy() - { - return $this->policy; - } - - /** - * @return string - */ - public function __toString() - { - return "$this->accessKeyId#$this->accessKeySecret#$this->roleArn#$this->roleSessionName"; - } - - /** - * @return ShaHmac1Signature - */ - public function getSignature() - { - return new ShaHmac1Signature(); - } - - /** - * @return string - */ - public function getOriginalAccessKeyId() - { - return $this->accessKeyId; - } - - /** - * @return string - */ - public function getOriginalAccessKeySecret() - { - return $this->accessKeySecret; - } - - /** - * @return string - * @throws Exception - * @throws GuzzleException - */ - public function getAccessKeyId() - { - return $this->getSessionCredential()->getAccessKeyId(); - } - - /** - * @return AlibabaCloud\Credentials\Providers\Credentials - * @throws Exception - * @throws GuzzleException - */ - protected function getSessionCredential() - { - $params = [ - 'accessKeyId' => $this->accessKeyId, - 'accessKeySecret' => $this->accessKeyId, - 'roleArn' => $this->roleArn, - 'roleSessionName' => $this->roleSessionName, - 'policy' => $this->policy, - ]; - return (new RamRoleArnCredentialsProvider($params))->getCredentials(); - } - - /** - * @return string - * @throws Exception - * @throws GuzzleException - */ - public function getAccessKeySecret() - { - return $this->getSessionCredential()->getAccessKeySecret(); - } - - /** - * @return string - * @throws Exception - * @throws GuzzleException - */ - public function getSecurityToken() - { - return $this->getSessionCredential()->getSecurityToken(); - } - - /** - * @return string - * @throws Exception - * @throws GuzzleException - */ - public function getExpiration() - { - return $this->getSessionCredential()->getExpiration(); - } - - /** - * @inheritDoc - */ - public function getCredential() - { - $credentials = $this->getSessionCredential(); - return new CredentialModel([ - 'accessKeyId' => $credentials->getAccessKeyId(), - 'accessKeySecret' => $credentials->getAccessKeySecret(), - 'securityToken' => $credentials->getSecurityToken(), - 'type' => 'ram_role_arn', - ]); - } -} diff --git a/src/Request/Request.php b/src/Request/Request.php index f0ba62f..80069ed 100644 --- a/src/Request/Request.php +++ b/src/Request/Request.php @@ -81,6 +81,168 @@ public static function signString($method, array $parameters) return $method . '&%2F&' . self::percentEncode(substr($canonicalized, 1)); } + public function getAuthorization($pathname, $method, $query, $headers, $signatureAlgorithm, $payload, $ak, $signingkey, $product, $region, $date) + { + $signature = $this->getSignature($pathname, $method, $query, $headers, $signatureAlgorithm, $payload, $signingkey); + $signedHeaders = $this->getSignedHeaders($headers); + $signedHeadersStr = ArrayUtil::join($signedHeaders, ";"); + return "" . $signatureAlgorithm . " Credential=" . $ak . "/" . $date . "/" . $region . "/" . $product . "/" . $this->_signPrefix . "_request,SignedHeaders=" . $signedHeadersStr . ",Signature=" . $signature . ""; + } + + /** + * @param string $pathname + * @param string $method + * @param string[] $query + * @param string[] $headers + * @param string $signatureAlgorithm + * @param string $payload + * @param int[] $signingkey + * @return string + */ + public function getSignature($pathname, $method, $query, $headers, $signatureAlgorithm, $payload, $signingkey) + { + $canonicalURI = "/"; + if (!Utils::empty_($pathname)) { + $canonicalURI = $pathname; + } + $stringToSign = ""; + $canonicalizedResource = $this->buildCanonicalizedResource($query); + $canonicalizedHeaders = $this->buildCanonicalizedHeaders($headers); + $signedHeaders = $this->getSignedHeaders($headers); + $signedHeadersStr = ArrayUtil::join($signedHeaders, ";"); + $stringToSign = "" . $method . "\n" . $canonicalURI . "\n" . $canonicalizedResource . "\n" . $canonicalizedHeaders . "\n" . $signedHeadersStr . "\n" . $payload . ""; + $hex = EncodeUtil::hexEncode(EncodeUtil::hash(Utils::toBytes($stringToSign), $signatureAlgorithm)); + $stringToSign = "" . $signatureAlgorithm . "\n" . $hex . ""; + $signature = Utils::toBytes(""); + if (Utils::equalString($signatureAlgorithm, $this->_sha256)) { + $signature = SignatureUtil::HmacSHA256SignByBytes($stringToSign, $signingkey); + } else if (Utils::equalString($signatureAlgorithm, $this->_sm3)) { + $signature = SignatureUtil::HmacSM3SignByBytes($stringToSign, $signingkey); + } + return EncodeUtil::hexEncode($signature); + } + + /** + * @param string $signatureAlgorithm + * @param string $secret + * @param string $product + * @param string $region + * @param string $date + * @return array + */ + public function getSigningkey($signatureAlgorithm, $secret, $product, $region, $date) + { + $sc1 = "" . $this->_signPrefix . "" . $secret . ""; + $sc2 = Utils::toBytes(""); + if (Utils::equalString($signatureAlgorithm, $this->_sha256)) { + $sc2 = SignatureUtil::HmacSHA256Sign($date, $sc1); + } else if (Utils::equalString($signatureAlgorithm, $this->_sm3)) { + $sc2 = SignatureUtil::HmacSM3Sign($date, $sc1); + } + $sc3 = Utils::toBytes(""); + if (Utils::equalString($signatureAlgorithm, $this->_sha256)) { + $sc3 = SignatureUtil::HmacSHA256SignByBytes($region, $sc2); + } else if (Utils::equalString($signatureAlgorithm, $this->_sm3)) { + $sc3 = SignatureUtil::HmacSM3SignByBytes($region, $sc2); + } + $sc4 = Utils::toBytes(""); + if (Utils::equalString($signatureAlgorithm, $this->_sha256)) { + $sc4 = SignatureUtil::HmacSHA256SignByBytes($product, $sc3); + } else if (Utils::equalString($signatureAlgorithm, $this->_sm3)) { + $sc4 = SignatureUtil::HmacSM3SignByBytes($product, $sc3); + } + $hmac = Utils::toBytes(""); + if (Utils::equalString($signatureAlgorithm, $this->_sha256)) { + $hmac = SignatureUtil::HmacSHA256SignByBytes("" . $this->_signPrefix . "_request", $sc4); + } else if (Utils::equalString($signatureAlgorithm, $this->_sm3)) { + $hmac = SignatureUtil::HmacSM3SignByBytes("" . $this->_signPrefix . "_request", $sc4); + } + return $hmac; + } + + /** + * @param string $product + * @param string $endpoint + * @param string $regionId + * @return string + */ + public function getRegion($product, $endpoint, $regionId) + { + if (!Utils::empty_($regionId)) { + return $regionId; + } + $region = "center"; + if (Utils::empty_($product) || Utils::empty_($endpoint)) { + return $region; + } + $strs = StringUtil::split($endpoint, ":", null); + $withoutPort = @$strs[0]; + $preRegion = StringUtil::replace($withoutPort, "." . $this->_endpointSuffix . "", "", null); + $nodes = StringUtil::split($preRegion, ".", null); + if (Utils::equalNumber(ArrayUtil::size($nodes), 2)) { + $region = @$nodes[1]; + } + return $region; + } + + /** + * @param string[] $query + * @return string + */ + public function buildCanonicalizedResource($query) + { + $canonicalizedResource = ""; + if (!Utils::isUnset($query)) { + $queryArray = MapUtil::keySet($query); + $sortedQueryArray = ArrayUtil::ascSort($queryArray); + $separator = ""; + foreach ($sortedQueryArray as $key) { + $canonicalizedResource = "" . $canonicalizedResource . "" . $separator . "" . EncodeUtil::percentEncode($key) . ""; + if (!Utils::empty_(@$query[$key])) { + $canonicalizedResource = "" . $canonicalizedResource . "=" . EncodeUtil::percentEncode(@$query[$key]) . ""; + } + $separator = "&"; + } + } + return $canonicalizedResource; + } + + /** + * @param string[] $headers + * @return string + */ + public function buildCanonicalizedHeaders($headers) + { + $canonicalizedHeaders = ""; + $sortedHeaders = $this->getSignedHeaders($headers); + foreach ($sortedHeaders as $header) { + $canonicalizedHeaders = "" . $canonicalizedHeaders . "" . $header . ":" . StringUtil::trim(@$headers[$header]) . "\n"; + } + return $canonicalizedHeaders; + } + + /** + * @param string[] $headers + * @return array + */ + public function getSignedHeaders($headers) + { + $headersArray = MapUtil::keySet($headers); + $sortedHeadersArray = ArrayUtil::ascSort($headersArray); + $tmp = ""; + $separator = ""; + foreach ($sortedHeadersArray as $key) { + $lowerKey = StringUtil::toLower($key); + if (StringUtil::hasPrefix($lowerKey, "x-acs-") || StringUtil::equals($lowerKey, "host") || StringUtil::equals($lowerKey, "content-type")) { + if (!StringUtil::contains($tmp, $lowerKey)) { + $tmp = "" . $tmp . "" . $separator . "" . $lowerKey . ""; + $separator = ";"; + } + } + } + return StringUtil::split($tmp, ";", null); + } + /** * @param string $string * @param string $accessKeySecret diff --git a/src/RsaKeyPairCredential.php b/src/RsaKeyPairCredential.php deleted file mode 100644 index 12e719e..0000000 --- a/src/RsaKeyPairCredential.php +++ /dev/null @@ -1,185 +0,0 @@ -publicKeyId = $public_key_id; - $this->privateKeyFile = $private_key_file; - $this->config = $config; - try { - $this->privateKey = file_get_contents($private_key_file); - } catch (Exception $exception) { - throw new InvalidArgumentException($exception->getMessage()); - } - } - - /** - * @return array - */ - public function getConfig() - { - return $this->config; - } - - /** - * @return string - */ - public function getOriginalAccessKeyId() - { - return $this->getPublicKeyId(); - } - - /** - * @return string - */ - public function getPublicKeyId() - { - return $this->publicKeyId; - } - - /** - * @return string - */ - public function getOriginalAccessKeySecret() - { - return $this->getPrivateKey(); - } - - /** - * @return mixed - */ - public function getPrivateKey() - { - return $this->privateKey; - } - - /** - * @return string - */ - public function __toString() - { - return "publicKeyId#$this->publicKeyId"; - } - - /** - * @return ShaHmac1Signature - */ - public function getSignature() - { - return new ShaHmac1Signature(); - } - - /** - * @return string - * @throws Exception - * @throws GuzzleException - */ - public function getAccessKeyId() - { - return $this->getSessionCredential()->getAccessKeyId(); - } - - /** - * @return AlibabaCloud\Credentials\Providers\Credentials - * @throws Exception - * @throws GuzzleException - */ - protected function getSessionCredential() - { - $params = [ - 'publicKeyId' => $this->publicKeyId, - 'privateKeyFile' => $this->privateKeyFile, - ]; - return (new RsaKeyPairCredentialsProvider($params))->getCredentials(); - } - - /** - * @return string - * @throws Exception - * @throws GuzzleException - */ - public function getAccessKeySecret() - { - return $this->getSessionCredential()->getAccessKeySecret(); - } - - /** - * @return string - * @throws Exception - * @throws GuzzleException - */ - public function getSecurityToken() - { - return $this->getSessionCredential()->getSecurityToken(); - } - - /** - * @return int - * @throws Exception - * @throws GuzzleException - */ - public function getExpiration() - { - return $this->getSessionCredential()->getExpiration(); - } - - /** - * @inheritDoc - */ - public function getCredential() - { - $credentials = $this->getSessionCredential(); - return new CredentialModel([ - 'accessKeyId' => $credentials->getAccessKeyId(), - 'accessKeySecret' => $credentials->getAccessKeySecret(), - 'securityToken' => $credentials->getSecurityToken(), - 'type' => 'rsa_key_pair', - ]); - } -} diff --git a/src/Signature/BearerTokenSignature.php b/src/Signature/BearerTokenSignature.php deleted file mode 100644 index 1d67a80..0000000 --- a/src/Signature/BearerTokenSignature.php +++ /dev/null @@ -1,47 +0,0 @@ -getMessage() - ); - } - - return base64_encode($binarySignature); - } -} diff --git a/src/Signature/SignatureInterface.php b/src/Signature/SignatureInterface.php deleted file mode 100644 index 9dfb73b..0000000 --- a/src/Signature/SignatureInterface.php +++ /dev/null @@ -1,34 +0,0 @@ -accessKeyId = $access_key_id; - $this->accessKeySecret = $access_key_secret; - $this->expiration = $expiration; - $this->securityToken = $security_token; - } - - /** - * @return int - */ - public function getExpiration() - { - return $this->expiration; - } - - /** - * @return string - */ - public function getAccessKeyId() - { - return $this->accessKeyId; - } - - /** - * @return string - */ - public function getAccessKeySecret() - { - return $this->accessKeySecret; - } - - /** - * @return string - */ - public function getSecurityToken() - { - return $this->securityToken; - } - - /** - * @return string - */ - public function __toString() - { - return "$this->accessKeyId#$this->accessKeySecret#$this->securityToken"; - } - - /** - * @return ShaHmac1Signature - */ - public function getSignature() - { - return new ShaHmac1Signature(); - } - - /** - * @inheritDoc - */ - public function getCredential() - { - return new CredentialModel([ - 'accessKeyId' => $this->accessKeyId, - 'accessKeySecret' => $this->accessKeySecret, - 'securityToken' => $this->securityToken, - 'type' => 'sts', - ]); - } - -} diff --git a/src/Utils/Filter.php b/src/Utils/Filter.php index 959fd8f..f1c44c6 100644 --- a/src/Utils/Filter.php +++ b/src/Utils/Filter.php @@ -4,11 +4,7 @@ use InvalidArgumentException; -/** - * Class Filter - * - * @package AlibabaCloud\Credentials\Utils - */ + class Filter { diff --git a/src/Utils/Helper.php b/src/Utils/Helper.php index 1621fe1..37b831f 100644 --- a/src/Utils/Helper.php +++ b/src/Utils/Helper.php @@ -3,14 +3,11 @@ namespace AlibabaCloud\Credentials\Utils; use AlibabaCloud\Credentials\Credential; +use AlibabaCloud\Configure\Config; use org\bovigo\vfs\vfsStream; use Closure; -/** - * Class Helper - * - * @package AlibabaCloud\Credentials\Utils - */ + class Helper { /** @@ -232,7 +229,7 @@ public static function snakeToCamelCase($str) */ public static function getUserAgent() { - return sprintf('AlibabaCloud (%s; %s) PHP/%s Credentials/%s TeaDSL/1', PHP_OS, \PHP_SAPI, PHP_VERSION, Credential::VERSION); + return sprintf(Config::KEY . ' (%s; %s) PHP/%s Credentials/%s TeaDSL/1', PHP_OS, \PHP_SAPI, PHP_VERSION, Credential::VERSION); } /** diff --git a/src/Utils/MockTrait.php b/src/Utils/MockTrait.php index cc07119..8006b7c 100644 --- a/src/Utils/MockTrait.php +++ b/src/Utils/MockTrait.php @@ -10,11 +10,7 @@ use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; -/** - * Trait MockTrait - * - * @package AlibabaCloud\Credentials\Utils - */ + trait MockTrait { /** diff --git a/tests/Feature/CredentialTest.php b/tests/Feature/CredentialTest.php index c6c81fa..b616e72 100644 --- a/tests/Feature/CredentialTest.php +++ b/tests/Feature/CredentialTest.php @@ -11,11 +11,6 @@ use ReflectionException; use RuntimeException; -/** - * Class CredentialTest - * - * @package AlibabaCloud\Credentials\Tests\Feature - */ class CredentialTest extends TestCase { diff --git a/tests/Mock/VirtualFile.php b/tests/Mock/VirtualFile.php index 86e95da..617bc10 100644 --- a/tests/Mock/VirtualFile.php +++ b/tests/Mock/VirtualFile.php @@ -2,6 +2,7 @@ namespace AlibabaCloud\Credentials\Tests\Mock; +use AlibabaCloud\Configure\Config; use org\bovigo\vfs\vfsStream; class VirtualFile @@ -41,7 +42,7 @@ public function url($fileName = 'file') { return vfsStream::newFile($fileName) ->withContent($this->content) - ->at(vfsStream::setup('AlibabaCloud')) + ->at(vfsStream::setup(Config::KEY)) ->url(); } } diff --git a/tests/Unit/AccessKeyCredentialTest.php b/tests/Unit/AccessKeyCredentialTest.php deleted file mode 100644 index f5637d4..0000000 --- a/tests/Unit/AccessKeyCredentialTest.php +++ /dev/null @@ -1,104 +0,0 @@ -assertEquals($accessKeyId, $credential->getAccessKeyId()); - $this->assertEquals($accessKeySecret, $credential->getAccessKeySecret()); - $this->assertEquals('', $credential->getSecurityToken()); - $this->assertInstanceOf(ShaHmac1Signature::class, $credential->getSignature()); - $this->assertEquals("$accessKeyId#$accessKeySecret", (string)$credential); - - $credentialModel = $credential->getCredential(); - $this->assertEquals($accessKeyId, $credentialModel->getAccessKeyId()); - $this->assertEquals($accessKeySecret, $credentialModel->getAccessKeySecret()); - $this->assertEquals('access_key', $credentialModel->getType()); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage accessKeyId cannot be empty - */ - public function testAccessKeyIdEmpty() - { - // Setup - $accessKeyId = ''; - $accessKeySecret = 'bar'; - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('accessKeyId cannot be empty'); - - new AccessKeyCredential($accessKeyId, $accessKeySecret); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage accessKeyId must be a string - */ - public function testAccessKeyIdFormat() - { - // Setup - $accessKeyId = null; - $accessKeySecret = 'bar'; - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('accessKeyId must be a string'); - - new AccessKeyCredential($accessKeyId, $accessKeySecret); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage accessKeySecret cannot be empty - */ - public function testAccessKeySecretEmpty() - { - // Setup - $accessKeyId = 'foo'; - $accessKeySecret = ''; - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('accessKeySecret cannot be empty'); - - // Test - new AccessKeyCredential($accessKeyId, $accessKeySecret); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage accessKeySecret must be a string - */ - public function testAccessKeySecretFormat() - { - // Setup - $accessKeyId = 'foo'; - $accessKeySecret = null; - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('accessKeySecret must be a string'); - - // Test - new AccessKeyCredential($accessKeyId, $accessKeySecret); - } -} diff --git a/tests/Unit/BearerTokenCredentialTest.php b/tests/Unit/BearerTokenCredentialTest.php index 34a5fc3..7bd69a0 100644 --- a/tests/Unit/BearerTokenCredentialTest.php +++ b/tests/Unit/BearerTokenCredentialTest.php @@ -8,11 +8,6 @@ use Exception; use PHPUnit\Framework\TestCase; -/** - * Class BearerTokenCredentialTest - * - * @package AlibabaCloud\Credentials\Tests\Unit - */ class BearerTokenCredentialTest extends TestCase { diff --git a/tests/Unit/ChainProviderTest.php b/tests/Unit/ChainProviderTest.php deleted file mode 100644 index 673f285..0000000 --- a/tests/Unit/ChainProviderTest.php +++ /dev/null @@ -1,163 +0,0 @@ -expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('No providers in chain'); - ChainProvider::set(); - } - - public function testSetIni() - { - $vf = VirtualAccessKeyCredential::ok(); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE=$vf"); - ChainProvider::set( - ChainProvider::ini() - ); - self::assertTrue(ChainProvider::hasCustomChain()); - ChainProvider::customProvider(ChainProvider::getDefaultName()); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE="); - } - - public function testSetIniEmpty() - { - try { - putenv('ALIBABA_CLOUD_CREDENTIALS_FILE='); - ChainProvider::set( - ChainProvider::ini() - ); - self::assertTrue(ChainProvider::hasCustomChain()); - ChainProvider::customProvider(ChainProvider::getDefaultName()); - } catch (\Exception $exception) { - self::assertRegExp('/No such file or directory/', $exception->getMessage()); - } - } - - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Credentials file is not readable: /a/c - */ - public function testSetIniWithDIYFile() - { - putenv('ALIBABA_CLOUD_CREDENTIALS_FILE=/a/c'); - ChainProvider::set( - ChainProvider::ini() - ); - self::assertTrue(ChainProvider::hasCustomChain()); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Credentials file is not readable: /a/c'); - ChainProvider::customProvider(ChainProvider::getDefaultName()); - putenv('ALIBABA_CLOUD_CREDENTIALS_FILE='); - } - - public function testInOpenBaseDir() - { - if (!Helper::isWindows()) { - $dirs = 'vfs://AlibabaCloud:/home:/Users:/private:/a/b'; - } else { - $dirs = 'C:\\projects;C:\\Users'; - } - - putenv('ALIBABA_CLOUD_CREDENTIALS_FILE=/a/c'); - ini_set('open_basedir', $dirs); - self::assertEquals($dirs, ini_get('open_basedir')); - ChainProvider::set( - ChainProvider::ini() - ); - self::assertTrue(ChainProvider::hasCustomChain()); - ChainProvider::customProvider(ChainProvider::getDefaultName()); - putenv('ALIBABA_CLOUD_CREDENTIALS_FILE='); - ini_set('open_basedir', null); - } - - public function testDefaultProvider() - { - ChainProvider::defaultProvider(ChainProvider::getDefaultName()); - self::assertTrue(true); - } - - public function testSetEnv() - { - ChainProvider::set( - ChainProvider::env() - ); - self::assertTrue(ChainProvider::hasCustomChain()); - } - - public function testSetInstance() - { - putenv('ALIBABA_CLOUD_ECS_METADATA=role_arn'); - ChainProvider::set( - ChainProvider::instance() - ); - self::assertTrue(ChainProvider::hasCustomChain()); - ChainProvider::customProvider(ChainProvider::getDefaultName()); - putenv('ALIBABA_CLOUD_ECS_METADATA='); - } - - public function testDefaultFile() - { - self::assertStringEndsWith( - 'credentials', - ChainProvider::getDefaultFile() - ); - putenv('ALIBABA_CLOUD_PROFILE='); - } - - public function testDefaultName() - { - putenv('ALIBABA_CLOUD_PROFILE=default1'); - self::assertEquals( - 'default1', - ChainProvider::getDefaultName() - ); - - putenv('ALIBABA_CLOUD_PROFILE=null'); - self::assertEquals( - 'default', - ChainProvider::getDefaultName() - ); - - putenv('ALIBABA_CLOUD_PROFILE='); - } -} diff --git a/tests/Unit/CredentialTest.php b/tests/Unit/CredentialTest.php index feee2e4..b91279e 100644 --- a/tests/Unit/CredentialTest.php +++ b/tests/Unit/CredentialTest.php @@ -9,11 +9,6 @@ use PHPUnit\Framework\TestCase; use ReflectionException; -/** - * Class CredentialTest - * - * @package AlibabaCloud\Credentials\Tests\Unit - */ class CredentialTest extends TestCase { public function testLoad() diff --git a/tests/Unit/CredentialsTest.php b/tests/Unit/CredentialsTest.php index 6a28aa1..f06c1c3 100644 --- a/tests/Unit/CredentialsTest.php +++ b/tests/Unit/CredentialsTest.php @@ -8,11 +8,6 @@ use ReflectionException; use RuntimeException; -/** - * Class CredentialsTest - * - * @package AlibabaCloud\Credentials\Tests\Unit - */ class CredentialsTest extends TestCase { diff --git a/tests/Unit/EcsRamRoleCredentialTest.php b/tests/Unit/EcsRamRoleCredentialTest.php deleted file mode 100644 index a92ecee..0000000 --- a/tests/Unit/EcsRamRoleCredentialTest.php +++ /dev/null @@ -1,400 +0,0 @@ -credential = new EcsRamRoleCredential('EcsRamRoleTest'); - Credentials::cancelMock(); - } - - /** - * @throws GuzzleException - */ - public function testConstruct() - { - // Setup - $roleName = 'role_arn'; - $expected = "roleName#$roleName"; - - // Test - $credential = new EcsRamRoleCredential($roleName); - - // Assert - $this->assertEquals($roleName, $credential->getRoleName()); - $this->assertInstanceOf(ShaHmac1Signature::class, $credential->getSignature()); - $this->assertEquals(false, $credential->isDisableIMDSv1()); - $this->assertEquals($expected, (string)$credential); - - Credentials::mockResponse(200, [], 'RoleName'); - $this->credential = new EcsRamRoleCredential(); - self::assertEquals('RoleName', $this->credential->getRoleName()); - } - - private function getPrivateField($instance, $field) - { - $reflection = new ReflectionClass(EcsRamRoleCredential::class); - $privateProperty = $reflection->getProperty($field); - $privateProperty->setAccessible(true); - return $privateProperty->getValue($instance); - } - - /** - * @throws GuzzleException - */ - public function testConstructWithIMDSv2() - { - // Setup - $roleName = 'role_arn'; - $disabl1e_imdsv1 = true; - $metadataTokenDuration = 3600; - $credential = new EcsRamRoleCredential($roleName, $disabl1e_imdsv1, $metadataTokenDuration); - - self::assertEquals(true, $this->getPrivateField($credential, 'disableIMDSv1')); - self::assertEquals(3600, $this->getPrivateField($credential, 'metadataTokenDuration')); - - $credential = new EcsRamRoleCredential($roleName); - - self::assertEquals(false, $this->getPrivateField($credential, 'disableIMDSv1')); - self::assertEquals(21600, $this->getPrivateField($credential, 'metadataTokenDuration')); - } - - /** - * @throws GuzzleException - */ - public function testDefault() - { - $result = [ - 'Expiration' => '2049-10-01 00:00:00', - 'AccessKeyId' => 'foo', - 'AccessKeySecret' => 'bar', - 'SecurityToken' => 'token', - 'Code' => 'Success', - ]; - - 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); - 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()); - self::assertEquals('bar', $this->credential->getAccessKeySecret()); - self::assertEquals('token', $this->credential->getSecurityToken()); - self::assertEquals(strtotime('2049-10-01 00:00:00'), $this->credential->getExpiration()); - - 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()); - self::assertEquals('token', $credentialModel->getSecurityToken()); - $this->assertEquals('ecs_ram_role', $credentialModel->getType()); - } - - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessageRegExp /The role name was not found in the instance/ - * @throws GuzzleException - */ - public function testDefault404() - { - Credentials::mockResponse(200, [], 'Token'); - Credentials::mockResponse(404, [], 'RoleName'); - - $this->credential = new EcsRamRoleCredential(); - - $this->expectException(InvalidArgumentException::class); - if (method_exists($this, 'expectExceptionMessageMatches')) { - $this->expectExceptionMessageMatches('/The role name was not found in the instance/'); - } elseif (method_exists($this, 'expectExceptionMessageRegExp')) { - $this->expectExceptionMessageRegExp('/The role name was not found in the instance/'); - } - - self::assertEquals('foo', $this->credential->getAccessKeyId()); - } - - /** - * @expectedException RuntimeException - * @expectedExceptionMessageRegExp /Error retrieving credentials from result: RoleName/ - * @throws GuzzleException - */ - public function testDefault500() - { - Credentials::mockResponse(200, [], 'Token'); - Credentials::mockResponse(500, [], 'RoleName'); - $this->credential = new EcsRamRoleCredential(); - - $this->expectException(RuntimeException::class); - - if (method_exists($this, 'expectExceptionMessageMatches')) { - $this->expectExceptionMessageMatches('/Error retrieving role name from result: RoleName/'); - } elseif (method_exists($this, 'expectExceptionMessageRegExp')) { - $this->expectExceptionMessageRegExp('/Error retrieving role name from result: RoleName/'); - } - self::assertEquals('foo', $this->credential->getAccessKeyId()); - } - - /** - * @expectedException RuntimeException - * @expectedExceptionMessageRegExp /Error retrieving credentials from result is empty/ - * @throws GuzzleException - */ - public function testDefaultEmpty() - { - - Credentials::mockResponse(200, [], 'Token'); - Credentials::mockResponse(200, [], 'RoleNameTest'); - Credentials::mockResponse(200, [], 'Token'); - Credentials::mockResponse(200, [], []); - - $this->credential = new EcsRamRoleCredential(); - - $this->expectException(RuntimeException::class); - if (method_exists($this, 'expectExceptionMessageMatches')) { - $this->expectExceptionMessageMatches('/Error retrieving credentials from IMDS result:\[\]/'); - } elseif (method_exists($this, 'expectExceptionMessageRegExp')) { - $this->expectExceptionMessageRegExp('/Error retrieving credentials from IMDS result:\[\]/'); - } - - self::assertEquals('foo', $this->credential->getAccessKeyId()); - } - - /** - * Tears down the fixture, for example, close a network connection. - * This method is called after a test is executed. - * - * @throws GuzzleException - */ - public function testSts() - { - $result = [ - 'Expiration' => '2049-10-01 00:00:00', - 'AccessKeyId' => 'foo', - 'AccessKeySecret' => 'bar', - 'SecurityToken' => 'token', - 'Code' => 'Success', - ]; - Credentials::mockResponse(200, [], 'Token'); - Credentials::mockResponse(200, [], $result); - - self::assertEquals('foo', $this->credential->getAccessKeyId()); - self::assertEquals('bar', $this->credential->getAccessKeySecret()); - self::assertEquals('token', $this->credential->getSecurityToken()); - self::assertEquals(strtotime('2049-10-01 00:00:00'), $this->credential->getExpiration()); - } - - /** - * @throws Exception - * @throws \GuzzleHttp\Exception\GuzzleException - * @expectedException \RuntimeException - * @expectedExceptionMessage Result contains no credentials - */ - public function testStsIncomplete() - { - $result = [ - 'Expiration' => '2049-10-01 00:00:00', - 'AccessKeyId' => 'foo', - ]; - $credential = new EcsRamRoleCredential('EcsRamRoleTest2'); - Credentials::mockResponse(200, [], 'Token'); - Credentials::mockResponse(200, [], $result); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Error retrieving credentials from IMDS result:{"Expiration":"2049-10-01 00:00:00","AccessKeyId":"foo"}'); - // Test - self::assertEquals('foo', $credential->getAccessKeyId()); - } - - /** - * @throws Exception - * @throws \GuzzleHttp\Exception\GuzzleException - * @expectedException \RuntimeException - * @expectedExceptionMessage Result contains no credentials - */ - public function testStsNoCode() - { - $result = [ - 'Expiration' => '2049-10-01 00:00:00', - 'AccessKeyId' => 'foo', - 'AccessKeySecret' => 'bar', - 'SecurityToken' => 'token', - ]; - $credential = new EcsRamRoleCredential('EcsRamRoleTest2'); - Credentials::mockResponse(200, [], 'Token'); - Credentials::mockResponse(200, [], $result); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Error retrieving credentials from IMDS result, Code is not Success:{"Expiration":"2049-10-01 00:00:00","AccessKeyId":"foo","AccessKeySecret":"bar","SecurityToken":"token"}'); - // Test - self::assertEquals('foo', $credential->getAccessKeyId()); - } - - /** - * @throws Exception - * @throws \GuzzleHttp\Exception\GuzzleException - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The role was not found in the instance - */ - public function testSts404() - { - $result = [ - 'Expiration' => '2049-10-01 00:00:00', - 'AccessKeyId' => 'foo', - ]; - $credential = new EcsRamRoleCredential('EcsRamRoleTest3'); - Credentials::mockResponse(200, [], 'Token'); - Credentials::mockResponse(404, [], $result); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('The role was not found in the instance'); - // Test - self::assertEquals('foo', $credential->getAccessKeyId()); - } - - /** - * @throws Exception - * @throws \GuzzleHttp\Exception\GuzzleException - * @expectedException \RuntimeException - * @expectedExceptionMessageRegExp /Error retrieving credentials from result/ - */ - public function testSts500() - { - $result = [ - 'Expiration' => '2049-10-01 00:00:00', - 'AccessKeyId' => 'foo', - ]; - - $credential = new EcsRamRoleCredential('EcsRamRoleTest3'); - Credentials::mockResponse(200, [], 'Token'); - Credentials::mockResponse(500, [], $result); - - $this->expectException(RuntimeException::class); - if (method_exists($this, 'expectExceptionMessageMatches')) { - $this->expectExceptionMessageMatches('/Error refreshing credentials from IMDS, statusCode: 500, result/'); - } elseif (method_exists($this, 'expectExceptionMessageRegExp')) { - $this->expectExceptionMessageRegExp('/Error refreshing credentials from IMDS, statusCode: 500, result/'); - } - - // Test - self::assertEquals('foo', $credential->getAccessKeyId()); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage roleName cannot be empty - */ - public function testRoleNameEmpty() - { - // Setup - $roleName = ''; - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('roleName cannot be empty'); - // Test - new EcsRamRoleCredential($roleName); - } - - /** - * @throws Exception - * @throws \GuzzleHttp\Exception\GuzzleException - * @expectedException \RuntimeException - * @expectedExceptionMessageRegExp /timed/ - */ - public function testStsWithoutMock() - { - Credentials::cancelMock(); - - $credential = new EcsRamRoleCredential('EcsRamRoleTest4'); - - $this->expectException(RuntimeException::class); - if (method_exists($this, 'expectExceptionMessageMatches')) { - $this->expectExceptionMessageMatches('/Timeout was reached/'); - } elseif (method_exists($this, 'expectExceptionMessageRegExp')) { - $this->expectExceptionMessageRegExp('/Timeout was reached/'); - } - // Test - self::assertEquals('foo', $credential->getAccessKeyId()); - } - - public function testGetRoleNameFromMeta() - { - $provider = new EcsRamRoleCredential(); - - Credentials::mockResponse(200, [], 'RoleName'); - - $roleName = $provider->getRoleNameFromMeta(); - self::assertEquals('RoleName', $roleName); - } - - public function testGetRoleNameFromMetaError() - { - $provider = new EcsRamRoleCredential(); - - Credentials::mockResponse(200, [], ''); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Error retrieving credentials from result is empty'); - $provider->getRoleNameFromMeta(); - } - - public function testGetRoleNameFromMeta404() - { - $provider = new EcsRamRoleCredential(); - - Credentials::mockResponse(404, [], 'Error'); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('The role name was not found in the instance'); - - $provider->getRoleNameFromMeta(); - } - - public function testRoleNameFromMetaError() - { - $provider = new EcsRamRoleCredential(); - - Credentials::mockResponse(500, [], 'Error'); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Error retrieving credentials from result: Error'); - - $provider->getRoleNameFromMeta(); - } -} diff --git a/tests/Unit/Ini/VirtualAccessKeyCredential.php b/tests/Unit/Ini/VirtualAccessKeyCredential.php index 66604ab..bdfd0ca 100644 --- a/tests/Unit/Ini/VirtualAccessKeyCredential.php +++ b/tests/Unit/Ini/VirtualAccessKeyCredential.php @@ -2,6 +2,7 @@ namespace AlibabaCloud\Credentials\Tests\Unit\Ini; +use AlibabaCloud\Configure\Config; use org\bovigo\vfs\vfsStream; /** @@ -75,7 +76,7 @@ public function url() return vfsStream::newFile($fileName) ->withContent($this->content) - ->at(vfsStream::setup('AlibabaCloud')) + ->at(vfsStream::setup(Config::KEY)) ->url(); } diff --git a/tests/Unit/Ini/VirtualCLIConfig.php b/tests/Unit/Ini/VirtualCLIConfig.php index c86b90e..9c9d56b 100644 --- a/tests/Unit/Ini/VirtualCLIConfig.php +++ b/tests/Unit/Ini/VirtualCLIConfig.php @@ -2,6 +2,7 @@ namespace AlibabaCloud\Credentials\Tests\Unit\Ini; +use AlibabaCloud\Configure\Config; use org\bovigo\vfs\vfsStream; /** @@ -45,7 +46,7 @@ public function url() return vfsStream::newFile($fileName) ->withContent($this->content) - ->at(vfsStream::setup('.aliyun')) + ->at(vfsStream::setup(Config::CLI_CONFIG_DIR)) ->url(); } diff --git a/tests/Unit/Providers/CLIProfileCredentialsProviderTest.php b/tests/Unit/Providers/CLIProfileCredentialsProviderTest.php index 2874114..0a7c032 100644 --- a/tests/Unit/Providers/CLIProfileCredentialsProviderTest.php +++ b/tests/Unit/Providers/CLIProfileCredentialsProviderTest.php @@ -2,6 +2,7 @@ namespace AlibabaCloud\Credentials\Tests\Unit\Providers; +use AlibabaCloud\Configure\Config; use AlibabaCloud\Credentials\Credentials; use AlibabaCloud\Credentials\Providers\CLIProfileCredentialsProvider; use AlibabaCloud\Credentials\Tests\Unit\Ini\VirtualCLIConfig; @@ -10,11 +11,6 @@ use RuntimeException; use InvalidArgumentException; -/** - * Class CLIProfileCredentialsProviderTest - * - * @package AlibabaCloud\Credentials\Tests\Unit\Providers - */ class CLIProfileCredentialsProviderTest extends TestCase { /** @@ -64,7 +60,7 @@ public function testConstruct() $params = [ 'profileName' => 'test', ]; - putenv("ALIBABA_CLOUD_PROFILE=profileName"); + putenv(Config:: ENV_PREFIX . "PROFILE=profileName"); $provider = new CLIProfileCredentialsProvider($params); @@ -73,7 +69,7 @@ public function testConstruct() self::assertEquals('test', $profileName); self::assertEquals('cli_profile', $provider->getProviderName()); - putenv("ALIBABA_CLOUD_PROFILE="); + putenv(Config:: ENV_PREFIX . "PROFILE="); } public function testEmpty() @@ -247,7 +243,7 @@ public function testOIDCRoleArn() public function testDisableCLI() { - putenv("ALIBABA_CLOUD_CLI_PROFILE_DISABLED=true"); + putenv(Config:: ENV_PREFIX . "CLI_PROFILE_DISABLED=true"); $provider = new CLIProfileCredentialsProvider(); @@ -259,6 +255,6 @@ public function testDisableCLI() } $provider->getCredentials(); - putenv("ALIBABA_CLOUD_CLI_PROFILE_DISABLED="); + putenv(Config:: ENV_PREFIX . "CLI_PROFILE_DISABLED="); } } diff --git a/tests/Unit/Providers/DefaultCredentialsProviderTest.php b/tests/Unit/Providers/DefaultCredentialsProviderTest.php index 5769acd..da95169 100644 --- a/tests/Unit/Providers/DefaultCredentialsProviderTest.php +++ b/tests/Unit/Providers/DefaultCredentialsProviderTest.php @@ -2,6 +2,7 @@ namespace AlibabaCloud\Credentials\Tests\Unit\Providers; +use AlibabaCloud\Configure\Config; use AlibabaCloud\Credentials\Providers\DefaultCredentialsProvider; use AlibabaCloud\Credentials\Providers\ProfileCredentialsProvider; use AlibabaCloud\Credentials\Credentials; @@ -11,11 +12,6 @@ use RuntimeException; use InvalidArgumentException; -/** - * Class DefaultCredentialsProviderTest - * - * @package AlibabaCloud\Credentials\Tests\Unit\Providers - */ class DefaultCredentialsProviderTest extends TestCase { /** @@ -58,8 +54,8 @@ public function testGetProviderName() public function testDefaultProviderWithEnv() { - putenv("ALIBABA_CLOUD_ACCESS_KEY_ID=id"); - putenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET=secret"); + putenv(Config:: ENV_PREFIX . "ACCESS_KEY_ID=id"); + putenv(Config:: ENV_PREFIX . "ACCESS_KEY_SECRET=secret"); $provider = new DefaultCredentialsProvider(); $credentials = $provider->getCredentials(); @@ -67,25 +63,25 @@ public function testDefaultProviderWithEnv() self::assertEquals("secret", $credentials->getAccessKeySecret()); self::assertEquals("default/env", $credentials->getProviderName()); - putenv("ALIBABA_CLOUD_SECURITY_TOKEN=token"); + putenv(Config:: ENV_PREFIX . "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()); - putenv("ALIBABA_CLOUD_ACCESS_KEY_ID="); - putenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET="); - putenv("ALIBABA_CLOUD_SECURITY_TOKEN="); + putenv(Config:: ENV_PREFIX . "ACCESS_KEY_ID="); + putenv(Config:: ENV_PREFIX . "ACCESS_KEY_SECRET="); + putenv(Config:: ENV_PREFIX . "SECURITY_TOKEN="); } public function testDefaultProviderWithOIDC() { - putenv("ALIBABA_CLOUD_ROLE_ARN=role-arn"); - putenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN=provider-arn"); + putenv(Config:: ENV_PREFIX . "ROLE_ARN=role-arn"); + putenv(Config:: ENV_PREFIX . "OIDC_PROVIDER_ARN=provider-arn"); $vf = new VirtualFile("token"); $url = $vf->url("token-file"); - putenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE=$url"); + putenv(Config:: ENV_PREFIX . "OIDC_TOKEN_FILE=$url"); $provider = new DefaultCredentialsProvider(); $result = '{ @@ -108,28 +104,28 @@ public function testDefaultProviderWithOIDC() self::assertEquals("token", $credentials->getSecurityToken()); self::assertEquals("default/oidc_role_arn", $credentials->getProviderName()); - putenv("ALIBABA_CLOUD_ROLE_ARN="); - putenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN="); - putenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE="); + putenv(Config:: ENV_PREFIX . "ROLE_ARN="); + putenv(Config:: ENV_PREFIX . "OIDC_PROVIDER_ARN="); + putenv(Config:: ENV_PREFIX . "OIDC_TOKEN_FILE="); } public function testDefaultProviderWithProfile() { $vf = VirtualAccessKeyCredential::ok(); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE=$vf"); - putenv("ALIBABA_CLOUD_PROFILE=ok"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE=$vf"); + putenv(Config:: ENV_PREFIX . "PROFILE=ok"); $provider = new DefaultCredentialsProvider(); $credentials = $provider->getCredentials(); self::assertEquals("foo", $credentials->getAccessKeyId()); self::assertEquals("bar", $credentials->getAccessKeySecret()); self::assertEquals("default/profile", $credentials->getProviderName()); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE="); - putenv("ALIBABA_CLOUD_PROFILE="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE="); + putenv(Config:: ENV_PREFIX . "PROFILE="); } public function testDefaultProviderWithIMDS() { - putenv("ALIBABA_CLOUD_ECS_METADATA=roleName"); + putenv(Config:: ENV_PREFIX . "ECS_METADATA=roleName"); $provider = new DefaultCredentialsProvider(); $result = [ @@ -147,13 +143,13 @@ public function testDefaultProviderWithIMDS() self::assertEquals("token", $credentials->getSecurityToken()); self::assertEquals("default/ecs_ram_role", $credentials->getProviderName()); - putenv("ALIBABA_CLOUD_ECS_METADATA="); + putenv(Config:: ENV_PREFIX . "ECS_METADATA="); } public function testDefaultProviderWithURI() { - putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED=true"); - putenv("ALIBABA_CLOUD_CREDENTIALS_URI=http://localhost:8080/token"); + putenv(Config:: ENV_PREFIX . "ECS_METADATA_DISABLED=true"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_URI=http://localhost:8080/token"); $provider = new DefaultCredentialsProvider(); $result = [ @@ -169,20 +165,20 @@ public function testDefaultProviderWithURI() self::assertEquals("token", $credentials->getSecurityToken()); self::assertEquals("default/credential_uri", $credentials->getProviderName()); - putenv("ALIBABA_CLOUD_CREDENTIALS_URI="); - putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_URI="); + putenv(Config:: ENV_PREFIX . "ECS_METADATA_DISABLED="); } public function testDefaultProviderWithReuseLast() { // 同时开启OIDC和CredentialsURI - putenv("ALIBABA_CLOUD_ROLE_ARN=test-role-arn"); - putenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN=test-provider-arn"); + putenv(Config:: ENV_PREFIX . "ROLE_ARN=test-role-arn"); + putenv(Config:: ENV_PREFIX . "OIDC_PROVIDER_ARN=test-provider-arn"); $vf = new VirtualFile("token"); $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"); + putenv(Config:: ENV_PREFIX . "OIDC_TOKEN_FILE=$url"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_URI=http://localhost:8080/token"); + putenv(Config:: ENV_PREFIX . "ECS_METADATA_DISABLED=true"); $provider = new DefaultCredentialsProvider(); $result = [ @@ -218,23 +214,23 @@ public function testDefaultProviderWithReuseLast() self::assertEquals("token", $credentials->getSecurityToken()); self::assertEquals("default/credential_uri", $credentials->getProviderName()); - putenv("ALIBABA_CLOUD_CREDENTIALS_URI="); - putenv("ALIBABA_CLOUD_ROLE_ARN="); - putenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN="); - putenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE="); - putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_URI="); + putenv(Config:: ENV_PREFIX . "ROLE_ARN="); + putenv(Config:: ENV_PREFIX . "OIDC_PROVIDER_ARN="); + putenv(Config:: ENV_PREFIX . "OIDC_TOKEN_FILE="); + putenv(Config:: ENV_PREFIX . "ECS_METADATA_DISABLED="); } public function testDefaultProviderWithUnReuseLast() { // 同时开启OIDC和CredentialsURI - putenv("ALIBABA_CLOUD_ROLE_ARN=test-role-arn"); - putenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN=test-provider-arn"); + putenv(Config:: ENV_PREFIX . "ROLE_ARN=test-role-arn"); + putenv(Config:: ENV_PREFIX . "OIDC_PROVIDER_ARN=test-provider-arn"); $vf = new VirtualFile("token"); $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"); + putenv(Config:: ENV_PREFIX . "OIDC_TOKEN_FILE=$url"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_URI=http://localhost:8080/token"); + putenv(Config:: ENV_PREFIX . "ECS_METADATA_DISABLED=true"); $provider = new DefaultCredentialsProvider([ 'reuseLastProviderEnabled' => false, @@ -272,10 +268,10 @@ public function testDefaultProviderWithUnReuseLast() self::assertEquals("token", $credentials->getSecurityToken()); self::assertEquals("default/oidc_role_arn", $credentials->getProviderName()); - putenv("ALIBABA_CLOUD_CREDENTIALS_URI="); - putenv("ALIBABA_CLOUD_ROLE_ARN="); - putenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN="); - putenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE="); - putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_URI="); + putenv(Config:: ENV_PREFIX . "ROLE_ARN="); + putenv(Config:: ENV_PREFIX . "OIDC_PROVIDER_ARN="); + putenv(Config:: ENV_PREFIX . "OIDC_TOKEN_FILE="); + putenv(Config:: ENV_PREFIX . "ECS_METADATA_DISABLED="); } } diff --git a/tests/Unit/Providers/EcsRamRoleCredentialsProviderTest.php b/tests/Unit/Providers/EcsRamRoleCredentialsProviderTest.php index 186dc83..14bbabc 100644 --- a/tests/Unit/Providers/EcsRamRoleCredentialsProviderTest.php +++ b/tests/Unit/Providers/EcsRamRoleCredentialsProviderTest.php @@ -9,12 +9,8 @@ use PHPUnit\Framework\TestCase; use RuntimeException; use ReflectionClass; +use AlibabaCloud\Configure\Config; -/** - * Class EcsRamRoleCredentialsProviderTest - * - * @package AlibabaCloud\Credentials\Tests\Unit\Providers - */ class EcsRamRoleCredentialsProviderTest extends TestCase { @@ -61,8 +57,8 @@ public function testConstruct() 'connectTimeout' => 10, 'readTimeout' => 10, ]; - putenv("ALIBABA_CLOUD_ECS_METADATA=roleName"); - putenv("ALIBABA_CLOUD_IMDSV1_DISABLED=false"); + putenv(Config:: ENV_PREFIX . "ECS_METADATA=roleName"); + putenv(Config:: ENV_PREFIX . "IMDSV1_DISABLED=false"); $provider = new EcsRamRoleCredentialsProvider($params, $config); @@ -77,8 +73,8 @@ public function testConstruct() self::assertEquals(true, $provider->isDisableIMDSv1()); self::assertEquals('ecs_ram_role', $provider->getProviderName()); - putenv("ALIBABA_CLOUD_ECS_METADATA="); - putenv("ALIBABA_CLOUD_IMDSV1_DISABLED="); + putenv(Config:: ENV_PREFIX . "ECS_METADATA="); + putenv(Config:: ENV_PREFIX . "IMDSV1_DISABLED="); } /** @@ -88,7 +84,7 @@ public function testConstruct() public function testEnvDisabled() { - putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED=true"); + putenv(Config:: ENV_PREFIX . "ECS_METADATA_DISABLED=true"); $provider = new EcsRamRoleCredentialsProvider([], []); $this->expectException(RuntimeException::class); @@ -99,7 +95,7 @@ public function testEnvDisabled() } $provider->getCredentials(); - putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED="); + putenv(Config:: ENV_PREFIX . "ECS_METADATA_DISABLED="); } public function testGetDisableECSIMDSv1() @@ -124,37 +120,37 @@ public function testGetDisableECSIMDSv1() self::assertEquals(false, $this->invokeProtectedFunc($provider, 'isDisableIMDSv1')); - putenv('ALIBABA_CLOUD_IMDSV1_DISABLED=true'); - + putenv(Config::ENV_PREFIX + 'IMDSV1_DISABLED=true'); + $provider = new EcsRamRoleCredentialsProvider($params); self::assertEquals(true, $this->invokeProtectedFunc($provider, 'isDisableIMDSv1')); - putenv('ALIBABA_CLOUD_IMDSV1_DISABLED=TRUE'); + putenv(Config::ENV_PREFIX + 'IMDSV1_DISABLED=TRUE'); $provider = new EcsRamRoleCredentialsProvider($params); self::assertEquals(true, $this->invokeProtectedFunc($provider, 'isDisableIMDSv1')); - putenv('ALIBABA_CLOUD_IMDSV1_DISABLED=ok'); + putenv(Config::ENV_PREFIX + 'IMDSV1_DISABLED=ok'); $provider = new EcsRamRoleCredentialsProvider($params); self::assertEquals(false, $this->invokeProtectedFunc($provider, 'isDisableIMDSv1')); - putenv('ALIBABA_CLOUD_IMDSV1_DISABLED=1'); + putenv(Config::ENV_PREFIX + 'IMDSV1_DISABLED=1'); $provider = new EcsRamRoleCredentialsProvider($params); self::assertEquals(false, $this->invokeProtectedFunc($provider, 'isDisableIMDSv1')); - putenv('ALIBABA_CLOUD_IMDSV1_DISABLED=false'); + putenv(Config::ENV_PREFIX + 'IMDSV1_DISABLED=false'); $provider = new EcsRamRoleCredentialsProvider($params); self::assertEquals(false, $this->invokeProtectedFunc($provider, 'isDisableIMDSv1')); - putenv('ALIBABA_CLOUD_IMDSV1_DISABLED='); + putenv(Config::ENV_PREFIX + 'IMDSV1_DISABLED='); $provider = new EcsRamRoleCredentialsProvider($params); diff --git a/tests/Unit/Providers/OIDCRoleArnCredentialsProviderTest.php b/tests/Unit/Providers/OIDCRoleArnCredentialsProviderTest.php index 0dea255..11e2f11 100644 --- a/tests/Unit/Providers/OIDCRoleArnCredentialsProviderTest.php +++ b/tests/Unit/Providers/OIDCRoleArnCredentialsProviderTest.php @@ -2,6 +2,7 @@ namespace AlibabaCloud\Credentials\Tests\Unit\Providers; +use AlibabaCloud\Configure\Config; use AlibabaCloud\Credentials\Credentials; use AlibabaCloud\Credentials\Tests\Mock\VirtualFile; use AlibabaCloud\Credentials\Providers\OIDCRoleArnCredentialsProvider; @@ -10,11 +11,6 @@ use PHPUnit\Framework\TestCase; use ReflectionClass; -/** - * Class OIDCRoleArnCredentialsProviderTest - * - * @package AlibabaCloud\Credentials\Tests\Unit\Providers - */ class OIDCRoleArnCredentialsProviderTest extends TestCase { @@ -47,18 +43,18 @@ public function testConstruct() 'policy' => 'policy', 'stsRegionId' => 'cn-beijing', 'enableVpc' => true, - 'stsEndpoint' => 'sts.cn-zhangjiakou.aliyuncs.com' + 'stsEndpoint' => 'sts.cn-zhangjiakou.' . Config:: ENDPOINT_SUFFIX ]; $config = [ 'connectTimeout' => 10, 'readTimeout' => 10, ]; - putenv("ALIBABA_CLOUD_ROLE_ARN=roleArn"); - putenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN=providerArn"); - putenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE=/b/c"); - putenv("ALIBABA_CLOUD_ROLE_SESSION_NAME=sessionName"); - putenv("ALIBABA_CLOUD_STS_REGION=cn-hangzhou"); - putenv("ALIBABA_CLOUD_VPC_ENDPOINT_ENABLED=true"); + putenv(Config:: ENV_PREFIX . "ROLE_ARN=roleArn"); + putenv(Config:: ENV_PREFIX . "OIDC_PROVIDER_ARN=providerArn"); + putenv(Config:: ENV_PREFIX . "OIDC_TOKEN_FILE=/b/c"); + putenv(Config:: ENV_PREFIX . "ROLE_SESSION_NAME=sessionName"); + putenv(Config:: ENV_PREFIX . "STS_REGION=cn-hangzhou"); + putenv(Config:: ENV_PREFIX . "VPC_ENDPOINT_ENABLED=true"); $provider = new OIDCRoleArnCredentialsProvider($params, $config); self::assertEquals('oidc_role_arn', $provider->getProviderName()); @@ -67,7 +63,7 @@ public function testConstruct() $policy = $this->getPrivateField($provider, 'policy'); $oidcTokenFilePath = $this->getPrivateField($provider, 'oidcTokenFilePath'); $durationSeconds = $this->getPrivateField($provider, 'durationSeconds'); - self::assertEquals('sts.cn-zhangjiakou.aliyuncs.com', $stsEndpoint); + self::assertEquals('sts.cn-zhangjiakou.' . Config:: ENDPOINT_SUFFIX, $stsEndpoint); self::assertEquals('policy', $policy); self::assertEquals('/a/b', $oidcTokenFilePath); self::assertEquals(3600, $durationSeconds); @@ -79,17 +75,17 @@ public function testConstruct() $policy = $this->getPrivateField($provider, 'policy'); $oidcTokenFilePath = $this->getPrivateField($provider, 'oidcTokenFilePath'); $durationSeconds = $this->getPrivateField($provider, 'durationSeconds'); - self::assertEquals('sts-vpc.cn-hangzhou.aliyuncs.com', $stsEndpoint); + self::assertEquals('stscn-hangzhou.' . Config:: ENDPOINT_SUFFIX, $stsEndpoint); self::assertNull($policy); self::assertEquals('/b/c', $oidcTokenFilePath); self::assertEquals(3600, $durationSeconds); - putenv("ALIBABA_CLOUD_ROLE_ARN="); - putenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN="); - putenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE="); - putenv("ALIBABA_CLOUD_ROLE_SESSION_NAME="); - putenv("ALIBABA_CLOUD_STS_REGION="); - putenv("ALIBABA_CLOUD_VPC_ENDPOINT_ENABLED="); + putenv(Config:: ENV_PREFIX . "ROLE_ARN="); + putenv(Config:: ENV_PREFIX . "OIDC_PROVIDER_ARN="); + putenv(Config:: ENV_PREFIX . "OIDC_TOKEN_FILE="); + putenv(Config:: ENV_PREFIX . "ROLE_SESSION_NAME="); + putenv(Config:: ENV_PREFIX . "STS_REGION="); + putenv(Config:: ENV_PREFIX . "VPC_ENDPOINT_ENABLED="); } public function testConstructErrorRoleArn() diff --git a/tests/Unit/Providers/ProfileCredentialsProviderTest.php b/tests/Unit/Providers/ProfileCredentialsProviderTest.php index 864ae2a..5889c4f 100644 --- a/tests/Unit/Providers/ProfileCredentialsProviderTest.php +++ b/tests/Unit/Providers/ProfileCredentialsProviderTest.php @@ -14,12 +14,8 @@ use ReflectionClass; use RuntimeException; use InvalidArgumentException; +use AlibabaCloud\Configure\Config; -/** - * Class ProfileCredentialsProviderTest - * - * @package AlibabaCloud\Credentials\Tests\Unit\Providers - */ class ProfileCredentialsProviderTest extends TestCase { @@ -53,8 +49,8 @@ public function testConstruct() $params = [ 'profileName' => 'test', ]; - putenv("ALIBABA_CLOUD_PROFILE=profileName"); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE=/a/b"); + putenv(Config:: ENV_PREFIX . "PROFILE=profileName"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE=/a/b"); $provider = new ProfileCredentialsProvider($params); @@ -65,15 +61,15 @@ public function testConstruct() self::assertEquals('/a/b', $profileFile); self::assertEquals('profile', $provider->getProviderName()); - putenv("ALIBABA_CLOUD_PROFILE="); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE="); + putenv(Config:: ENV_PREFIX . "PROFILE="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE="); } public function testInvalidType() { $vf = VirtualAccessKeyCredential::invalidType(); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE=$vf"); - putenv("ALIBABA_CLOUD_PROFILE=phpunit"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE=$vf"); + putenv(Config:: ENV_PREFIX . "PROFILE=phpunit"); $this->expectException(RuntimeException::class); if (method_exists($this, 'expectExceptionMessageMatches')) { $this->expectExceptionMessageMatches('/Unsupported credential type from credentials file: invalidType/'); @@ -82,29 +78,29 @@ public function testInvalidType() } $provider = new ProfileCredentialsProvider(); $provider->getCredentials(); - putenv("ALIBABA_CLOUD_PROFILE="); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE="); + putenv(Config:: ENV_PREFIX . "PROFILE="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE="); } public function testAK() { $vf = VirtualAccessKeyCredential::ok(); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE=$vf"); - putenv("ALIBABA_CLOUD_PROFILE=ok"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE=$vf"); + putenv(Config:: ENV_PREFIX . "PROFILE=ok"); $provider = new ProfileCredentialsProvider(); $credentials = $provider->getCredentials(); self::assertEquals('foo', $credentials->getAccessKeyId()); self::assertEquals('bar', $credentials->getAccessKeySecret()); self::assertEquals('profile/static_ak', $credentials->getProviderName()); - putenv("ALIBABA_CLOUD_PROFILE="); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE="); + putenv(Config:: ENV_PREFIX . "PROFILE="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE="); } public function testAKNoKeyError() { $vf = VirtualAccessKeyCredential::noKey(); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE=$vf"); - putenv("ALIBABA_CLOUD_PROFILE=phpunit"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE=$vf"); + putenv(Config:: ENV_PREFIX . "PROFILE=phpunit"); $this->expectException(InvalidArgumentException::class); if (method_exists($this, 'expectExceptionMessageMatches')) { $this->expectExceptionMessageMatches('/accessKeyId must be a string/'); @@ -113,15 +109,15 @@ public function testAKNoKeyError() } $provider = new ProfileCredentialsProvider(); $provider->getCredentials(); - putenv("ALIBABA_CLOUD_PROFILE="); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE="); + putenv(Config:: ENV_PREFIX . "PROFILE="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE="); } public function testAKNoTypeError() { $vf = VirtualAccessKeyCredential::noType(); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE=$vf"); - putenv("ALIBABA_CLOUD_PROFILE=phpunit"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE=$vf"); + putenv(Config:: ENV_PREFIX . "PROFILE=phpunit"); $this->expectException(RuntimeException::class); if (method_exists($this, 'expectExceptionMessageMatches')) { $this->expectExceptionMessageMatches('/Unsupported credential type from credentials file/'); @@ -130,15 +126,15 @@ public function testAKNoTypeError() } $provider = new ProfileCredentialsProvider(); $provider->getCredentials(); - putenv("ALIBABA_CLOUD_PROFILE="); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE="); + putenv(Config:: ENV_PREFIX . "PROFILE="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE="); } public function testRamRoleArn() { $vf = VirtualRamRoleArnCredential::client(); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE=$vf"); - putenv("ALIBABA_CLOUD_PROFILE=phpunit"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE=$vf"); + putenv(Config:: ENV_PREFIX . "PROFILE=phpunit"); $provider = new ProfileCredentialsProvider(); $result = '{ @@ -155,15 +151,15 @@ public function testRamRoleArn() self::assertEquals('foo', $credentials->getAccessKeyId()); self::assertEquals('bar', $credentials->getAccessKeySecret()); self::assertEquals('profile/ram_role_arn/static_ak', $credentials->getProviderName()); - putenv("ALIBABA_CLOUD_PROFILE="); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE="); + putenv(Config:: ENV_PREFIX . "PROFILE="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE="); } public function testRamRoleArnError() { $vf = VirtualRamRoleArnCredential::noRoleArn(); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE=$vf"); - putenv("ALIBABA_CLOUD_PROFILE=phpunit"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE=$vf"); + putenv(Config:: ENV_PREFIX . "PROFILE=phpunit"); $provider = new ProfileCredentialsProvider(); $this->expectException(InvalidArgumentException::class); if (method_exists($this, 'expectExceptionMessageMatches')) { @@ -172,16 +168,16 @@ public function testRamRoleArnError() $this->expectExceptionMessageRegExp('/roleArn cannot be empty/'); } $provider->getCredentials(); - putenv("ALIBABA_CLOUD_PROFILE="); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE="); + putenv(Config:: ENV_PREFIX . "PROFILE="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE="); } public function testEcsRamRole() { $vf = VirtualEcsRamRoleCredential::client(); - putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED=false"); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE=$vf"); - putenv("ALIBABA_CLOUD_PROFILE=phpunit"); + putenv(Config:: ENV_PREFIX . "ECS_METADATA_DISABLED=false"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE=$vf"); + putenv(Config:: ENV_PREFIX . "PROFILE=phpunit"); $provider = new ProfileCredentialsProvider(); $result = [ @@ -199,9 +195,9 @@ public function testEcsRamRole() self::assertEquals('foo', $credentials->getAccessKeyId()); self::assertEquals('bar', $credentials->getAccessKeySecret()); self::assertEquals('profile/ecs_ram_role', $credentials->getProviderName()); - putenv("ALIBABA_CLOUD_PROFILE="); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE="); - putenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED="); + putenv(Config:: ENV_PREFIX . "PROFILE="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE="); + putenv(Config:: ENV_PREFIX . "ECS_METADATA_DISABLED="); } public function testOIDCRoleArn() @@ -209,8 +205,8 @@ public function testOIDCRoleArn() $vf = new VirtualFile("token"); $url = $vf->url("token-file"); $vf = VirtualOIDCRoleArnCredential::client($url); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE=$vf"); - putenv("ALIBABA_CLOUD_PROFILE=phpunit"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE=$vf"); + putenv(Config:: ENV_PREFIX . "PROFILE=phpunit"); $this->expectException(InvalidArgumentException::class); if (method_exists($this, 'expectExceptionMessageMatches')) { @@ -220,15 +216,15 @@ public function testOIDCRoleArn() } $provider = new ProfileCredentialsProvider(); $provider->getCredentials(); - putenv("ALIBABA_CLOUD_PROFILE="); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE="); + putenv(Config:: ENV_PREFIX . "PROFILE="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE="); } public function testOIDCRoleArnError() { $vf = VirtualOIDCRoleArnCredential::noRoleArn(); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE=$vf"); - putenv("ALIBABA_CLOUD_PROFILE=phpunit"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE=$vf"); + putenv(Config:: ENV_PREFIX . "PROFILE=phpunit"); $provider = new ProfileCredentialsProvider(); $this->expectException(InvalidArgumentException::class); if (method_exists($this, 'expectExceptionMessageMatches')) { @@ -237,15 +233,15 @@ public function testOIDCRoleArnError() $this->expectExceptionMessageRegExp('/roleArn cannot be empty/'); } $provider->getCredentials(); - putenv("ALIBABA_CLOUD_PROFILE="); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE="); + putenv(Config:: ENV_PREFIX . "PROFILE="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE="); } public function testRsaKeyPairNoPrivateKeyFile() { $vf = VirtualRsaKeyPairCredential::noPrivateKeyFile(); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE=$vf"); - putenv("ALIBABA_CLOUD_PROFILE=phpunit"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE=$vf"); + putenv(Config:: ENV_PREFIX . "PROFILE=phpunit"); $provider = new ProfileCredentialsProvider(); $this->expectException(InvalidArgumentException::class); if (method_exists($this, 'expectExceptionMessageMatches')) { @@ -254,15 +250,15 @@ public function testRsaKeyPairNoPrivateKeyFile() $this->expectExceptionMessageRegExp('/privateKeyFile must be a string/'); } $provider->getCredentials(); - putenv("ALIBABA_CLOUD_PROFILE="); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE="); + putenv(Config:: ENV_PREFIX . "PROFILE="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE="); } public function testRsaKeyPairNoPublicKeyId() { $vf = VirtualRsaKeyPairCredential::noPublicKeyId(); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE=$vf"); - putenv("ALIBABA_CLOUD_PROFILE=phpunit"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE=$vf"); + putenv(Config:: ENV_PREFIX . "PROFILE=phpunit"); $provider = new ProfileCredentialsProvider(); $this->expectException(InvalidArgumentException::class); if (method_exists($this, 'expectExceptionMessageMatches')) { @@ -271,8 +267,8 @@ public function testRsaKeyPairNoPublicKeyId() $this->expectExceptionMessageRegExp('/publicKeyId must be a string/'); } $provider->getCredentials(); - putenv("ALIBABA_CLOUD_PROFILE="); - putenv("ALIBABA_CLOUD_CREDENTIALS_FILE="); + putenv(Config:: ENV_PREFIX . "PROFILE="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_FILE="); } public function testSetIniError() @@ -283,9 +279,9 @@ public function testSetIniError() } elseif (method_exists($this, 'expectExceptionMessageRegExp')) { $this->expectExceptionMessageRegExp('/Unable to open credentials file/'); } - putenv('ALIBABA_CLOUD_CREDENTIALS_FILE=/c/d'); + putenv(Config::ENV_PREFIX + 'CREDENTIALS_FILE=/c/d'); $provider = new ProfileCredentialsProvider(); $provider->getCredentials(); - putenv('ALIBABA_CLOUD_CREDENTIALS_FILE='); + putenv(Config::ENV_PREFIX + 'CREDENTIALS_FILE='); } } diff --git a/tests/Unit/Providers/RamRoleArnCredentialsProviderTest.php b/tests/Unit/Providers/RamRoleArnCredentialsProviderTest.php index dda6091..3c9410e 100644 --- a/tests/Unit/Providers/RamRoleArnCredentialsProviderTest.php +++ b/tests/Unit/Providers/RamRoleArnCredentialsProviderTest.php @@ -2,6 +2,7 @@ namespace AlibabaCloud\Credentials\Tests\Unit\Providers; +use AlibabaCloud\Configure\Config; use AlibabaCloud\Credentials\Credentials; use AlibabaCloud\Credentials\Providers\RamRoleArnCredentialsProvider; use AlibabaCloud\Credentials\Providers\StaticAKCredentialsProvider; @@ -10,11 +11,6 @@ use PHPUnit\Framework\TestCase; use ReflectionClass; -/** - * Class RamRoleArnCredentialsProviderTest - * - * @package AlibabaCloud\Credentials\Tests\Unit\Providers - */ class RamRoleArnCredentialsProviderTest extends TestCase { @@ -48,16 +44,16 @@ public function testConstruct() 'externalId' => 'externalId', 'stsRegionId' => 'cn-beijing', 'enableVpc' => true, - 'stsEndpoint' => 'sts.cn-zhangjiakou.aliyuncs.com' + 'stsEndpoint' => 'sts.cn-zhangjiakou.' . Config:: ENDPOINT_SUFFIX ]; $config = [ 'connectTimeout' => 10, 'readTimeout' => 10, ]; - putenv("ALIBABA_CLOUD_ROLE_ARN=roleArn"); - putenv("ALIBABA_CLOUD_ROLE_SESSION_NAME=sessionName"); - putenv("ALIBABA_CLOUD_STS_REGION=cn-hangzhou"); - putenv("ALIBABA_CLOUD_VPC_ENDPOINT_ENABLED=true"); + putenv(Config:: ENV_PREFIX . "ROLE_ARN=roleArn"); + putenv(Config:: ENV_PREFIX . "ROLE_SESSION_NAME=sessionName"); + putenv(Config:: ENV_PREFIX . "STS_REGION=cn-hangzhou"); + putenv(Config:: ENV_PREFIX . "VPC_ENDPOINT_ENABLED=true"); $provider = new RamRoleArnCredentialsProvider($params, $config); @@ -70,7 +66,7 @@ public function testConstruct() self::assertEquals('ram_role_arn#credential#foo#roleArn#test#roleSessionName#default', $provider->key()); $stsEndpoint = $this->getPrivateField($provider, 'stsEndpoint'); $externalId = $this->getPrivateField($provider, 'externalId'); - self::assertEquals('sts.cn-zhangjiakou.aliyuncs.com', $stsEndpoint); + self::assertEquals('sts.cn-zhangjiakou.' . Config:: ENDPOINT_SUFFIX, $stsEndpoint); self::assertEquals('externalId', $externalId); $params = [ @@ -88,13 +84,13 @@ public function testConstruct() self::assertEquals('ram_role_arn#credential#foo#roleArn#roleArn#roleSessionName#sessionName', $provider->key()); $stsEndpoint = $this->getPrivateField($provider, 'stsEndpoint'); $externalId = $this->getPrivateField($provider, 'externalId'); - self::assertEquals('sts-vpc.cn-hangzhou.aliyuncs.com', $stsEndpoint); + self::assertEquals('sts.cn-hangzhou.' . Config:: ENDPOINT_SUFFIX, $stsEndpoint); self::assertNull($externalId); - putenv("ALIBABA_CLOUD_ROLE_ARN="); - putenv("ALIBABA_CLOUD_ROLE_SESSION_NAME="); - putenv("ALIBABA_CLOUD_STS_REGION="); - putenv("ALIBABA_CLOUD_VPC_ENDPOINT_ENABLED="); + putenv(Config:: ENV_PREFIX . "ROLE_ARN="); + putenv(Config:: ENV_PREFIX . "ROLE_SESSION_NAME="); + putenv(Config:: ENV_PREFIX . "STS_REGION="); + putenv(Config:: ENV_PREFIX . "VPC_ENDPOINT_ENABLED"); } public function testConstructErrorCredentials() diff --git a/tests/Unit/Providers/RsaKeyPairCredentialsProviderTest.php b/tests/Unit/Providers/RsaKeyPairCredentialsProviderTest.php index 1b63cac..b9755a1 100644 --- a/tests/Unit/Providers/RsaKeyPairCredentialsProviderTest.php +++ b/tests/Unit/Providers/RsaKeyPairCredentialsProviderTest.php @@ -2,6 +2,7 @@ namespace AlibabaCloud\Credentials\Tests\Unit\Providers; +use AlibabaCloud\Configure\Config; use AlibabaCloud\Credentials\Credentials; use AlibabaCloud\Credentials\Tests\Unit\Ini\VirtualRsaKeyPairCredential; use AlibabaCloud\Credentials\Providers\RsaKeyPairCredentialsProvider; @@ -10,11 +11,6 @@ use PHPUnit\Framework\TestCase; use ReflectionClass; -/** - * Class RsaKeyPairCredentialsProviderTest - * - * @package AlibabaCloud\Credentials\Tests\Unit\Providers - */ class RsaKeyPairCredentialsProviderTest extends TestCase { @@ -42,7 +38,7 @@ public function testConstruct() $params = [ 'publicKeyId' => 'test', 'privateKeyFile' => $url, - 'stsEndpoint' => 'sts.aliyuncs.com', + 'stsEndpoint' => 'sts.' . Config:: ENDPOINT_SUFFIX, 'durationSeconds' => 6000, ]; $config = [ @@ -59,7 +55,7 @@ public function testConstruct() self::assertEquals('test', $provider->getPublicKeyId()); $stsEndpoint = $this->getPrivateField($provider, 'stsEndpoint'); $durationSeconds = $this->getPrivateField($provider, 'durationSeconds'); - self::assertEquals('sts.aliyuncs.com', $stsEndpoint); + self::assertEquals('sts.' . Config:: ENDPOINT_SUFFIX, $stsEndpoint); self::assertEquals(6000, $durationSeconds); $params = [ @@ -74,7 +70,7 @@ public function testConstruct() self::assertEquals('test', $provider->getPublicKeyId()); $stsEndpoint = $this->getPrivateField($provider, 'stsEndpoint'); $durationSeconds = $this->getPrivateField($provider, 'durationSeconds'); - self::assertEquals('sts.ap-northeast-1.aliyuncs.com', $stsEndpoint); + self::assertEquals('sts.ap-northeast-1.' . Config:: ENDPOINT_SUFFIX, $stsEndpoint); self::assertEquals(3600, $durationSeconds); } diff --git a/tests/Unit/Providers/SessionCredentialsProviderTest.php b/tests/Unit/Providers/SessionCredentialsProviderTest.php index d577a80..0c3f30a 100644 --- a/tests/Unit/Providers/SessionCredentialsProviderTest.php +++ b/tests/Unit/Providers/SessionCredentialsProviderTest.php @@ -76,11 +76,6 @@ public function getCredentialsInCache() } } -/** - * Class SessionCredentialsProviderTest - * - * @package AlibabaCloud\Credentials\Tests\Unit\Providers - */ class SessionCredentialsProviderTest extends TestCase { diff --git a/tests/Unit/Providers/StaticCredentialsProviderTest.php b/tests/Unit/Providers/StaticCredentialsProviderTest.php index 5a8a1ac..a1af523 100644 --- a/tests/Unit/Providers/StaticCredentialsProviderTest.php +++ b/tests/Unit/Providers/StaticCredentialsProviderTest.php @@ -2,16 +2,12 @@ namespace AlibabaCloud\Credentials\Tests\Unit\Providers; +use AlibabaCloud\Configure\Config; use AlibabaCloud\Credentials\Credentials; use AlibabaCloud\Credentials\Providers\StaticSTSCredentialsProvider; use AlibabaCloud\Credentials\Providers\StaticAKCredentialsProvider; use PHPUnit\Framework\TestCase; -/** - * Class StaticCredentialsProviderTest - * - * @package AlibabaCloud\Credentials\Tests\Unit\Providers - */ class StaticCredentialsProviderTest extends TestCase { @@ -32,9 +28,9 @@ public function testConstruct() 'accessKeySecret' => 'test', 'securityToken' => 'test', ]; - putenv("ALIBABA_CLOUD_ACCESS_KEY_ID=id"); - putenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET=secret"); - putenv("ALIBABA_CLOUD_SECURITY_TOKEN=token"); + putenv(Config:: ENV_PREFIX . "ACCESS_KEY_ID=id"); + putenv(Config:: ENV_PREFIX . "ACCESS_KEY_SECRET=secret"); + putenv(Config:: ENV_PREFIX . "SECURITY_TOKEN=token"); $provider = new StaticSTSCredentialsProvider($params); $credential = $provider->getCredentials(); @@ -68,8 +64,8 @@ public function testConstruct() self::assertEquals('', $credential->getSecurityToken()); self::assertEquals('static_ak', $credential->getProviderName()); - putenv("ALIBABA_CLOUD_ACCESS_KEY_ID="); - putenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET="); - putenv("ALIBABA_CLOUD_SECURITY_TOKEN="); + putenv(Config:: ENV_PREFIX . "ACCESS_KEY_ID="); + putenv(Config:: ENV_PREFIX . "ACCESS_KEY_SECRET="); + putenv(Config:: ENV_PREFIX . "SECURITY_TOKEN="); } } diff --git a/tests/Unit/Providers/URLCredentialsProviderTest.php b/tests/Unit/Providers/URLCredentialsProviderTest.php index 5bfcfa1..1cd8f1b 100644 --- a/tests/Unit/Providers/URLCredentialsProviderTest.php +++ b/tests/Unit/Providers/URLCredentialsProviderTest.php @@ -2,6 +2,7 @@ namespace AlibabaCloud\Credentials\Tests\Unit\Providers; +use AlibabaCloud\Configure\Config; use AlibabaCloud\Credentials\Credentials; use AlibabaCloud\Credentials\Providers\URLCredentialsProvider; use RuntimeException; @@ -9,11 +10,6 @@ use PHPUnit\Framework\TestCase; use ReflectionClass; -/** - * Class URLCredentialsProviderTest - * - * @package AlibabaCloud\Credentials\Tests\Unit\Providers - */ class URLCredentialsProviderTest extends TestCase { @@ -44,7 +40,7 @@ public function testConstruct() 'connectTimeout' => 10, 'readTimeout' => 10, ]; - putenv("ALIBABA_CLOUD_CREDENTIALS_URI=http://test.aliyun.com"); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_URI=http://test.aliyun.com"); $provider = new URLCredentialsProvider($params, $config); @@ -59,7 +55,7 @@ public function testConstruct() $credentialsURI = $this->getPrivateField($provider, 'credentialsURI'); self::assertEquals('http://test.aliyun.com', $credentialsURI); - putenv("ALIBABA_CLOUD_CREDENTIALS_URI="); + putenv(Config:: ENV_PREFIX . "CREDENTIALS_URI="); } public function testConstructError() @@ -79,7 +75,7 @@ public function testConstructError() public function testSts() { $params = [ - 'credentialsURI' => 'http://credentials.aliyun.com', + 'credentialsURI' => 'http://example.com', ]; $provider = new URLCredentialsProvider($params); diff --git a/tests/Unit/RamRoleArnCredentialTest.php b/tests/Unit/RamRoleArnCredentialTest.php deleted file mode 100644 index 040791f..0000000 --- a/tests/Unit/RamRoleArnCredentialTest.php +++ /dev/null @@ -1,191 +0,0 @@ - 'access_key_id', - 'access_key_secret' => 'access_key_secret', - 'role_arn' => 'role_arn', - 'role_session_name' => 'role_session_name', - 'policy' => '', - ]); - - // Assert - $this->assertEquals($accessKeyId, $credential->getOriginalAccessKeyId()); - $this->assertEquals($accessKeySecret, $credential->getOriginalAccessKeySecret()); - $this->assertEquals($arn, $credential->getRoleArn()); - $this->assertEquals($sessionName, $credential->getRoleSessionName()); - $this->assertEquals($policy, $credential->getPolicy()); - $this->assertInstanceOf(ShaHmac1Signature::class, $credential->getSignature()); - $this->assertEquals( - "$accessKeyId#$accessKeySecret#$arn#$sessionName", - (string)$credential - ); - - $this->assertEquals( - [], - $credential->getConfig() - ); - } - - /** - * @throws Exception - * @throws \GuzzleHttp\Exception\GuzzleException - */ - public function testSts() - { - $result = '{ - "RequestId": "88FEA385-EF5D-4A8A-8C00-A07DAE3BFD44", - "AssumedRoleUser": { - "AssumedRoleId": "********************", - "Arn": "********************" - }, - "Credentials": { - "AccessKeySecret": "********************", - "AccessKeyId": "STS.**************", - "Expiration": "2049-02-25T03:56:19Z", - "SecurityToken": "**************" - } -}'; - Credentials::mockResponse(200, [], $result); - Credentials::mockResponse(200, [], $result); - Credentials::mockResponse(200, [], $result); - Credentials::mockResponse(200, [], $result); - $credential = new RamRoleArnCredential([ - 'access_key_id' => 'access_key_id', - 'access_key_secret' => 'access_key_secret', - 'role_arn' => 'role_arn1', - 'role_session_name' => 'role_session_name', - 'policy' => [], - ]); - - self::assertEquals('STS.**************', $credential->getAccessKeyId()); - self::assertEquals('********************', $credential->getAccessKeySecret()); - self::assertEquals('**************', $credential->getSecurityToken()); - self::assertEquals(strtotime('2049-02-25T03:56:19Z'), $credential->getExpiration()); - - Credentials::mockResponse(200, [], $result); - $credentialModel = $credential->getCredential(); - $this->assertEquals('STS.**************', $credentialModel->getAccessKeyId()); - $this->assertEquals('********************', $credentialModel->getAccessKeySecret()); - self::assertEquals('**************', $credentialModel->getSecurityToken()); - $this->assertEquals('ram_role_arn', $credentialModel->getType()); - } - - /** - * @throws Exception - * @throws \GuzzleHttp\Exception\GuzzleException - * @expectedException \RuntimeException - * @expectedExceptionMessage Result contains no credentials - */ - public function testStsIncomplete() - { - // Setup - Credentials::cancelMock(); - $result = '{ - "RequestId": "88FEA385-EF5D-4A8A-8C00-A07DAE3BFD44", - "AssumedRoleUser": { - "AssumedRoleId": "********************", - "Arn": "********************" - }, - "Credentials": { - "AccessKeyId": "STS.**************", - "Expiration": "2020-02-25T03:56:19Z", - "SecurityToken": "**************" - } -}'; - Credentials::mockResponse(200, [], $result); - $credential = new RamRoleArnCredential([ - 'access_key_id' => 'access_key_id2', - 'access_key_secret' => 'access_key_secret2', - 'role_arn' => 'role_arn2', - 'role_session_name' => 'role_session_name2', - 'policy' => '', - ]); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Error retrieving credentials from RamRoleArn result:{"RequestId":"88FEA385-EF5D-4A8A-8C00-A07DAE3BFD44","AssumedRoleUser":{"AssumedRoleId":"********************","Arn":"********************"},"Credentials":{"AccessKeyId":"STS.**************","Expiration":"2020-02-25T03:56:19Z","SecurityToken":"**************"}}'); - // Test - self::assertEquals('TMPSK.**************', $credential->getAccessKeyId()); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage access_key_id cannot be empty - */ - public function testAccessKeyIdEmpty() - { - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('accessKeyId cannot be empty'); - // Test - new RamRoleArnCredential([ - 'access_key_id' => '', - 'access_key_secret' => 'access_key_secret', - 'role_arn' => 'role_arn', - 'role_session_name' => 'role_session_name', - 'policy' => '', - ]); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Missing required access_key_secret option in config for ram_role_arn - */ - public function testAccessKeyIdFormat() - { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Missing required access_key_secret option in config for ram_role_arn'); - // Test - new RamRoleArnCredential([ - 'access_key_id' => 'access_key_id', - 'access_key_secret' => null, - 'role_arn' => 'role_arn', - 'role_session_name' => 'role_session_name', - 'policy' => '', - ]); - } - - /** - * @before - */ - protected function initialize() - { - // Setup - Credentials::cancelMock(); - $this->credential = new RamRoleArnCredential([ - 'access_key_id' => 'access_key_id', - 'access_key_secret' => 'access_key_secret', - 'role_arn' => 'role_arn', - 'role_session_name' => 'role_session_name', - 'policy' => '', - ]); - } -} diff --git a/tests/Unit/Request/RequestTest.php b/tests/Unit/Request/RequestTest.php index 0e61c1c..7490b6b 100644 --- a/tests/Unit/Request/RequestTest.php +++ b/tests/Unit/Request/RequestTest.php @@ -7,11 +7,6 @@ use PHPUnit\Framework\TestCase; use InvalidArgumentException; -/** - * Class RequestTest - * - * @package AlibabaCloud\Credentials\Tests\Unit\Request - */ class RequestTest extends TestCase { diff --git a/tests/Unit/RsaKeyPairCredentialTest.php b/tests/Unit/RsaKeyPairCredentialTest.php deleted file mode 100644 index f174c7d..0000000 --- a/tests/Unit/RsaKeyPairCredentialTest.php +++ /dev/null @@ -1,238 +0,0 @@ -getMessage()) - ); - } - } - - public static function testOpenBasedirException() - { - // Setup - $publicKeyId = 'PUBLIC_KEY_ID'; - if (Helper::isWindows()) { - $dirs = 'C:\\projects;C:\\Users'; - $privateKeyFile = 'C:\\AlibabaCloud\\no.no'; - } else { - $dirs = 'vfs://AlibabaCloud:/home:/Users:/private:/a/b'; - $privateKeyFile = '/dev/no.no'; - } - - // Test - ini_set('open_basedir', $dirs); - try { - new RsaKeyPairCredential($publicKeyId, $privateKeyFile); - } catch (Exception $e) { - self::assertEquals( - "file_get_contents(): open_basedir restriction in effect. File($privateKeyFile) is not within the allowed path(s): ($dirs)", - $e->getMessage() - ); - } - ini_set('open_basedir', null); - } - - public function testConstruct() - { - // Setup - $publicKeyId = 'public_key_id'; - $privateKeyFile = VirtualRsaKeyPairCredential::privateKeyFileUrl(); - - // Test - $credential = new RsaKeyPairCredential($publicKeyId, $privateKeyFile); - - // Assert - $this->assertEquals($publicKeyId, $credential->getPublicKeyId()); - $this->assertStringEqualsFile($privateKeyFile, $credential->getPrivateKey()); - $this->assertEquals( - "publicKeyId#$publicKeyId", - (string)$credential - ); - $this->assertEquals([], $credential->getConfig()); - $this->assertInstanceOf(ShaHmac1Signature::class, $credential->getSignature()); - $this->assertEquals($publicKeyId, $credential->getOriginalAccessKeyId()); - $this->assertNotEmpty($credential->getOriginalAccessKeySecret()); - } - - /** - * @throws Exception - * @throws GuzzleException - */ - public function testSts() - { - $publicKeyId = 'public_key_id'; - $privateKeyFile = VirtualRsaKeyPairCredential::privateKeyFileUrl(); - $result = '{ - "RequestId": "F702286E-F231-4F40-BB86-XXXXXX", - "SessionAccessKey": { - "SessionAccessKeyId": "TMPSK.**************", - "Expiration": "2049-02-19T07:02:36.225Z", - "SessionAccessKeySecret": "**************" - } -}'; - Credentials::mockResponse(200, [], $result); - Credentials::mockResponse(200, [], $result); - Credentials::mockResponse(200, [], $result); - Credentials::mockResponse(200, [], $result); - - // Test - $credential = new RsaKeyPairCredential($publicKeyId, $privateKeyFile); - - self::assertEquals('TMPSK.**************', $credential->getAccessKeyId()); - self::assertEquals('**************', $credential->getAccessKeySecret()); - self::assertEquals('', $credential->getSecurityToken()); - self::assertEquals(strtotime('2049-02-19T07:02:36.225Z'), $credential->getExpiration()); - - Credentials::mockResponse(200, [], $result); - $credentialModel = $this->credential->getCredential(); - $this->assertEquals('TMPSK.**************', $credentialModel->getAccessKeyId()); - $this->assertEquals('**************', $credentialModel->getAccessKeySecret()); - self::assertEquals('', $credentialModel->getSecurityToken()); - $this->assertEquals('rsa_key_pair', $credentialModel->getType()); - } - - /** - * @throws Exception - * @throws GuzzleException - * @expectedException \RuntimeException - * @expectedExceptionMessage Result contains no credentials - */ - public function testStsIncomplete() - { - // Setup - $publicKeyId = 'public_key_id_new'; - $privateKeyFile = VirtualRsaKeyPairCredential::privateKeyFileUrl(); - Credentials::cancelMock(); - $result = '{ - "RequestId": "F702286E-F231-4F40-BB86-XXXXXX", - "SessionAccessKey": { - "SessionAccessKeyId": "TMPSK.**************", - "Expiration": "2023-02-19T07:02:36.225Z" - } -}'; - Credentials::mockResponse(200, [], $result); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Error retrieving credentials from RsaKeyPair result:{"RequestId":"F702286E-F231-4F40-BB86-XXXXXX","SessionAccessKey":{"SessionAccessKeyId":"TMPSK.**************","Expiration":"2023-02-19T07:02:36.225Z"}}'); - - $credential = new RsaKeyPairCredential($publicKeyId, $privateKeyFile); - - // Test - self::assertEquals('TMPSK.**************', $credential->getAccessKeyId()); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage public_key_id cannot be empty - */ - public function testPublicKeyIdEmpty() - { - // Setup - $publicKeyId = ''; - $privateKeyFile = VirtualRsaKeyPairCredential::privateKeyFileUrl(); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('publicKeyId cannot be empty'); - // Test - new RsaKeyPairCredential($publicKeyId, $privateKeyFile); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage public_key_id must be a string - */ - public function testPublicKeyIdFormat() - { - // Setup - $publicKeyId = null; - $privateKeyFile = VirtualRsaKeyPairCredential::privateKeyFileUrl(); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('publicKeyId must be a string'); - // Test - new RsaKeyPairCredential($publicKeyId, $privateKeyFile); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage private_key_file cannot be empty - */ - public function testPrivateKeyFileEmpty() - { - // Setup - $publicKeyId = 'publicKeyId'; - $privateKeyFile = ''; - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('privateKeyFile cannot be empty'); - // Test - new RsaKeyPairCredential($publicKeyId, $privateKeyFile); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage private_key_file must be a string - */ - public function testPrivateKeyFileFormat() - { - // Setup - $publicKeyId = 'publicKeyId'; - $privateKeyFile = null; - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('privateKeyFile must be a string'); - // Test - new RsaKeyPairCredential($publicKeyId, $privateKeyFile); - } - - /** - * @before - */ - protected function initialize() - { - // Setup - Credentials::cancelMock(); - - // Setup - $publicKeyId = 'public_key_id'; - $privateKeyFile = VirtualRsaKeyPairCredential::privateKeyFileUrl(); - - // Test - $this->credential = new RsaKeyPairCredential($publicKeyId, $privateKeyFile); - } -} diff --git a/tests/Unit/Signature/BearerTokenSignatureTest.php b/tests/Unit/Signature/BearerTokenSignatureTest.php deleted file mode 100644 index cf31e73..0000000 --- a/tests/Unit/Signature/BearerTokenSignatureTest.php +++ /dev/null @@ -1,32 +0,0 @@ -sign($string, $accessKeySecret)); - static::assertEquals('', $signature->getMethod()); - static::assertEquals('1.0', $signature->getVersion()); - static::assertEquals('BEARERTOKEN', $signature->getType()); - } -} diff --git a/tests/Unit/Signature/ShaHmac1SignatureTest.php b/tests/Unit/Signature/ShaHmac1SignatureTest.php deleted file mode 100644 index 66a5a0d..0000000 --- a/tests/Unit/Signature/ShaHmac1SignatureTest.php +++ /dev/null @@ -1,32 +0,0 @@ -getMethod()); - static::assertEquals('1.0', $signature->getVersion()); - static::assertEquals('', $signature->getType()); - static::assertEquals($expected, $signature->sign($string, $accessKeySecret)); - } -} diff --git a/tests/Unit/Signature/ShaHmac256SignatureTest.php b/tests/Unit/Signature/ShaHmac256SignatureTest.php deleted file mode 100644 index 8ba521a..0000000 --- a/tests/Unit/Signature/ShaHmac256SignatureTest.php +++ /dev/null @@ -1,35 +0,0 @@ -getMethod()); - static::assertEquals('1.0', $signature->getVersion()); - static::assertEquals('', $signature->getType()); - static::assertEquals( - $expected, - $signature->sign($string, $accessKeySecret) - ); - } -} diff --git a/tests/Unit/Signature/ShaHmac256WithRsaSignatureTest.php b/tests/Unit/Signature/ShaHmac256WithRsaSignatureTest.php deleted file mode 100644 index c800d5e..0000000 --- a/tests/Unit/Signature/ShaHmac256WithRsaSignatureTest.php +++ /dev/null @@ -1,63 +0,0 @@ -getMethod()); - static::assertEquals('1.0', $signature->getVersion()); - static::assertEquals('PRIVATEKEY', $signature->getType()); - static::assertEquals( - $expected, - $signature->sign($string, \file_get_contents($privateKeyFile)) - ); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionCode 0 - * @expectedExceptionMessage openssl_sign(): supplied key param cannot be coerced into a private key - */ - public function testShaHmac256SignatureBadPrivateKey() - { - // Setup - $string = 'string'; - $privateKeyFile = VirtualRsaKeyPairCredential::badPrivateKey(); - - $this->expectException(InvalidArgumentException::class); - if (method_exists($this, 'expectExceptionMessageMatches')) { - $this->expectExceptionMessageMatches('/supplied key param cannot be coerced into a private key/i'); - } elseif (method_exists($this, 'expectExceptionMessageRegExp')) { - $this->expectExceptionMessageRegExp('/supplied key param cannot be coerced into a private key/i'); - } - - // Test - $signature = new ShaHmac256WithRsaSignature(); - - // Assert - $signature->sign($string, \file_get_contents($privateKeyFile)); - } -} diff --git a/tests/Unit/StsCredentialTest.php b/tests/Unit/StsCredentialTest.php deleted file mode 100644 index 67c92c0..0000000 --- a/tests/Unit/StsCredentialTest.php +++ /dev/null @@ -1,109 +0,0 @@ -assertEquals($accessKeyId, $credential->getAccessKeyId()); - $this->assertEquals($accessKeySecret, $credential->getAccessKeySecret()); - $this->assertEquals($securityToken, $credential->getSecurityToken()); - $this->assertEquals($expiration, $credential->getExpiration()); - $this->assertInstanceOf(ShaHmac1Signature::class, $credential->getSignature()); - $this->assertEquals( - "$accessKeyId#$accessKeySecret#$securityToken", - (string)$credential - ); - - $credentialModel = $credential->getCredential(); - $this->assertEquals($accessKeyId, $credentialModel->getAccessKeyId()); - $this->assertEquals($accessKeySecret, $credentialModel->getAccessKeySecret()); - self::assertEquals($securityToken, $credentialModel->getSecurityToken()); - $this->assertEquals('sts', $credentialModel->getType()); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage access_key_id cannot be empty - */ - public function testAccessKeyIdEmpty() - { - // Setup - $accessKeyId = ''; - $accessKeySecret = 'accessKeySecret'; - $securityToken = 'securityToken'; - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('accessKeyId cannot be empty'); - - new StsCredential($accessKeyId, $accessKeySecret, $securityToken); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage access_key_id must be a string - */ - public function testAccessKeyIdFormat() - { - // Setup - $accessKeyId = null; - $accessKeySecret = 'accessKeySecret'; - $securityToken = 'securityToken'; - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('accessKeyId must be a string'); - - new StsCredential($accessKeyId, $accessKeySecret, $securityToken); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage access_key_secret cannot be empty - */ - public function testAccessKeySecretEmpty() - { - // Setup - $accessKeyId = 'accessKeyId'; - $accessKeySecret = ''; - $securityToken = 'securityToken'; - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('accessKeySecret cannot be empty'); - - new StsCredential($accessKeyId, $accessKeySecret, $securityToken); - } - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage access_key_secret must be a string - */ - public function testAccessKeySecretFormat() - { - // Setup - $accessKeyId = 'accessKeyId'; - $accessKeySecret = null; - $securityToken = 'securityToken'; - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionCode(0); - $this->expectExceptionMessage('accessKeySecret must be a string'); - - new StsCredential($accessKeyId, $accessKeySecret, $securityToken); - } -} diff --git a/tests/Unit/Utils/FilterTest.php b/tests/Unit/Utils/FilterTest.php index 4ef7149..f50a95d 100644 --- a/tests/Unit/Utils/FilterTest.php +++ b/tests/Unit/Utils/FilterTest.php @@ -7,11 +7,6 @@ use Exception; use PHPUnit\Framework\TestCase; -/** - * Class FilterTest - * - * @package AlibabaCloud\Credentials\Tests\Unit\Filter - */ class FilterTest extends TestCase { /** diff --git a/tests/Unit/Utils/HelperTest.php b/tests/Unit/Utils/HelperTest.php index bef8b55..8ebfbc2 100644 --- a/tests/Unit/Utils/HelperTest.php +++ b/tests/Unit/Utils/HelperTest.php @@ -7,12 +7,8 @@ use PHPUnit\Framework\TestCase; use ReflectionClass; use ReflectionException; +use AlibabaCloud\Configure\Config; -/** - * Class HelperTest - * - * @package AlibabaCloud\Credentials\Tests\Unit - */ class HelperTest extends TestCase { public static function testDefault() @@ -58,25 +54,25 @@ public static function testSwitch() public static function testString() { - putenv('STRING="Alibaba Cloud"'); - self::assertEquals('"Alibaba Cloud"', getenv('STRING')); - self::assertEquals('Alibaba Cloud', Helper::env('STRING')); + putenv('STRING="Cloud"'); + self::assertEquals('"Cloud"', getenv('STRING')); + self::assertEquals('Cloud', Helper::env('STRING')); - putenv('STRING="Alibaba Cloud'); - self::assertEquals('"Alibaba Cloud', getenv('STRING')); - self::assertEquals('"Alibaba Cloud', Helper::env('STRING')); + putenv('STRING="Cloud'); + self::assertEquals('"Cloud', getenv('STRING')); + self::assertEquals('"Cloud', Helper::env('STRING')); } public static function testEnvNotEmpty() { - self::assertFalse(Helper::envNotEmpty('ALIBABA_CLOUD_NOT_EXISTS')); + self::assertFalse(Helper::envNotEmpty(Config::ENV_PREFIX + 'NOT_EXISTS')); } public static function testEnvNotEmptyException() { - putenv('ALIBABA_CLOUD_NOT_EXISTS='); + putenv(Config::ENV_PREFIX + 'NOT_EXISTS='); - self::assertFalse(Helper::envNotEmpty('ALIBABA_CLOUD_NOT_EXISTS')); + self::assertFalse(Helper::envNotEmpty(Config::ENV_PREFIX + 'NOT_EXISTS')); } public static function testInOpenBaseDir() @@ -86,11 +82,11 @@ public static function testInOpenBaseDir() ini_set('open_basedir', $dirs); self::assertEquals($dirs, ini_get('open_basedir')); } else { - $dirs = 'vfs://AlibabaCloud:/home:/Users:/private:/a/b'; + $dirs = 'vfs://' . Config::KEY . ':/home:/Users:/private:/a/b'; ini_set('open_basedir', $dirs); self::assertEquals($dirs, ini_get('open_basedir')); - self::assertTrue(Helper::inOpenBasedir('/Users/alibabacloud')); - self::assertTrue(Helper::inOpenBasedir('/private/alibabacloud')); + self::assertTrue(Helper::inOpenBasedir('/Users/test')); + self::assertTrue(Helper::inOpenBasedir('/private/test')); self::assertFalse(Helper::inOpenBasedir('/no/permission')); self::assertFalse(Helper::inOpenBasedir('/a')); self::assertTrue(Helper::inOpenBasedir('/a/b/')); @@ -142,11 +138,11 @@ public function testGetsHomeDirectoryForWindowsUser() { putenv('HOME='); putenv('HOMEDRIVE=C:'); - putenv('HOMEPATH=\\Users\\Alibaba'); + putenv('HOMEPATH=\\Users\\Test'); $ref = new ReflectionClass(Helper::class); $method = $ref->getMethod('getHomeDirectory'); $method->setAccessible(true); - $this->assertEquals('C:\\Users\\Alibaba', $method->invoke(null)); + $this->assertEquals('C:\\Users\\Test', $method->invoke(null)); } /** @@ -176,11 +172,12 @@ public function testSnakeToCamelCase() public function testGetUserAgent() { - self::assertStringStartsWith('AlibabaCloud', Helper::getUserAgent()); + self::assertStringStartsWith(Config::KEY, Helper::getUserAgent()); self::assertStringEndsWith('Credentials/' . Credential::VERSION . ' TeaDSL/1', Helper::getUserAgent()); } - public function testUnsetReturnNull() { + public function testUnsetReturnNull() + { $params = [ 'key' => 'value', 'test' => '', diff --git a/tests/Unit/Utils/MockTraitTest.php b/tests/Unit/Utils/MockTraitTest.php index 49178b3..273e45d 100644 --- a/tests/Unit/Utils/MockTraitTest.php +++ b/tests/Unit/Utils/MockTraitTest.php @@ -7,11 +7,6 @@ use GuzzleHttp\Psr7\Request; use PHPUnit\Framework\TestCase; -/** - * Class MockTraitTest - * - * @package AlibabaCloud\Credentials\Tests\Unit - */ class MockTraitTest extends TestCase { /**