Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

upgrade imds v2 default #26

Merged
merged 1 commit into from
Jun 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ jobs:
strategy:
matrix:
operating-system: [ubuntu-latest]
php-versions: ['5.6', '7.0', '7.1', '7.2', '7.3', '7.4']
php-versions: ['5.6', '7.0', '7.1', '7.2', '7.3', '7.4', '8.0', '8.1', '8.2']
fail-fast: false
name: PHP ${{ matrix.php-versions }} Test on ${{ matrix.operating-system }}

steps:
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
"ext-sockets": "*",
"drupal/coder": "^8.3",
"symfony/dotenv": "^3.4",
"phpunit/phpunit": "^5.7|^6.6|^7.5",
"phpunit/phpunit": "^5.7|^6.6|^9.3",
"monolog/monolog": "^1.24",
"composer/composer": "^1.8",
"mikey179/vfsstream": "^1.6",
Expand Down
2 changes: 1 addition & 1 deletion src/Credential/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class Config

public $expiration = 0;

public $enableIMDSv2 = false;
public $disableIMDSv1 = false;

public $metadataTokenDuration = 21600;

Expand Down
18 changes: 13 additions & 5 deletions src/EcsRamRoleCredential.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class EcsRamRoleCredential implements CredentialsInterface
/**
* @var boolean
*/
private $enableIMDSv2;
private $disableIMDSv1;

/**
* @var int
Expand All @@ -37,15 +37,15 @@ class EcsRamRoleCredential implements CredentialsInterface
*
* @param $role_name
*/
public function __construct($role_name = null, $enable_IMDS_v2 = false, $metadata_token_duration = 21600 )
public function __construct($role_name = null, $disable_imdsv1 = false, $metadata_token_duration = 21600 )
{
Filter::roleName($role_name);

$this->roleName = $role_name;

Filter::enableIMDSv2($enable_IMDS_v2);
Filter::disableIMDSv1($disable_imdsv1);

$this->enableIMDSv2 = $enable_IMDS_v2;
$this->disableIMDSv1 = $disable_imdsv1;

Filter::metadataTokenDuration($metadata_token_duration);

Expand Down Expand Up @@ -136,7 +136,7 @@ public function getAccessKeyId()
protected function getSessionCredential()
{
$config = [
'enableIMDSv2' => $this->enableIMDSv2,
'disableIMDSv1' => $this->disableIMDSv1,
'metadataTokenDuration' => $this->metadataTokenDuration,
];
return (new EcsRamRoleProvider($this, $config))->get();
Expand Down Expand Up @@ -172,4 +172,12 @@ public function getExpiration()
return $this->getSessionCredential()->getExpiration();
}

/**
* @return bool
*/
public function isDisableIMDSv1()
{
return $this->disableIMDSv1;
}

}
8 changes: 4 additions & 4 deletions src/Filter.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,12 @@ public static function roleName($role_name)
}

/**
* @param boolean|null $enable_IMDS_v2
* @param boolean|null $disable_IMDS_v1
*/
public static function enableIMDSv2($enable_IMDS_v2)
public static function disableIMDSv1($disable_imdsv1)
{
if (!is_bool($enable_IMDS_v2)) {
throw new InvalidArgumentException('enable_IMDS_v2 must be a string');
if (!is_bool($disable_imdsv1)) {
throw new InvalidArgumentException('disable_IMDS_v1 must be a boolean');
}
}

Expand Down
30 changes: 15 additions & 15 deletions src/Providers/EcsRamRoleProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class EcsRamRoleProvider extends Provider
/**
* @var string
*/
private $metadataToken;
private $metadataToken = null;

/**
* @var string
Expand Down Expand Up @@ -84,13 +84,13 @@ public function get()
}


protected function getEnableECSIMDSv2()
protected function getDisableECSIMDSv1()
{
if (Helper::envNotEmpty('ALIBABA_CLOUD_ECS_IMDSV2_ENABLE')) {
return Helper::env('ALIBABA_CLOUD_ECS_IMDSV2_ENABLE') === true ? true : false;
if (Helper::envNotEmpty('ALIBABA_CLOUD_IMDSV1_DISABLE')) {
return Helper::env('ALIBABA_CLOUD_IMDSV1_DISABLE') === true ? true : false;
}
if(isset($this->config['enableIMDSv2'])) {
return $this->config['enableIMDSv2'];
if(isset($this->config['disableIMDSv1'])) {
return $this->config['disableIMDSv1'];
}
return false;
}
Expand All @@ -113,8 +113,8 @@ public function request()
'connect_timeout' => 1,
];

if ($this->getEnableECSIMDSv2()) {
$this->refreshMetadataToken();
$this->metadataToken = $this->refreshMetadataToken();
if(!is_null($this->metadataToken)) {
$options['headers']['X-aliyun-ecs-metadata-token'] = $this->metadataToken;
}

Expand All @@ -135,14 +135,14 @@ public function request()
/**
* Get metadata token by request.
*
* @return ResponseInterface
* @return bool
* @throws Exception
* @throws GuzzleException
*/
protected function refreshMetadataToken()
{
if(!$this->needToRefresh()) {
return;
return $this->metadataToken;
}
$credential = $this->credential;
$url = $this->metadataHost . $this->metadataTokenUri;
Expand All @@ -161,12 +161,12 @@ protected function refreshMetadataToken()

if ($result->getStatusCode() != 200) {
$this->staleTime = $tmpTime;
throw new RuntimeException('Failed to get token from ECS Metadata Service. HttpCode= ' . $result->getStatusCode());
if ($this->getDisableECSIMDSv1()) {
throw new RuntimeException('Failed to get token from ECS Metadata Service. HttpCode= ' . $result->getStatusCode());
}
return null;
}

$this->metadataToken = $result->getBody();

return;
return (string) $result->getBody();
}


Expand Down
12 changes: 11 additions & 1 deletion tests/Feature/CredentialTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use GuzzleHttp\Exception\GuzzleException;
use PHPUnit\Framework\TestCase;
use ReflectionException;
use RuntimeException;

/**
* Class CredentialTest
Expand Down Expand Up @@ -51,6 +52,13 @@ public function testEcsRamRoleCredential()
]);
$credential = new Credential($config);

$this->expectException(\GuzzleHttp\Exception\ConnectException::class);
if (method_exists($this, 'expectExceptionMessageMatches')) {
$this->expectExceptionMessageMatches('/timed/');
} elseif (method_exists($this, 'expectExceptionMessageRegExp')) {
$this->expectExceptionMessageRegExp('/timed/');
}

// Assert
$this->assertEquals('foo', $credential->getRoleName());
$this->assertEquals('ecs_ram_role', $credential->getType());
Expand Down Expand Up @@ -98,11 +106,13 @@ public function testRsaKeyPairCredential()
'privateKeyFile' => $privateKeyFile,
]);
$credential = new Credential($config);

$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Specified access key type is not match with signature type.');
// Assert
$this->assertTrue(null !== $credential->getAccessKeyId());
$this->assertTrue(null !== $credential->getAccessKeySecret());
$this->assertEquals('rsa_key_pair', $credential->getType());

$credential->getAccessKeySecret();
}

Expand Down
13 changes: 13 additions & 0 deletions tests/Unit/AccessKeyCredentialTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use AlibabaCloud\Credentials\AccessKeyCredential;
use AlibabaCloud\Credentials\Signature\ShaHmac1Signature;
use PHPUnit\Framework\TestCase;
use InvalidArgumentException;

/**
* Class AccessKeyCredentialTest
Expand Down Expand Up @@ -39,6 +40,9 @@ public function testAccessKeyIdEmpty()
$accessKeyId = '';
$accessKeySecret = 'bar';

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('access_key_id cannot be empty');

new AccessKeyCredential($accessKeyId, $accessKeySecret);
}

Expand All @@ -52,6 +56,9 @@ public function testAccessKeyIdFormat()
$accessKeyId = null;
$accessKeySecret = 'bar';

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('access_key_id must be a string');

new AccessKeyCredential($accessKeyId, $accessKeySecret);
}

Expand All @@ -65,6 +72,9 @@ public function testAccessKeySecretEmpty()
$accessKeyId = 'foo';
$accessKeySecret = '';

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('access_key_secret cannot be empty');

// Test
new AccessKeyCredential($accessKeyId, $accessKeySecret);
}
Expand All @@ -79,6 +89,9 @@ public function testAccessKeySecretFormat()
$accessKeyId = 'foo';
$accessKeySecret = null;

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('access_key_secret must be a string');

// Test
new AccessKeyCredential($accessKeyId, $accessKeySecret);
}
Expand Down
11 changes: 9 additions & 2 deletions tests/Unit/BearerTokenCredentialTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use AlibabaCloud\Credentials\BearerTokenCredential;
use AlibabaCloud\Credentials\Signature\BearerTokenSignature;
use InvalidArgumentException;
use Exception;
use PHPUnit\Framework\TestCase;

/**
Expand All @@ -19,24 +20,30 @@ class BearerTokenCredentialTest extends TestCase
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage bearer_token cannot be empty
*/
public static function testBearerTokenEmpty()
public function testBearerTokenEmpty()
{
// Setup
$bearerToken = '';

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('bearer_token cannot be empty');
// Test
new BearerTokenCredential($bearerToken);

}

/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage bearer_token must be a string
*/
public static function testBearerTokenFormat()
public function testBearerTokenFormat()
{
// Setup
$bearerToken = null;

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('bearer_token must be a string');

// Test
new BearerTokenCredential($bearerToken);
}
Expand Down
12 changes: 11 additions & 1 deletion tests/Unit/ChainProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
use AlibabaCloud\Credentials\Providers\ChainProvider;
use AlibabaCloud\Credentials\Tests\Unit\Ini\VirtualAccessKeyCredential;
use PHPUnit\Framework\TestCase;
use RuntimeException;
use InvalidArgumentException;

/**
* Class ChainProviderTest
Expand All @@ -20,6 +22,8 @@ class ChainProviderTest extends TestCase
*/
public function testNoProvides()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('No providers in chain');
ChainProvider::set();
}

Expand Down Expand Up @@ -59,6 +63,8 @@ public function testSetIniWithDIYFile()
ChainProvider::ini()
);
self::assertTrue(ChainProvider::hasCustomChain());
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Credentials file is not readable: /a/c');
ChainProvider::customProvider(ChainProvider::getDefaultName());
}

Expand All @@ -83,6 +89,7 @@ public function testInOpenBaseDir()
public function testDefaultProvider()
{
ChainProvider::defaultProvider(ChainProvider::getDefaultName());
self::assertTrue(true);
}

public function testSetEnv()
Expand Down Expand Up @@ -127,7 +134,10 @@ public function testDefaultName()
);
}

protected function setUp()
/**
* @before
*/
protected function initialize()
{
parent::setUp();
putenv('ALIBABA_CLOUD_ACCESS_KEY_ID=foo');
Expand Down
10 changes: 6 additions & 4 deletions tests/Unit/CredentialTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public function testLoad()
} catch (Exception $exception) {
self::assertEquals($exception->getMessage(), "Credential 'default' not found");
}
self::assertTrue(true);
}

/**
Expand All @@ -36,8 +37,9 @@ public function testException(array $config, $message)
try {
new Credential($config);
} catch (Exception $e) {
self::assertEquals($message, $e->getMessage());
self::assertEquals(strtolower($message), strtolower($e->getMessage()));
}
self::assertTrue(true);
}

/**
Expand Down Expand Up @@ -175,16 +177,16 @@ public function exceptionCases()
[
'type' => 'ecs_ram_role',
'role_name' => 'test',
'enableIMDSv2' => 'false',
'disableIMDSv1' => 'false',
],
'enable_IMDS_v2 must be a string',
'disable_IMDS_v1 must be a boolean',
],

[
[
'type' => 'ecs_ram_role',
'role_name' => 'test',
'enableIMDSv2' => false,
'disableIMDSv1' => false,
'metadataTokenDuration' => 3600,
],
'metadata_token_duration must be a int',
Expand Down
Loading
Loading