Skip to content

Commit

Permalink
Merge pull request #8 from AxiosCros/dev/20200316
Browse files Browse the repository at this point in the history
work: improve credentials
  • Loading branch information
aliguyong authored Mar 16, 2020
2 parents cfb38ae + ce51a7e commit 1128a81
Show file tree
Hide file tree
Showing 10 changed files with 171 additions and 80 deletions.
6 changes: 1 addition & 5 deletions appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,8 @@ install:
- echo extension=php_curl.dll >> C:\tools\phpci\php\php.ini
- cd %APPVEYOR_BUILD_FOLDER%
- composer install --prefer-dist --no-progress
# Install Proxy
- npm install o_o -g

test_script:
# Start Proxy
- ps: Start-Process -FilePath o_o -NoNewWindow
# Test
- cd %APPVEYOR_BUILD_FOLDER%
- vendor\bin\phpunit --colors=always
- IF NOT DEFINED ACCESS_KEY_ID (vendor\bin\phpunit --colors=always --testsuite=Unit) ELSE (vendor\bin\phpunit --colors=always)
33 changes: 30 additions & 3 deletions src/Credential.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace AlibabaCloud\Credentials;

use AlibabaCloud\Credentials\Credential\Config;
use InvalidArgumentException;
use ReflectionClass;
use ReflectionException;
Expand Down Expand Up @@ -49,12 +50,15 @@ class Credential
/**
* Credential constructor.
*
* @param array $config
* @param array|Config $config
*
* @throws ReflectionException
*/
public function __construct(array $config = [])
public function __construct($config = [])
{
if ($config instanceof Config) {
$config = $this->parse($config);
}
if ($config !== []) {
$this->config = array_change_key_case($config);
$this->parseConfig();
Expand All @@ -63,6 +67,29 @@ public function __construct(array $config = [])
}
}

/**
* @param Config $config
*
* @return array
*/
private function parse($config)
{
$config = get_object_vars($config);
$res = [];
foreach ($config as $key => $value) {
$res[$this->toUnderScore($key)] = $value;
}
return $res;
}

private function toUnderScore($str)
{
$dstr = preg_replace_callback('/([A-Z]+)/', function ($matchs) {
return '_' . strtolower($matchs[0]);
}, $str);
return trim(preg_replace('/_{2,}/', '_', $dstr), '_');
}

/**
* @throws ReflectionException
*/
Expand Down Expand Up @@ -95,7 +122,7 @@ private function parseConfig()
/**
* @param ReflectionParameter $parameter
*
* @return string
* @return string|array
* @throws ReflectionException
*/
protected function getValue(ReflectionParameter $parameter)
Expand Down
50 changes: 50 additions & 0 deletions src/Credential/Config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace AlibabaCloud\Credentials\Credential;

class Config
{
/**
* @var string
*/
public $type = 'default';

public $accessKeyId = "";

public $accessKeySecret = "";

public $securityToken = "";

public $bearerToken = "";

public $roleName = "";

public $roleArn = "";

public $roleSessionName = "";

public $host = "";

public $publicKeyId = "";

public $privateKeyFile = "";

public $readTimeout = 0;

public $connectTimeout = 0;

public $certFile = "";

public $certPassword = "";

public $proxy = "";

public $expiration = 0;

public function __construct($config)
{
foreach ($config as $k => $v) {
$this->{$k} = $v;
}
}
}
3 changes: 1 addition & 2 deletions src/MockTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,7 @@ public static function mockRequestException(
ResponseInterface $response = null,
Exception $previous = null,
array $handlerContext = []
)
{
) {
self::$mockQueue[] = new RequestException(
$message,
$request,
Expand Down
6 changes: 3 additions & 3 deletions src/Providers/ChainProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public static function defaultProvider($name)
*/
public static function env()
{
return static function() {
return static function () {
$accessKeyId = Helper::envNotEmpty('ALIBABA_CLOUD_ACCESS_KEY_ID');
$accessKeySecret = Helper::envNotEmpty('ALIBABA_CLOUD_ACCESS_KEY_SECRET');

Expand Down Expand Up @@ -126,7 +126,7 @@ public static function getDefaultName()
*/
public static function ini()
{
return static function() {
return static function () {
$filename = Helper::envNotEmpty('ALIBABA_CLOUD_CREDENTIALS_FILE');
if (!$filename) {
$filename = self::getDefaultFile();
Expand Down Expand Up @@ -171,7 +171,7 @@ public static function getDefaultFile()
*/
public static function instance()
{
return static function() {
return static function () {
$instance = Helper::envNotEmpty('ALIBABA_CLOUD_ECS_METADATA');
if ($instance) {
Credentials::set(
Expand Down
9 changes: 3 additions & 6 deletions src/Request/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
use AlibabaCloud\Credentials\Signature\ShaHmac256WithRsaSignature;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Uri;
Expand Down Expand Up @@ -75,8 +74,7 @@ public function __construct()
}

/**
* @return Response
* @throws GuzzleException
* @return ResponseInterface
* @throws Exception
*/
public function request()
Expand All @@ -90,7 +88,6 @@ public function request()
self::signString('GET', $this->options['query']),
$this->credential->getOriginalAccessKeySecret() . '&'
);

return self::createClient()->request('GET', (string)$this->uri, $this->options);
}

Expand Down Expand Up @@ -128,7 +125,7 @@ public static function signString($method, array $parameters)
*/
private static function percentEncode($string)
{
$result = urlencode($string);
$result = rawurlencode($string);
$result = str_replace(['+', '*'], ['%20', '%2A'], $result);
$result = preg_replace('/%7E/', '~', $result);

Expand All @@ -147,7 +144,7 @@ public static function createClient()
$stack = HandlerStack::create();
}

$stack->push(Middleware::mapResponse(static function(ResponseInterface $response) {
$stack->push(Middleware::mapResponse(static function (ResponseInterface $response) {
return new Response($response);
}));

Expand Down
52 changes: 29 additions & 23 deletions tests/Feature/CredentialTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Credentials\Credentials;
use AlibabaCloud\Credentials\Tests\Helper;
use AlibabaCloud\Credentials\Tests\Unit\Ini\VirtualRsaKeyPairCredential;
use GuzzleHttp\Exception\GuzzleException;
use PHPUnit\Framework\TestCase;
Expand All @@ -23,11 +24,12 @@ class CredentialTest extends TestCase
*/
public function testAccessKey()
{
$credential = new Credential([
'type' => 'access_key',
'access_key_id' => 'foo',
'access_key_secret' => 'bar',
]);
$config = new Credential\Config([
'type' => 'access_key',
'accessKeyId' => 'foo',
'accessKeySecret' => 'bar',
]);
$credential = new Credential($config);

// Assert
$this->assertEquals('foo', $credential->getAccessKeyId());
Expand All @@ -42,10 +44,11 @@ public function testAccessKey()
*/
public function testEcsRamRoleCredential()
{
$credential = new Credential([
'type' => 'ecs_ram_role',
'role_name' => 'foo',
]);
$config = new Credential\Config([
'type' => 'ecs_ram_role',
'roleName' => 'foo',
]);
$credential = new Credential($config);

// Assert
$this->assertEquals('foo', $credential->getRoleName());
Expand All @@ -61,14 +64,16 @@ public function testEcsRamRoleCredential()
public function testRamRoleArnCredential()
{
Credentials::cancelMock();
$credential = new Credential([
'type' => 'ram_role_arn',
'access_key_id' => getenv('ACCESS_KEY_ID'),
'access_key_secret' => getenv('ACCESS_KEY_SECRET'),
'role_arn' => getenv('ROLE_ARN'),
'role_session_name' => 'role_session_name',
'policy' => '',
]);
$config = new Credential\Config([
'type' => 'ram_role_arn',
'accessKeyId' => Helper::getEnvironment('ACCESS_KEY_ID'),
'accessKeySecret' => Helper::getEnvironment('ACCESS_KEY_SECRET'),
'roleArn' => Helper::getEnvironment('ROLE_ARN'),
'roleSessionName' => 'role_session_name',
'policy' => '',
]);

$credential = new Credential($config);

// Assert
$this->assertEquals('access_key_id2', $credential->getAccessKeyId());
Expand All @@ -84,13 +89,14 @@ public function testRamRoleArnCredential()
public function testRsaKeyPairCredential()
{
Credentials::cancelMock();
$publicKeyId = getenv('PUBLIC_KEY_ID');
$publicKeyId = Helper::getEnvironment('PUBLIC_KEY_ID');
$privateKeyFile = VirtualRsaKeyPairCredential::privateKeyFileUrl();
$credential = new Credential([
'type' => 'rsa_key_pair',
'public_key_id' => $publicKeyId,
'private_key_file' => $privateKeyFile,
]);
$config = new Credential\Config([
'type' => 'rsa_key_pair',
'publicKeyId' => $publicKeyId,
'privateKeyFile' => $privateKeyFile,
]);
$credential = new Credential($config);

// Assert
$this->assertEquals('access_key_id2', $credential->getAccessKeyId());
Expand Down
1 change: 0 additions & 1 deletion tests/Unit/EcsRamRoleCredentialTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -218,5 +218,4 @@ public function testStsWithoutMock()
// Test
self::assertEquals('foo', $credential->getAccessKeyId());
}

}
Loading

0 comments on commit 1128a81

Please sign in to comment.