初始化仓库

This commit is contained in:
wangxiaowei
2025-04-22 14:09:52 +08:00
commit 8b100110bb
5155 changed files with 664201 additions and 0 deletions

View File

@ -0,0 +1,65 @@
<?php
namespace AlibabaCloud\Client\Credentials;
use AlibabaCloud\Client\Filter\CredentialFilter;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Use the AccessKey to complete the authentication.
*
* @package AlibabaCloud\Client\Credentials
*/
class AccessKeyCredential implements CredentialsInterface
{
/**
* @var string
*/
private $accessKeyId;
/**
* @var string
*/
private $accessKeySecret;
/**
* AccessKeyCredential constructor.
*
* @param string $accessKeyId Access key ID
* @param string $accessKeySecret Access Key Secret
*
* @throws ClientException
*/
public function __construct($accessKeyId, $accessKeySecret)
{
CredentialFilter::AccessKey($accessKeyId, $accessKeySecret);
$this->accessKeyId = $accessKeyId;
$this->accessKeySecret = $accessKeySecret;
}
/**
* @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";
}
}

View File

@ -0,0 +1,66 @@
<?php
namespace AlibabaCloud\Client\Credentials;
use AlibabaCloud\Client\Filter\CredentialFilter;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class BearerTokenCredential
*
* @package AlibabaCloud\Client\Credentials
*/
class BearerTokenCredential implements CredentialsInterface
{
/**
* @var string
*/
private $bearerToken;
/**
* Class constructor.
*
* @param string $bearerToken
*
* @throws ClientException
*/
public function __construct($bearerToken)
{
CredentialFilter::bearerToken($bearerToken);
$this->bearerToken = $bearerToken;
}
/**
* @return string
*/
public function getBearerToken()
{
return $this->bearerToken;
}
/**
* @return string
*/
public function getAccessKeyId()
{
return '';
}
/**
* @return string
*/
public function getAccessKeySecret()
{
return '';
}
/**
* @return string
*/
public function __toString()
{
return "bearerToken#$this->bearerToken";
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace AlibabaCloud\Client\Credentials;
/**
* interface CredentialsInterface
*
* @package AlibabaCloud\Client\Credentials
*
* @codeCoverageIgnore
*/
interface CredentialsInterface
{
/**
* @return string
*/
public function __toString();
}

View File

@ -0,0 +1,50 @@
<?php
namespace AlibabaCloud\Client\Credentials;
use AlibabaCloud\Client\Filter\CredentialFilter;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Use the RAM role of an ECS instance to complete the authentication.
*
* @package AlibabaCloud\Client\Credentials
*/
class EcsRamRoleCredential implements CredentialsInterface
{
/**
* @var string
*/
private $roleName;
/**
* Class constructor.
*
* @param string $roleName
*
* @throws ClientException
*/
public function __construct($roleName)
{
CredentialFilter::roleName($roleName);
$this->roleName = $roleName;
}
/**
* @return string
*/
public function getRoleName()
{
return $this->roleName;
}
/**
* @return string
*/
public function __toString()
{
return "roleName#$this->roleName";
}
}

View File

@ -0,0 +1,181 @@
<?php
namespace AlibabaCloud\Client\Credentials\Ini;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Clients\Client;
use AlibabaCloud\Client\Clients\AccessKeyClient;
use AlibabaCloud\Client\Clients\RamRoleArnClient;
use AlibabaCloud\Client\Clients\RsaKeyPairClient;
use AlibabaCloud\Client\Clients\EcsRamRoleClient;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Clients\BearerTokenClient;
/**
* Trait CreateTrait
*
* @package AlibabaCloud\Client\Credentials\Ini
*
* @mixin IniCredential
*/
trait CreateTrait
{
/**
* @param string $clientName
* @param array $credential
*
* @return Client|bool
* @throws ClientException
*/
protected function createClient($clientName, array $credential)
{
if (!isset($credential['enable']) || !$credential['enable']) {
return false;
}
if (!isset($credential['type'])) {
$this->missingRequired('type', $clientName);
}
return $this->createClientByType($clientName, $credential)->name($clientName);
}
/**
* @param string $clientName
* @param array $credential
*
* @return AccessKeyClient|BearerTokenClient|EcsRamRoleClient|RamRoleArnClient|RsaKeyPairClient
* @throws ClientException
*/
private function createClientByType($clientName, array $credential)
{
switch (\strtolower($credential['type'])) {
case 'access_key':
return $this->accessKeyClient($clientName, $credential);
case 'ecs_ram_role':
return $this->ecsRamRoleClient($clientName, $credential);
case 'ram_role_arn':
return $this->ramRoleArnClient($clientName, $credential);
case 'bearer_token':
return $this->bearerTokenClient($clientName, $credential);
case 'rsa_key_pair':
return $this->rsaKeyPairClient($clientName, $credential);
default:
throw new ClientException(
"Invalid type '{$credential['type']}' for '$clientName' in {$this->filename}",
SDK::INVALID_CREDENTIAL
);
}
}
/**
* @param array $credential
* @param string $clientName
*
* @return AccessKeyClient
* @throws ClientException
*/
private function accessKeyClient($clientName, array $credential)
{
if (!isset($credential['access_key_id'])) {
$this->missingRequired('access_key_id', $clientName);
}
if (!isset($credential['access_key_secret'])) {
$this->missingRequired('access_key_secret', $clientName);
}
return new AccessKeyClient(
$credential['access_key_id'],
$credential['access_key_secret']
);
}
/**
* @param string $clientName
* @param array $credential
*
* @return EcsRamRoleClient
* @throws ClientException
*/
private function ecsRamRoleClient($clientName, array $credential)
{
if (!isset($credential['role_name'])) {
$this->missingRequired('role_name', $clientName);
}
return new EcsRamRoleClient($credential['role_name']);
}
/**
* @param string $clientName
* @param array $credential
*
* @return RamRoleArnClient
* @throws ClientException
*/
private function ramRoleArnClient($clientName, array $credential)
{
if (!isset($credential['access_key_id'])) {
$this->missingRequired('access_key_id', $clientName);
}
if (!isset($credential['access_key_secret'])) {
$this->missingRequired('access_key_secret', $clientName);
}
if (!isset($credential['role_arn'])) {
$this->missingRequired('role_arn', $clientName);
}
if (!isset($credential['role_session_name'])) {
$this->missingRequired('role_session_name', $clientName);
}
return new RamRoleArnClient(
$credential['access_key_id'],
$credential['access_key_secret'],
$credential['role_arn'],
$credential['role_session_name']
);
}
/**
* @param string $clientName
* @param array $credential
*
* @return BearerTokenClient
* @throws ClientException
*/
private function bearerTokenClient($clientName, array $credential)
{
if (!isset($credential['bearer_token'])) {
$this->missingRequired('bearer_token', $clientName);
}
return new BearerTokenClient($credential['bearer_token']);
}
/**
* @param array $credential
* @param string $clientName
*
* @return RsaKeyPairClient
* @throws ClientException
*/
private function rsaKeyPairClient($clientName, array $credential)
{
if (!isset($credential['public_key_id'])) {
$this->missingRequired('public_key_id', $clientName);
}
if (!isset($credential['private_key_file'])) {
$this->missingRequired('private_key_file', $clientName);
}
return new RsaKeyPairClient(
$credential['public_key_id'],
$credential['private_key_file']
);
}
}

View File

@ -0,0 +1,209 @@
<?php
namespace AlibabaCloud\Client\Credentials\Ini;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Clients\Client;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class IniCredential
*
* @package AlibabaCloud\Client\Credentials\Ini
*/
class IniCredential
{
use CreateTrait;
use OptionsTrait;
/**
* @var array
*/
private static $hasLoaded;
/**
* @var string
*/
protected $filename;
/**
* IniCredential constructor.
*
* @param string $filename
*/
public function __construct($filename = '')
{
$this->filename = $filename ?: $this->getDefaultFile();
}
/**
* Get the default credential file.
*
* @return string
*/
public function getDefaultFile()
{
return self::getHomeDirectory() . DIRECTORY_SEPARATOR . '.alibabacloud' . DIRECTORY_SEPARATOR . 'credentials';
}
/**
* Gets the environment's HOME directory.
*
* @return null|string
*/
private static function getHomeDirectory()
{
if (getenv('HOME')) {
return getenv('HOME');
}
return (getenv('HOMEDRIVE') && getenv('HOMEPATH'))
? getenv('HOMEDRIVE') . getenv('HOMEPATH')
: null;
}
/**
* Clear credential cache.
*
* @return void
*/
public static function forgetLoadedCredentialsFile()
{
self::$hasLoaded = [];
}
/**
* Get the credential file.
*
* @return string
*/
public function getFilename()
{
return $this->filename;
}
/**
* @param array $array
* @param string $key
*
* @return bool
*/
protected static function isNotEmpty(array $array, $key)
{
return isset($array[$key]) && !empty($array[$key]);
}
/**
* @param string $key
* @param string $clientName
*
* @throws ClientException
*/
public function missingRequired($key, $clientName)
{
throw new ClientException(
"Missing required '$key' option for '$clientName' in " . $this->getFilename(),
SDK::INVALID_CREDENTIAL
);
}
/**
* @return array|mixed
* @throws ClientException
*/
public function load()
{
// If it has been loaded, assign the client directly.
if (isset(self::$hasLoaded[$this->filename])) {
/**
* @var $client Client
*/
foreach (self::$hasLoaded[$this->filename] as $projectName => $client) {
$client->name($projectName);
}
return self::$hasLoaded[$this->filename];
}
return $this->loadFile();
}
/**
* Exceptions will be thrown if the file is unreadable and not the default file.
*
* @return array|mixed
* @throws ClientException
*/
private function loadFile()
{
if (!\AlibabaCloud\Client\inOpenBasedir($this->filename)) {
return [];
}
if (!\is_readable($this->filename) || !\is_file($this->filename)) {
if ($this->filename === $this->getDefaultFile()) {
// @codeCoverageIgnoreStart
return [];
// @codeCoverageIgnoreEnd
}
throw new ClientException(
'Credential file is not readable: ' . $this->getFilename(),
SDK::INVALID_CREDENTIAL
);
}
return $this->parseFile();
}
/**
* Decode the ini file into an array.
*
* @return array|mixed
* @throws ClientException
*/
private function parseFile()
{
try {
$file = \parse_ini_file($this->filename, true);
if (\is_array($file) && $file !== []) {
return $this->initClients($file);
}
throw new ClientException(
'Format error: ' . $this->getFilename(),
SDK::INVALID_CREDENTIAL
);
} catch (\Exception $e) {
throw new ClientException(
$e->getMessage(),
SDK::INVALID_CREDENTIAL,
$e
);
}
}
/**
* Initialize clients.
*
* @param array $array
*
* @return array|mixed
* @throws ClientException
*/
private function initClients($array)
{
foreach (\array_change_key_case($array) as $clientName => $configures) {
$configures = \array_change_key_case($configures);
$clientInstance = $this->createClient($clientName, $configures);
if ($clientInstance instanceof Client) {
self::$hasLoaded[$this->filename][$clientName] = $clientInstance;
self::setClientAttributes($configures, $clientInstance);
self::setCert($configures, $clientInstance);
self::setProxy($configures, $clientInstance);
}
}
return isset(self::$hasLoaded[$this->filename])
? self::$hasLoaded[$this->filename]
: [];
}
}

View File

@ -0,0 +1,111 @@
<?php
namespace AlibabaCloud\Client\Credentials\Ini;
use AlibabaCloud\Client\Clients\Client;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Trait OptionsTrait
*
* @package AlibabaCloud\Client\Credentials\Ini
*
* @mixin IniCredential
*/
trait OptionsTrait
{
/**
* @param array $configures
* @param Client $client
*
* @throws ClientException
*/
private static function setClientAttributes($configures, Client $client)
{
if (self::isNotEmpty($configures, 'region_id')) {
$client->regionId($configures['region_id']);
}
if (isset($configures['debug'])) {
$client->options(
[
'debug' => (bool)$configures['debug'],
]
);
}
if (self::isNotEmpty($configures, 'timeout')) {
$client->options(
[
'timeout' => $configures['timeout'],
]
);
}
if (self::isNotEmpty($configures, 'connect_timeout')) {
$client->options(
[
'connect_timeout' => $configures['connect_timeout'],
]
);
}
}
/**
* @param array $configures
* @param Client $client
*/
private static function setProxy($configures, Client $client)
{
if (self::isNotEmpty($configures, 'proxy')) {
$client->options(
[
'proxy' => $configures['proxy'],
]
);
}
$proxy = [];
if (self::isNotEmpty($configures, 'proxy_http')) {
$proxy['http'] = $configures['proxy_http'];
}
if (self::isNotEmpty($configures, 'proxy_https')) {
$proxy['https'] = $configures['proxy_https'];
}
if (self::isNotEmpty($configures, 'proxy_no')) {
$proxy['no'] = \explode(',', $configures['proxy_no']);
}
if ($proxy !== []) {
$client->options(
[
'proxy' => $proxy,
]
);
}
}
/**
* @param array $configures
* @param Client $client
*/
private static function setCert($configures, Client $client)
{
if (self::isNotEmpty($configures, 'cert_file') && !self::isNotEmpty($configures, 'cert_password')) {
$client->options(
[
'cert' => $configures['cert_file'],
]
);
}
if (self::isNotEmpty($configures, 'cert_file') && self::isNotEmpty($configures, 'cert_password')) {
$client->options(
[
'cert' => [
$configures['cert_file'],
$configures['cert_password'],
],
]
);
}
}
}

View File

@ -0,0 +1,170 @@
<?php
namespace AlibabaCloud\Client\Credentials\Providers;
use Closure;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class CredentialsProvider
*
* @package AlibabaCloud\Client\Credentials\Providers
*/
class CredentialsProvider
{
/**
* @var array
*/
private static $customChains;
/**
* @throws ClientException
*/
public static function chain()
{
$providers = func_get_args();
if (empty($providers)) {
throw new ClientException('No providers in chain', SDK::INVALID_ARGUMENT);
}
foreach ($providers as $provider) {
if (!$provider instanceof Closure) {
throw new ClientException('Providers must all be Closures', SDK::INVALID_ARGUMENT);
}
}
self::$customChains = $providers;
}
/**
* Forget the custom providers chain.
*/
public static function flush()
{
self::$customChains = [];
}
/**
* @return bool
*/
public static function hasCustomChain()
{
return (bool)self::$customChains;
}
/**
* @param string $clientName
*
* @throws ClientException
*/
public static function customProvider($clientName)
{
foreach (self::$customChains as $provider) {
$provider();
if (AlibabaCloud::has($clientName)) {
break;
}
}
}
/**
* @param string $clientName
*
* @throws ClientException
*/
public static function defaultProvider($clientName)
{
$providers = [
self::env(),
self::ini(),
self::instance(),
];
foreach ($providers as $provider) {
$provider();
if (AlibabaCloud::has($clientName)) {
break;
}
}
}
/**
* @return Closure
*/
public static function env()
{
return static function () {
$accessKeyId = \AlibabaCloud\Client\envNotEmpty('ALIBABA_CLOUD_ACCESS_KEY_ID');
$accessKeySecret = \AlibabaCloud\Client\envNotEmpty('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
if ($accessKeyId && $accessKeySecret) {
AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)->asDefaultClient();
}
};
}
/**
* @return Closure
*/
public static function ini()
{
return static function () {
$ini = \AlibabaCloud\Client\envNotEmpty('ALIBABA_CLOUD_CREDENTIALS_FILE');
if ($ini) {
AlibabaCloud::load($ini);
} else {
// @codeCoverageIgnoreStart
AlibabaCloud::load();
// @codeCoverageIgnoreEnd
}
self::compatibleWithGlobal();
};
}
/**
* @codeCoverageIgnore
*
* Compatible with global
*
* @throws ClientException
*/
private static function compatibleWithGlobal()
{
if (AlibabaCloud::has('global') && !AlibabaCloud::has(self::getDefaultName())) {
AlibabaCloud::get('global')->name(self::getDefaultName());
}
}
/**
* @return array|false|string
* @throws ClientException
*/
public static function getDefaultName()
{
$name = \AlibabaCloud\Client\envNotEmpty('ALIBABA_CLOUD_PROFILE');
if ($name) {
return $name;
}
return 'default';
}
/**
* @return Closure
*/
public static function instance()
{
return static function () {
$instance = \AlibabaCloud\Client\envNotEmpty('ALIBABA_CLOUD_ECS_METADATA');
if ($instance) {
AlibabaCloud::ecsRamRoleClient($instance)->asDefaultClient();
}
};
}
}

View File

@ -0,0 +1,128 @@
<?php
namespace AlibabaCloud\Client\Credentials\Providers;
use Exception;
use AlibabaCloud\Client\Support\Stringy;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Result\Result;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Exception\GuzzleException;
use AlibabaCloud\Client\Request\RpcRequest;
use AlibabaCloud\Client\Credentials\StsCredential;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Client\Credentials\EcsRamRoleCredential;
/**
* Class EcsRamRoleProvider
*
* @package AlibabaCloud\Client\Credentials\Providers
*/
class EcsRamRoleProvider extends Provider
{
/**
* Expiration time slot for temporary security credentials.
*
* @var int
*/
protected $expirationSlot = 10;
/**
* @var string
*/
private $uri = 'http://100.100.100.200/latest/meta-data/ram/security-credentials/';
/**
* Get credential.
*
* @return StsCredential
* @throws ClientException
* @throws ServerException
*/
public function get()
{
$result = $this->getCredentialsInCache();
if ($result === null) {
$result = $this->request();
if (!isset($result['AccessKeyId'], $result['AccessKeySecret'], $result['SecurityToken'])) {
throw new ServerException($result, $this->error, SDK::INVALID_CREDENTIAL);
}
$this->cache($result->toArray());
}
return new StsCredential(
$result['AccessKeyId'],
$result['AccessKeySecret'],
$result['SecurityToken']
);
}
/**
* Get credentials by request.
*
* @return Result
* @throws ClientException
* @throws ServerException
*/
public function request()
{
$result = $this->getResponse();
if ($result->getStatusCode() === 404) {
$message = 'The role was not found in the instance';
throw new ClientException($message, SDK::INVALID_CREDENTIAL);
}
if (!$result->isSuccess()) {
$message = 'Error retrieving credentials from result';
throw new ServerException($result, $message, SDK::INVALID_CREDENTIAL);
}
return $result;
}
/**
* Get data from meta.
*
* @return mixed|ResponseInterface
* @throws ClientException
* @throws Exception
*/
public function getResponse()
{
/**
* @var EcsRamRoleCredential $credential
*/
$credential = $this->client->getCredential();
$url = $this->uri . $credential->getRoleName();
$options = [
'http_errors' => false,
'timeout' => 1,
'connect_timeout' => 1,
'debug' => $this->client->isDebug(),
];
try {
return RpcRequest::createClient()->request('GET', $url, $options);
} catch (GuzzleException $exception) {
if (Stringy::contains($exception->getMessage(), 'timed')) {
$message = 'Timeout or instance does not belong to Alibaba Cloud';
} else {
$message = $exception->getMessage();
}
throw new ClientException(
$message,
SDK::SERVER_UNREACHABLE,
$exception
);
}
}
}

View File

@ -0,0 +1,88 @@
<?php
namespace AlibabaCloud\Client\Credentials\Providers;
use AlibabaCloud\Client\Clients\Client;
/**
* Class Provider
*
* @package AlibabaCloud\Client\Credentials\Providers
*/
class Provider
{
/**
* For TSC Duration Seconds
*/
const DURATION_SECONDS = 3600;
/**
* @var array
*/
protected static $credentialsCache = [];
/**
* Expiration time slot for temporary security credentials.
*
* @var int
*/
protected $expirationSlot = 180;
/**
* @var Client
*/
protected $client;
/**
* @var string
*/
protected $error = 'Result contains no credentials';
/**
* CredentialTrait constructor.
*
* @param Client $client
*/
public function __construct(Client $client)
{
$this->client = $client;
}
/**
* Get the credentials from the cache in the validity period.
*
* @return array|null
*/
public function getCredentialsInCache()
{
if (isset(self::$credentialsCache[$this->key()])) {
$result = self::$credentialsCache[$this->key()];
if (\strtotime($result['Expiration']) - \time() >= $this->expirationSlot) {
return $result;
}
unset(self::$credentialsCache[$this->key()]);
}
return null;
}
/**
* Get the toString of the credentials as the key.
*
* @return string
*/
protected function key()
{
return (string)$this->client->getCredential();
}
/**
* Cache credentials.
*
* @param array $credential
*/
protected function cache(array $credential)
{
self::$credentialsCache[$this->key()] = $credential;
}
}

View File

@ -0,0 +1,84 @@
<?php
namespace AlibabaCloud\Client\Credentials\Providers;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Result\Result;
use AlibabaCloud\Client\Request\Request;
use AlibabaCloud\Client\Credentials\StsCredential;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Client\Credentials\Requests\AssumeRole;
/**
* Class RamRoleArnProvider
*
* @package AlibabaCloud\Client\Credentials\Providers
*/
class RamRoleArnProvider extends Provider
{
/**
* Get credential.
*
*
* @param int $timeout
* @param int $connectTimeout
*
* @return StsCredential
* @throws ClientException
* @throws ServerException
*/
public function get($timeout = Request::TIMEOUT, $connectTimeout = Request::CONNECT_TIMEOUT)
{
$credential = $this->getCredentialsInCache();
if (null === $credential) {
$result = $this->request($timeout, $connectTimeout);
if (!isset($result['Credentials']['AccessKeyId'],
$result['Credentials']['AccessKeySecret'],
$result['Credentials']['SecurityToken'])) {
throw new ServerException($result, $this->error, SDK::INVALID_CREDENTIAL);
}
$credential = $result['Credentials'];
$this->cache($credential);
}
return new StsCredential(
$credential['AccessKeyId'],
$credential['AccessKeySecret'],
$credential['SecurityToken']
);
}
/**
* Get credentials by request.
*
* @param $timeout
* @param $connectTimeout
*
* @return Result
* @throws ClientException
* @throws ServerException
*/
private function request($timeout, $connectTimeout)
{
$clientName = __CLASS__ . \uniqid('ak', true);
$credential = $this->client->getCredential();
AlibabaCloud::accessKeyClient(
$credential->getAccessKeyId(),
$credential->getAccessKeySecret()
)->name($clientName);
return (new AssumeRole($credential))
->client($clientName)
->timeout($timeout)
->connectTimeout($connectTimeout)
->debug($this->client->isDebug())
->request();
}
}

View File

@ -0,0 +1,86 @@
<?php
namespace AlibabaCloud\Client\Credentials\Providers;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Result\Result;
use AlibabaCloud\Client\Request\Request;
use AlibabaCloud\Client\Credentials\StsCredential;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Client\Credentials\AccessKeyCredential;
use AlibabaCloud\Client\Signature\ShaHmac256WithRsaSignature;
use AlibabaCloud\Client\Credentials\Requests\GenerateSessionAccessKey;
/**
* Class RsaKeyPairProvider
*
* @package AlibabaCloud\Client\Credentials\Providers
*/
class RsaKeyPairProvider extends Provider
{
/**
* Get credential.
*
* @param int $timeout
* @param int $connectTimeout
*
* @return StsCredential
* @throws ClientException
* @throws ServerException
*/
public function get($timeout = Request::TIMEOUT, $connectTimeout = Request::CONNECT_TIMEOUT)
{
$credential = $this->getCredentialsInCache();
if ($credential === null) {
$result = $this->request($timeout, $connectTimeout);
if (!isset($result['SessionAccessKey']['SessionAccessKeyId'],
$result['SessionAccessKey']['SessionAccessKeySecret'])) {
throw new ServerException($result, $this->error, SDK::INVALID_CREDENTIAL);
}
$credential = $result['SessionAccessKey'];
$this->cache($credential);
}
return new StsCredential(
$credential['SessionAccessKeyId'],
$credential['SessionAccessKeySecret']
);
}
/**
* Get credentials by request.
*
* @param $timeout
* @param $connectTimeout
*
* @return Result
* @throws ClientException
* @throws ServerException
*/
private function request($timeout, $connectTimeout)
{
$clientName = __CLASS__ . \uniqid('rsa', true);
$credential = $this->client->getCredential();
AlibabaCloud::client(
new AccessKeyCredential(
$credential->getPublicKeyId(),
$credential->getPrivateKey()
),
new ShaHmac256WithRsaSignature()
)->name($clientName);
return (new GenerateSessionAccessKey($credential->getPublicKeyId()))
->client($clientName)
->timeout($timeout)
->connectTimeout($connectTimeout)
->debug($this->client->isDebug())
->request();
}
}

View File

@ -0,0 +1,110 @@
<?php
namespace AlibabaCloud\Client\Credentials;
use AlibabaCloud\Client\Filter\CredentialFilter;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Use the AssumeRole of the RAM account to complete the authentication.
*
* @package AlibabaCloud\Client\Credentials
*/
class RamRoleArnCredential implements CredentialsInterface
{
/**
* @var string
*/
private $accessKeyId;
/**
* @var string
*/
private $accessKeySecret;
/**
* @var string
*/
private $roleArn;
/**
* @var string
*/
private $roleSessionName;
/**
* @var string
*/
private $policy;
/**
* Class constructor.
*
* @param string $accessKeyId
* @param string $accessKeySecret
* @param string $roleArn
* @param string $roleSessionName
* @param string|array $policy
*
* @throws ClientException
*/
public function __construct($accessKeyId, $accessKeySecret, $roleArn, $roleSessionName, $policy = '')
{
CredentialFilter::AccessKey($accessKeyId, $accessKeySecret);
$this->accessKeyId = $accessKeyId;
$this->accessKeySecret = $accessKeySecret;
$this->roleArn = $roleArn;
$this->roleSessionName = $roleSessionName;
$this->policy = $policy;
}
/**
* @return string
*/
public function getAccessKeyId()
{
return $this->accessKeyId;
}
/**
* @return string
*/
public function getAccessKeySecret()
{
return $this->accessKeySecret;
}
/**
* @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";
}
}

View File

@ -0,0 +1,47 @@
<?php
namespace AlibabaCloud\Client\Credentials\Requests;
use AlibabaCloud\Client\Request\RpcRequest;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Credentials\Providers\Provider;
use AlibabaCloud\Client\Credentials\RamRoleArnCredential;
/**
* Retrieving assume role credentials.
*
* @package AlibabaCloud\Client\Credentials\Requests
*/
class AssumeRole extends RpcRequest
{
/**
* AssumeRole constructor.
*
* @param RamRoleArnCredential $arnCredential
*
* @throws ClientException
*/
public function __construct(RamRoleArnCredential $arnCredential)
{
parent::__construct();
$this->product('Sts');
$this->version('2015-04-01');
$this->action('AssumeRole');
$this->host('sts.aliyuncs.com');
$this->scheme('https');
$this->regionId('cn-hangzhou');
$this->options['verify'] = false;
$this->options['query']['RoleArn'] = $arnCredential->getRoleArn();
$this->options['query']['RoleSessionName'] = $arnCredential->getRoleSessionName();
$this->options['query']['DurationSeconds'] = Provider::DURATION_SECONDS;
if ($arnCredential->getPolicy()) {
if (is_array($arnCredential->getPolicy())) {
$this->options['query']['Policy'] = json_encode($arnCredential->getPolicy());
}
if (is_string($arnCredential->getPolicy())) {
$this->options['query']['Policy'] = $arnCredential->getPolicy();
}
}
}
}

View File

@ -0,0 +1,37 @@
<?php
namespace AlibabaCloud\Client\Credentials\Requests;
use AlibabaCloud\Client\Request\RpcRequest;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Credentials\Providers\Provider;
/**
* Use the RSA key pair to complete the authentication (supported only on Japanese site)
*
* @package AlibabaCloud\Client\Credentials\Requests
*/
class GenerateSessionAccessKey extends RpcRequest
{
/**
* GenerateSessionAccessKey constructor.
*
* @param string $publicKeyId
*
* @throws ClientException
*/
public function __construct($publicKeyId)
{
parent::__construct();
$this->product('Sts');
$this->version('2015-04-01');
$this->action('GenerateSessionAccessKey');
$this->host('sts.ap-northeast-1.aliyuncs.com');
$this->scheme('https');
$this->regionId('cn-hangzhou');
$this->options['verify'] = false;
$this->options['query']['PublicKeyId'] = $publicKeyId;
$this->options['query']['DurationSeconds'] = Provider::DURATION_SECONDS;
}
}

View File

@ -0,0 +1,75 @@
<?php
namespace AlibabaCloud\Client\Credentials;
use Exception;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Filter\CredentialFilter;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Use the RSA key pair to complete the authentication (supported only on Japanese site)
*
* @package AlibabaCloud\Client\Credentials
*/
class RsaKeyPairCredential implements CredentialsInterface
{
/**
* @var string
*/
private $publicKeyId;
/**
* @var string
*/
private $privateKey;
/**
* RsaKeyPairCredential constructor.
*
* @param string $publicKeyId
* @param string $privateKeyFile
*
* @throws ClientException
*/
public function __construct($publicKeyId, $privateKeyFile)
{
CredentialFilter::publicKeyId($publicKeyId);
CredentialFilter::privateKeyFile($privateKeyFile);
$this->publicKeyId = $publicKeyId;
try {
$this->privateKey = file_get_contents($privateKeyFile);
} catch (Exception $exception) {
throw new ClientException(
$exception->getMessage(),
SDK::INVALID_CREDENTIAL
);
}
}
/**
* @return mixed
*/
public function getPrivateKey()
{
return $this->privateKey;
}
/**
* @return string
*/
public function getPublicKeyId()
{
return $this->publicKeyId;
}
/**
* @return string
*/
public function __toString()
{
return "publicKeyId#$this->publicKeyId";
}
}

View File

@ -0,0 +1,80 @@
<?php
namespace AlibabaCloud\Client\Credentials;
use AlibabaCloud\Client\Filter\CredentialFilter;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Use the STS Token to complete the authentication.
*
* @package AlibabaCloud\Client\Credentials
*/
class StsCredential implements CredentialsInterface
{
/**
* @var string
*/
private $accessKeyId;
/**
* @var string
*/
private $accessKeySecret;
/**
* @var string
*/
private $securityToken;
/**
* StsCredential constructor.
*
* @param string $accessKeyId Access key ID
* @param string $accessKeySecret Access Key Secret
* @param string $securityToken Security Token
*
* @throws ClientException
*/
public function __construct($accessKeyId, $accessKeySecret, $securityToken = '')
{
CredentialFilter::AccessKey($accessKeyId, $accessKeySecret);
$this->accessKeyId = $accessKeyId;
$this->accessKeySecret = $accessKeySecret;
$this->securityToken = $securityToken;
}
/**
* @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";
}
}