최초 커밋
This commit is contained in:
+67
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
namespace Aws\Credentials;
|
||||
|
||||
use Aws\Exception\CredentialsException;
|
||||
use Aws\Result;
|
||||
use Aws\Sts\StsClient;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
|
||||
/**
|
||||
* Credential provider that provides credentials via assuming a role
|
||||
* More Information, see: http://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sts-2011-06-15.html#assumerole
|
||||
*/
|
||||
class AssumeRoleCredentialProvider
|
||||
{
|
||||
const ERROR_MSG = "Missing required 'AssumeRoleCredentialProvider' configuration option: ";
|
||||
|
||||
/** @var StsClient */
|
||||
private $client;
|
||||
|
||||
/** @var array */
|
||||
private $assumeRoleParams;
|
||||
|
||||
/**
|
||||
* The constructor requires following configure parameters:
|
||||
* - client: a StsClient
|
||||
* - assume_role_params: Parameters used to make assumeRole call
|
||||
*
|
||||
* @param array $config Configuration options
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function __construct(array $config = [])
|
||||
{
|
||||
if (!isset($config['assume_role_params'])) {
|
||||
throw new \InvalidArgumentException(self::ERROR_MSG . "'assume_role_params'.");
|
||||
}
|
||||
|
||||
if (!isset($config['client'])) {
|
||||
throw new \InvalidArgumentException(self::ERROR_MSG . "'client'.");
|
||||
}
|
||||
|
||||
$this->client = $config['client'];
|
||||
$this->assumeRoleParams = $config['assume_role_params'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads assume role credentials.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*/
|
||||
public function __invoke()
|
||||
{
|
||||
$client = $this->client;
|
||||
return $client->assumeRoleAsync($this->assumeRoleParams)
|
||||
->then(function (Result $result) {
|
||||
return $this->client->createCredentials(
|
||||
$result,
|
||||
CredentialSources::STS_ASSUME_ROLE
|
||||
);
|
||||
})->otherwise(function (\RuntimeException $exception) {
|
||||
throw new CredentialsException(
|
||||
"Error in retrieving assume role credentials.",
|
||||
0,
|
||||
$exception
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
Vendored
+170
@@ -0,0 +1,170 @@
|
||||
<?php
|
||||
namespace Aws\Credentials;
|
||||
|
||||
use Aws\Exception\AwsException;
|
||||
use Aws\Exception\CredentialsException;
|
||||
use Aws\Result;
|
||||
use Aws\Sts\StsClient;
|
||||
use GuzzleHttp\Promise;
|
||||
|
||||
/**
|
||||
* Credential provider that provides credentials via assuming a role with a web identity
|
||||
* More Information, see: https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sts-2011-06-15.html#assumerolewithwebidentity
|
||||
*/
|
||||
class AssumeRoleWithWebIdentityCredentialProvider
|
||||
{
|
||||
const ERROR_MSG = "Missing required 'AssumeRoleWithWebIdentityCredentialProvider' configuration option: ";
|
||||
const ENV_RETRIES = 'AWS_METADATA_SERVICE_NUM_ATTEMPTS';
|
||||
|
||||
/** @var string */
|
||||
private $tokenFile;
|
||||
|
||||
/** @var string */
|
||||
private $arn;
|
||||
|
||||
/** @var string */
|
||||
private $session;
|
||||
|
||||
/** @var StsClient */
|
||||
private $client;
|
||||
|
||||
/** @var integer */
|
||||
private $retries;
|
||||
|
||||
/** @var integer */
|
||||
private $authenticationAttempts;
|
||||
|
||||
/** @var integer */
|
||||
private $tokenFileReadAttempts;
|
||||
/** @var string */
|
||||
private $source;
|
||||
|
||||
/**
|
||||
* The constructor attempts to load config from environment variables.
|
||||
* If not set, the following config options are used:
|
||||
* - WebIdentityTokenFile: full path of token filename
|
||||
* - RoleArn: arn of role to be assumed
|
||||
* - SessionName: (optional) set by SDK if not provided
|
||||
* - source: To identify if the provider was sourced by a profile or
|
||||
* from environment definition. Default will be `sts_web_id_token`.
|
||||
*
|
||||
* @param array $config Configuration options
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function __construct(array $config = [])
|
||||
{
|
||||
if (!isset($config['RoleArn'])) {
|
||||
throw new \InvalidArgumentException(self::ERROR_MSG . "'RoleArn'.");
|
||||
}
|
||||
$this->arn = $config['RoleArn'];
|
||||
|
||||
if (!isset($config['WebIdentityTokenFile'])) {
|
||||
throw new \InvalidArgumentException(self::ERROR_MSG . "'WebIdentityTokenFile'.");
|
||||
}
|
||||
$this->tokenFile = $config['WebIdentityTokenFile'];
|
||||
|
||||
if (!preg_match("/^\w\:|^\/|^\\\/", $this->tokenFile)) {
|
||||
throw new \InvalidArgumentException("'WebIdentityTokenFile' must be an absolute path.");
|
||||
}
|
||||
|
||||
$this->retries = (int) getenv(self::ENV_RETRIES) ?: (isset($config['retries']) ? $config['retries'] : 3);
|
||||
$this->authenticationAttempts = 0;
|
||||
$this->tokenFileReadAttempts = 0;
|
||||
$this->session = $config['SessionName']
|
||||
?? 'aws-sdk-php-' . round(microtime(true) * 1000);
|
||||
$region = $config['region'] ?? 'us-east-1';
|
||||
if (isset($config['client'])) {
|
||||
$this->client = $config['client'];
|
||||
} else {
|
||||
$this->client = new StsClient([
|
||||
'credentials' => false,
|
||||
'region' => $region,
|
||||
'version' => 'latest'
|
||||
]);
|
||||
}
|
||||
|
||||
$this->source = $config['source']
|
||||
?? CredentialSources::STS_WEB_ID_TOKEN;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads assume role with web identity credentials.
|
||||
*
|
||||
* @return Promise\PromiseInterface
|
||||
*/
|
||||
public function __invoke()
|
||||
{
|
||||
return Promise\Coroutine::of(function () {
|
||||
$client = $this->client;
|
||||
$result = null;
|
||||
while ($result == null) {
|
||||
try {
|
||||
$token = @file_get_contents($this->tokenFile);
|
||||
if (false === $token) {
|
||||
clearstatcache(true, dirname($this->tokenFile) . "/" . readlink($this->tokenFile));
|
||||
clearstatcache(true, dirname($this->tokenFile) . "/" . dirname(readlink($this->tokenFile)));
|
||||
clearstatcache(true, $this->tokenFile);
|
||||
if (!@is_readable($this->tokenFile)) {
|
||||
throw new CredentialsException(
|
||||
"Unreadable tokenfile at location {$this->tokenFile}"
|
||||
);
|
||||
}
|
||||
|
||||
$token = @file_get_contents($this->tokenFile);
|
||||
}
|
||||
if (empty($token)) {
|
||||
if ($this->tokenFileReadAttempts < $this->retries) {
|
||||
sleep((int) pow(1.2, $this->tokenFileReadAttempts));
|
||||
$this->tokenFileReadAttempts++;
|
||||
continue;
|
||||
}
|
||||
throw new CredentialsException("InvalidIdentityToken from file: {$this->tokenFile}");
|
||||
}
|
||||
} catch (\Exception $exception) {
|
||||
throw new CredentialsException(
|
||||
"Error reading WebIdentityTokenFile from " . $this->tokenFile,
|
||||
0,
|
||||
$exception
|
||||
);
|
||||
}
|
||||
|
||||
$assumeParams = [
|
||||
'RoleArn' => $this->arn,
|
||||
'RoleSessionName' => $this->session,
|
||||
'WebIdentityToken' => $token
|
||||
];
|
||||
|
||||
try {
|
||||
$result = $client->assumeRoleWithWebIdentity($assumeParams);
|
||||
} catch (AwsException $e) {
|
||||
if ($e->getAwsErrorCode() == 'InvalidIdentityToken') {
|
||||
if ($this->authenticationAttempts < $this->retries) {
|
||||
sleep((int) pow(1.2, $this->authenticationAttempts));
|
||||
} else {
|
||||
throw new CredentialsException(
|
||||
"InvalidIdentityToken, retries exhausted"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
throw new CredentialsException(
|
||||
"Error assuming role from web identity credentials",
|
||||
0,
|
||||
$e
|
||||
);
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
throw new CredentialsException(
|
||||
"Error retrieving web identity credentials: " . $e->getMessage()
|
||||
. " (" . $e->getCode() . ")"
|
||||
);
|
||||
}
|
||||
$this->authenticationAttempts++;
|
||||
}
|
||||
|
||||
yield $this->client->createCredentials(
|
||||
$result,
|
||||
$this->source
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace Aws\Credentials;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class CredentialSources
|
||||
{
|
||||
const STATIC = 'static';
|
||||
const ENVIRONMENT = 'env';
|
||||
const STS_WEB_ID_TOKEN = 'sts_web_id_token';
|
||||
const ENVIRONMENT_STS_WEB_ID_TOKEN = 'env_sts_web_id_token';
|
||||
const PROFILE_STS_WEB_ID_TOKEN = 'profile_sts_web_id_token';
|
||||
const STS_ASSUME_ROLE = 'sts_assume_role';
|
||||
const PROFILE = 'profile';
|
||||
const IMDS = 'instance_profile_provider';
|
||||
const ECS = 'ecs';
|
||||
const PROFILE_SSO = 'profile_sso';
|
||||
const PROFILE_SSO_LEGACY = 'profile_sso_legacy';
|
||||
const PROFILE_PROCESS = 'profile_process';
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
namespace Aws\Credentials;
|
||||
|
||||
use Aws\Identity\AwsCredentialIdentity;
|
||||
|
||||
/**
|
||||
* Basic implementation of the AWS Credentials interface that allows callers to
|
||||
* pass in the AWS Access Key and AWS Secret Access Key in the constructor.
|
||||
*/
|
||||
class Credentials extends AwsCredentialIdentity implements
|
||||
CredentialsInterface,
|
||||
\Serializable
|
||||
{
|
||||
private $key;
|
||||
private $secret;
|
||||
private $token;
|
||||
private $expires;
|
||||
private $accountId;
|
||||
private $source;
|
||||
|
||||
/**
|
||||
* Constructs a new BasicAWSCredentials object, with the specified AWS
|
||||
* access key and AWS secret key
|
||||
*
|
||||
* @param string $key AWS access key ID
|
||||
* @param string $secret AWS secret access key
|
||||
* @param string $token Security token to use
|
||||
* @param int $expires UNIX timestamp for when credentials expire
|
||||
*/
|
||||
public function __construct(
|
||||
$key,
|
||||
$secret,
|
||||
$token = null,
|
||||
$expires = null,
|
||||
$accountId = null,
|
||||
$source = CredentialSources::STATIC
|
||||
)
|
||||
{
|
||||
$this->key = trim((string) $key);
|
||||
$this->secret = trim((string) $secret);
|
||||
$this->token = $token;
|
||||
$this->expires = $expires;
|
||||
$this->accountId = $accountId;
|
||||
$this->source = $source ?? CredentialSources::STATIC;
|
||||
}
|
||||
|
||||
public static function __set_state(array $state)
|
||||
{
|
||||
return new self(
|
||||
$state['key'],
|
||||
$state['secret'],
|
||||
$state['token'],
|
||||
$state['expires'],
|
||||
$state['accountId'],
|
||||
$state['source'] ?? null
|
||||
);
|
||||
}
|
||||
|
||||
public function getAccessKeyId()
|
||||
{
|
||||
return $this->key;
|
||||
}
|
||||
|
||||
public function getSecretKey()
|
||||
{
|
||||
return $this->secret;
|
||||
}
|
||||
|
||||
public function getSecurityToken()
|
||||
{
|
||||
return $this->token;
|
||||
}
|
||||
|
||||
public function getExpiration()
|
||||
{
|
||||
return $this->expires;
|
||||
}
|
||||
|
||||
public function isExpired()
|
||||
{
|
||||
return $this->expires !== null && time() >= $this->expires;
|
||||
}
|
||||
|
||||
public function getAccountId()
|
||||
{
|
||||
return $this->accountId;
|
||||
}
|
||||
|
||||
public function getSource()
|
||||
{
|
||||
return $this->source;
|
||||
}
|
||||
|
||||
public function toArray()
|
||||
{
|
||||
return [
|
||||
'key' => $this->key,
|
||||
'secret' => $this->secret,
|
||||
'token' => $this->token,
|
||||
'expires' => $this->expires,
|
||||
'accountId' => $this->accountId,
|
||||
'source' => $this->source
|
||||
];
|
||||
}
|
||||
|
||||
public function serialize()
|
||||
{
|
||||
return json_encode($this->__serialize());
|
||||
}
|
||||
|
||||
public function unserialize($serialized)
|
||||
{
|
||||
$data = json_decode($serialized, true);
|
||||
|
||||
$this->__unserialize($data);
|
||||
}
|
||||
|
||||
public function __serialize()
|
||||
{
|
||||
return $this->toArray();
|
||||
}
|
||||
|
||||
public function __unserialize($data)
|
||||
{
|
||||
$this->key = $data['key'];
|
||||
$this->secret = $data['secret'];
|
||||
$this->token = $data['token'];
|
||||
$this->expires = $data['expires'];
|
||||
$this->accountId = $data['accountId'] ?? null;
|
||||
$this->source = $data['source'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal-only. Used when IMDS is unreachable
|
||||
* or returns expires credentials.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public function extendExpiration() {
|
||||
$extension = mt_rand(5, 10);
|
||||
$this->expires = time() + $extension * 60;
|
||||
|
||||
$message = <<<EOT
|
||||
Attempting credential expiration extension due to a credential service
|
||||
availability issue. A refresh of these credentials will be attempted again
|
||||
after {$extension} minutes.\n
|
||||
EOT;
|
||||
trigger_error($message, E_USER_WARNING);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
namespace Aws\Credentials;
|
||||
|
||||
/**
|
||||
* Provides access to the AWS credentials used for accessing AWS services: AWS
|
||||
* access key ID, secret access key, and security token. These credentials are
|
||||
* used to securely sign requests to AWS services.
|
||||
*/
|
||||
interface CredentialsInterface
|
||||
{
|
||||
/**
|
||||
* Returns the AWS access key ID for this credentials object.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getAccessKeyId();
|
||||
|
||||
/**
|
||||
* Returns the AWS secret access key for this credentials object.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getSecretKey();
|
||||
|
||||
/**
|
||||
* Get the associated security token if available
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getSecurityToken();
|
||||
|
||||
/**
|
||||
* Get the UNIX timestamp in which the credentials will expire
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function getExpiration();
|
||||
|
||||
/**
|
||||
* Check if the credentials are expired
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isExpired();
|
||||
|
||||
/**
|
||||
* Converts the credentials to an associative array.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function toArray();
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace Aws\Credentials;
|
||||
|
||||
final class CredentialsUtils
|
||||
{
|
||||
/**
|
||||
* Determines whether a given host
|
||||
* is a loopback address.
|
||||
*
|
||||
* @param $host
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function isLoopBackAddress($host): bool
|
||||
{
|
||||
if (!filter_var($host, FILTER_VALIDATE_IP)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
|
||||
if ($host === '::1') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$loopbackStart = ip2long('127.0.0.0');
|
||||
$loopbackEnd = ip2long('127.255.255.255');
|
||||
$ipLong = ip2long($host);
|
||||
|
||||
return ($ipLong >= $loopbackStart && $ipLong <= $loopbackEnd);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
<?php
|
||||
namespace Aws\Credentials;
|
||||
|
||||
use Aws\Arn\Arn;
|
||||
use Aws\Exception\CredentialsException;
|
||||
use GuzzleHttp\Exception\ConnectException;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
use GuzzleHttp\Psr7\Request;
|
||||
use GuzzleHttp\Promise;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Credential provider that fetches container credentials with GET request.
|
||||
* container environment variables are used in constructing request URI.
|
||||
*/
|
||||
class EcsCredentialProvider
|
||||
{
|
||||
const SERVER_URI = 'http://169.254.170.2';
|
||||
const ENV_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI";
|
||||
const ENV_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI";
|
||||
const ENV_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN";
|
||||
const ENV_AUTH_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE";
|
||||
const ENV_TIMEOUT = 'AWS_METADATA_SERVICE_TIMEOUT';
|
||||
const EKS_SERVER_HOST_IPV4 = '169.254.170.23';
|
||||
const EKS_SERVER_HOST_IPV6 = 'fd00:ec2::23';
|
||||
const ENV_RETRIES = 'AWS_METADATA_SERVICE_NUM_ATTEMPTS';
|
||||
|
||||
const DEFAULT_ENV_TIMEOUT = 1.0;
|
||||
const DEFAULT_ENV_RETRIES = 3;
|
||||
|
||||
/** @var callable */
|
||||
private $client;
|
||||
|
||||
/** @var float|mixed */
|
||||
private $timeout;
|
||||
|
||||
/** @var int */
|
||||
private $retries;
|
||||
|
||||
/** @var int */
|
||||
private $attempts;
|
||||
|
||||
/**
|
||||
* The constructor accepts following options:
|
||||
* - timeout: (optional) Connection timeout, in seconds, default 1.0
|
||||
* - retries: Optional number of retries to be attempted, default 3.
|
||||
* - client: An EcsClient to make request from
|
||||
*
|
||||
* @param array $config Configuration options
|
||||
*/
|
||||
public function __construct(array $config = [])
|
||||
{
|
||||
$this->timeout = (float) isset($config['timeout'])
|
||||
? $config['timeout']
|
||||
: (getenv(self::ENV_TIMEOUT) ?: self::DEFAULT_ENV_TIMEOUT);
|
||||
$this->retries = (int) isset($config['retries'])
|
||||
? $config['retries']
|
||||
: ((int) getenv(self::ENV_RETRIES) ?: self::DEFAULT_ENV_RETRIES);
|
||||
|
||||
$this->client = $config['client'] ?? \Aws\default_http_handler();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load container credentials.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function __invoke()
|
||||
{
|
||||
$this->attempts = 0;
|
||||
$uri = $this->getEcsUri();
|
||||
if ($this->isCompatibleUri($uri)) {
|
||||
return Promise\Coroutine::of(function () {
|
||||
$client = $this->client;
|
||||
$request = new Request('GET', $this->getEcsUri());
|
||||
$headers = $this->getHeadersForAuthToken();
|
||||
$credentials = null;
|
||||
while ($credentials === null) {
|
||||
$credentials = (yield $client(
|
||||
$request,
|
||||
[
|
||||
'timeout' => $this->timeout,
|
||||
'proxy' => '',
|
||||
'headers' => $headers,
|
||||
]
|
||||
)->then(function (ResponseInterface $response) {
|
||||
$result = $this->decodeResult((string)$response->getBody());
|
||||
if (!isset($result['AccountId']) && isset($result['RoleArn'])) {
|
||||
try {
|
||||
$parsedArn = new Arn($result['RoleArn']);
|
||||
$result['AccountId'] = $parsedArn->getAccountId();
|
||||
} catch (\Exception $e) {
|
||||
// AccountId will be null
|
||||
}
|
||||
}
|
||||
|
||||
return new Credentials(
|
||||
$result['AccessKeyId'],
|
||||
$result['SecretAccessKey'],
|
||||
$result['Token'],
|
||||
strtotime($result['Expiration']),
|
||||
$result['AccountId'] ?? null,
|
||||
CredentialSources::ECS
|
||||
);
|
||||
})->otherwise(function ($reason) {
|
||||
$reason = is_array($reason) ? $reason['exception'] : $reason;
|
||||
|
||||
$isRetryable = $reason instanceof ConnectException;
|
||||
if ($isRetryable && ($this->attempts < $this->retries)) {
|
||||
sleep((int)pow(1.2, $this->attempts));
|
||||
} else {
|
||||
$msg = $reason->getMessage();
|
||||
throw new CredentialsException(
|
||||
sprintf('Error retrieving credentials from container metadata after attempt %d/%d (%s)', $this->attempts, $this->retries, $msg)
|
||||
);
|
||||
}
|
||||
}));
|
||||
$this->attempts++;
|
||||
}
|
||||
|
||||
yield $credentials;
|
||||
});
|
||||
}
|
||||
|
||||
throw new CredentialsException("Uri '{$uri}' contains an unsupported host.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of attempts that have been done.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getAttempts(): int
|
||||
{
|
||||
return $this->attempts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves authorization token.
|
||||
*
|
||||
* @return array|false|string
|
||||
*/
|
||||
private function getEcsAuthToken()
|
||||
{
|
||||
if (!empty($path = getenv(self::ENV_AUTH_TOKEN_FILE))) {
|
||||
$token = @file_get_contents($path);
|
||||
if (false === $token) {
|
||||
clearstatcache(true, dirname($path) . DIRECTORY_SEPARATOR . @readlink($path));
|
||||
clearstatcache(true, dirname($path) . DIRECTORY_SEPARATOR . dirname(@readlink($path)));
|
||||
clearstatcache(true, $path);
|
||||
}
|
||||
|
||||
if (!is_readable($path)) {
|
||||
throw new CredentialsException("Failed to read authorization token from '{$path}': no such file or directory.");
|
||||
}
|
||||
|
||||
$token = @file_get_contents($path);
|
||||
|
||||
if (empty($token)) {
|
||||
throw new CredentialsException("Invalid authorization token read from `$path`. Token file is empty!");
|
||||
}
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
return getenv(self::ENV_AUTH_TOKEN);
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides headers for credential metadata request.
|
||||
*
|
||||
* @return array|array[]|string[]
|
||||
*/
|
||||
private function getHeadersForAuthToken()
|
||||
{
|
||||
$authToken = self::getEcsAuthToken();
|
||||
$headers = [];
|
||||
|
||||
if (!empty($authToken))
|
||||
$headers = ['Authorization' => $authToken];
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
/** @deprecated */
|
||||
public function setHeaderForAuthToken()
|
||||
{
|
||||
$authToken = self::getEcsAuthToken();
|
||||
$headers = [];
|
||||
if (!empty($authToken))
|
||||
$headers = ['Authorization' => $authToken];
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch container metadata URI from container environment variable.
|
||||
*
|
||||
* @return string Returns container metadata URI
|
||||
*/
|
||||
private function getEcsUri()
|
||||
{
|
||||
$credsUri = getenv(self::ENV_URI);
|
||||
|
||||
if ($credsUri === false) {
|
||||
$credsUri = $_SERVER[self::ENV_URI] ?? '';
|
||||
}
|
||||
|
||||
if (empty($credsUri)){
|
||||
$credFullUri = getenv(self::ENV_FULL_URI);
|
||||
if ($credFullUri === false){
|
||||
$credFullUri = $_SERVER[self::ENV_FULL_URI] ?? '';
|
||||
}
|
||||
|
||||
if (!empty($credFullUri))
|
||||
return $credFullUri;
|
||||
}
|
||||
|
||||
return self::SERVER_URI . $credsUri;
|
||||
}
|
||||
|
||||
private function decodeResult($response)
|
||||
{
|
||||
$result = json_decode($response, true);
|
||||
|
||||
if (!isset($result['AccessKeyId'])) {
|
||||
throw new CredentialsException('Unexpected container metadata credentials value');
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether or not a given request URI is a valid
|
||||
* container credential request URI.
|
||||
*
|
||||
* @param $uri
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function isCompatibleUri($uri)
|
||||
{
|
||||
$parsed = parse_url($uri);
|
||||
|
||||
if ($parsed['scheme'] !== 'https') {
|
||||
$host = trim($parsed['host'], '[]');
|
||||
$ecsHost = parse_url(self::SERVER_URI)['host'];
|
||||
$eksHost = self::EKS_SERVER_HOST_IPV4;
|
||||
|
||||
if ($host !== $ecsHost
|
||||
&& $host !== $eksHost
|
||||
&& $host !== self::EKS_SERVER_HOST_IPV6
|
||||
&& !CredentialsUtils::isLoopBackAddress(gethostbyname($host))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
<?php
|
||||
namespace Aws\Credentials;
|
||||
|
||||
use Aws\Configuration\ConfigurationResolver;
|
||||
use Aws\Exception\CredentialsException;
|
||||
use Aws\Exception\InvalidJsonException;
|
||||
use Aws\Sdk;
|
||||
use GuzzleHttp\Exception\TransferException;
|
||||
use GuzzleHttp\Promise;
|
||||
use GuzzleHttp\Psr7\Request;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Credential provider that provides credentials from the EC2 metadata service.
|
||||
*/
|
||||
class InstanceProfileProvider
|
||||
{
|
||||
const CRED_PATH = 'meta-data/iam/security-credentials/';
|
||||
const TOKEN_PATH = 'api/token';
|
||||
const ENV_DISABLE = 'AWS_EC2_METADATA_DISABLED';
|
||||
const ENV_TIMEOUT = 'AWS_METADATA_SERVICE_TIMEOUT';
|
||||
const ENV_RETRIES = 'AWS_METADATA_SERVICE_NUM_ATTEMPTS';
|
||||
const CFG_EC2_METADATA_V1_DISABLED = 'ec2_metadata_v1_disabled';
|
||||
const CFG_EC2_METADATA_SERVICE_ENDPOINT = 'ec2_metadata_service_endpoint';
|
||||
const CFG_EC2_METADATA_SERVICE_ENDPOINT_MODE = 'ec2_metadata_service_endpoint_mode';
|
||||
const DEFAULT_TIMEOUT = 1.0;
|
||||
const DEFAULT_RETRIES = 3;
|
||||
const DEFAULT_TOKEN_TTL_SECONDS = 21600;
|
||||
const DEFAULT_AWS_EC2_METADATA_V1_DISABLED = false;
|
||||
const ENDPOINT_MODE_IPv4 = 'IPv4';
|
||||
const ENDPOINT_MODE_IPv6 = 'IPv6';
|
||||
const DEFAULT_METADATA_SERVICE_IPv4_ENDPOINT = 'http://169.254.169.254';
|
||||
const DEFAULT_METADATA_SERVICE_IPv6_ENDPOINT = 'http://[fd00:ec2::254]';
|
||||
|
||||
/** @var string */
|
||||
private $profile;
|
||||
|
||||
/** @var callable */
|
||||
private $client;
|
||||
|
||||
/** @var int */
|
||||
private $retries;
|
||||
|
||||
/** @var int */
|
||||
private $attempts;
|
||||
|
||||
/** @var float|mixed */
|
||||
private $timeout;
|
||||
|
||||
/** @var bool */
|
||||
private $secureMode = true;
|
||||
|
||||
/** @var bool|null */
|
||||
private $ec2MetadataV1Disabled;
|
||||
|
||||
/** @var string */
|
||||
private $endpoint;
|
||||
|
||||
/** @var string */
|
||||
private $endpointMode;
|
||||
|
||||
/** @var array */
|
||||
private $config;
|
||||
|
||||
/**
|
||||
* The constructor accepts the following options:
|
||||
*
|
||||
* - timeout: Connection timeout, in seconds.
|
||||
* - profile: Optional EC2 profile name, if known.
|
||||
* - retries: Optional number of retries to be attempted.
|
||||
* - ec2_metadata_v1_disabled: Optional for disabling the fallback to IMDSv1.
|
||||
* - endpoint: Optional for overriding the default endpoint to be used for fetching credentials.
|
||||
* The value must contain a valid URI scheme. If the URI scheme is not https, it must
|
||||
* resolve to a loopback address.
|
||||
* - endpoint_mode: Optional for overriding the default endpoint mode (IPv4|IPv6) to be used for
|
||||
* resolving the default endpoint.
|
||||
* - use_aws_shared_config_files: Decides whether the shared config file should be considered when
|
||||
* using the ConfigurationResolver::resolve method.
|
||||
*
|
||||
* @param array $config Configuration options.
|
||||
*/
|
||||
public function __construct(array $config = [])
|
||||
{
|
||||
$this->timeout = (float) getenv(self::ENV_TIMEOUT) ?: ($config['timeout'] ?? self::DEFAULT_TIMEOUT);
|
||||
$this->profile = $config['profile'] ?? null;
|
||||
$this->retries = (int) getenv(self::ENV_RETRIES) ?: ($config['retries'] ?? self::DEFAULT_RETRIES);
|
||||
$this->client = $config['client'] ?? \Aws\default_http_handler();
|
||||
$this->ec2MetadataV1Disabled = $config[self::CFG_EC2_METADATA_V1_DISABLED] ?? null;
|
||||
$this->endpoint = $config[self::CFG_EC2_METADATA_SERVICE_ENDPOINT] ?? null;
|
||||
if (!empty($this->endpoint) && !$this->isValidEndpoint($this->endpoint)) {
|
||||
throw new \InvalidArgumentException('The provided URI "' . $this->endpoint . '" is invalid, or contains an unsupported host');
|
||||
}
|
||||
|
||||
$this->endpointMode = $config[self::CFG_EC2_METADATA_SERVICE_ENDPOINT_MODE] ?? null;
|
||||
$this->config = $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads instance profile credentials.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*/
|
||||
public function __invoke($previousCredentials = null)
|
||||
{
|
||||
$this->attempts = 0;
|
||||
return Promise\Coroutine::of(function () use ($previousCredentials) {
|
||||
|
||||
// Retrieve token or switch out of secure mode
|
||||
$token = null;
|
||||
while ($this->secureMode && is_null($token)) {
|
||||
try {
|
||||
$token = (yield $this->request(
|
||||
self::TOKEN_PATH,
|
||||
'PUT',
|
||||
[
|
||||
'x-aws-ec2-metadata-token-ttl-seconds' => self::DEFAULT_TOKEN_TTL_SECONDS
|
||||
]
|
||||
));
|
||||
} catch (TransferException $e) {
|
||||
if ($this->getExceptionStatusCode($e) === 500
|
||||
&& $previousCredentials instanceof Credentials
|
||||
) {
|
||||
goto generateCredentials;
|
||||
} elseif ($this->shouldFallbackToIMDSv1()
|
||||
&& (!method_exists($e, 'getResponse')
|
||||
|| empty($e->getResponse())
|
||||
|| !in_array(
|
||||
$e->getResponse()->getStatusCode(),
|
||||
[400, 500, 502, 503, 504]
|
||||
))
|
||||
) {
|
||||
$this->secureMode = false;
|
||||
} else {
|
||||
$this->handleRetryableException(
|
||||
$e,
|
||||
[],
|
||||
$this->createErrorMessage(
|
||||
'Error retrieving metadata token'
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
$this->attempts++;
|
||||
}
|
||||
|
||||
// Set token header only for secure mode
|
||||
$headers = [];
|
||||
if ($this->secureMode) {
|
||||
$headers = [
|
||||
'x-aws-ec2-metadata-token' => $token
|
||||
];
|
||||
}
|
||||
|
||||
// Retrieve profile
|
||||
while (!$this->profile) {
|
||||
try {
|
||||
$this->profile = (yield $this->request(
|
||||
self::CRED_PATH,
|
||||
'GET',
|
||||
$headers
|
||||
));
|
||||
} catch (TransferException $e) {
|
||||
// 401 indicates insecure flow not supported, switch to
|
||||
// attempting secure mode for subsequent calls
|
||||
if (!empty($this->getExceptionStatusCode($e))
|
||||
&& $this->getExceptionStatusCode($e) === 401
|
||||
) {
|
||||
$this->secureMode = true;
|
||||
}
|
||||
$this->handleRetryableException(
|
||||
$e,
|
||||
[ 'blacklist' => [401, 403] ],
|
||||
$this->createErrorMessage($e->getMessage())
|
||||
);
|
||||
}
|
||||
|
||||
$this->attempts++;
|
||||
}
|
||||
|
||||
// Retrieve credentials
|
||||
$result = null;
|
||||
while ($result == null) {
|
||||
try {
|
||||
$json = (yield $this->request(
|
||||
self::CRED_PATH . $this->profile,
|
||||
'GET',
|
||||
$headers
|
||||
));
|
||||
$result = $this->decodeResult($json);
|
||||
} catch (InvalidJsonException $e) {
|
||||
$this->handleRetryableException(
|
||||
$e,
|
||||
[ 'blacklist' => [401, 403] ],
|
||||
$this->createErrorMessage(
|
||||
'Invalid JSON response, retries exhausted'
|
||||
)
|
||||
);
|
||||
} catch (TransferException $e) {
|
||||
// 401 indicates insecure flow not supported, switch to
|
||||
// attempting secure mode for subsequent calls
|
||||
if (($this->getExceptionStatusCode($e) === 500
|
||||
|| strpos($e->getMessage(), "cURL error 28") !== false)
|
||||
&& $previousCredentials instanceof Credentials
|
||||
) {
|
||||
goto generateCredentials;
|
||||
} elseif (!empty($this->getExceptionStatusCode($e))
|
||||
&& $this->getExceptionStatusCode($e) === 401
|
||||
) {
|
||||
$this->secureMode = true;
|
||||
}
|
||||
$this->handleRetryableException(
|
||||
$e,
|
||||
[ 'blacklist' => [401, 403] ],
|
||||
$this->createErrorMessage($e->getMessage())
|
||||
);
|
||||
}
|
||||
$this->attempts++;
|
||||
}
|
||||
generateCredentials:
|
||||
|
||||
if (!isset($result)) {
|
||||
$credentials = $previousCredentials;
|
||||
} else {
|
||||
$credentials = new Credentials(
|
||||
$result['AccessKeyId'],
|
||||
$result['SecretAccessKey'],
|
||||
$result['Token'],
|
||||
strtotime($result['Expiration']),
|
||||
$result['AccountId'] ?? null,
|
||||
CredentialSources::IMDS
|
||||
);
|
||||
}
|
||||
|
||||
if ($credentials->isExpired()) {
|
||||
$credentials->extendExpiration();
|
||||
}
|
||||
|
||||
yield $credentials;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $url
|
||||
* @param string $method
|
||||
* @param array $headers
|
||||
* @return PromiseInterface Returns a promise that is fulfilled with the
|
||||
* body of the response as a string.
|
||||
*/
|
||||
private function request($url, $method = 'GET', $headers = [])
|
||||
{
|
||||
$disabled = getenv(self::ENV_DISABLE) ?: false;
|
||||
if (strcasecmp($disabled, 'true') === 0) {
|
||||
throw new CredentialsException(
|
||||
$this->createErrorMessage('EC2 metadata service access disabled')
|
||||
);
|
||||
}
|
||||
|
||||
$fn = $this->client;
|
||||
$request = new Request($method, $this->resolveEndpoint() . $url);
|
||||
$userAgent = 'aws-sdk-php/' . Sdk::VERSION;
|
||||
if (defined('HHVM_VERSION')) {
|
||||
$userAgent .= ' HHVM/' . HHVM_VERSION;
|
||||
}
|
||||
$userAgent .= ' ' . \Aws\default_user_agent();
|
||||
$request = $request->withHeader('User-Agent', $userAgent);
|
||||
foreach ($headers as $key => $value) {
|
||||
$request = $request->withHeader($key, $value);
|
||||
}
|
||||
|
||||
return $fn($request, ['timeout' => $this->timeout])
|
||||
->then(function (ResponseInterface $response) {
|
||||
return (string) $response->getBody();
|
||||
})->otherwise(function (array $reason) {
|
||||
$reason = $reason['exception'];
|
||||
if ($reason instanceof TransferException) {
|
||||
throw $reason;
|
||||
}
|
||||
$msg = $reason->getMessage();
|
||||
throw new CredentialsException(
|
||||
$this->createErrorMessage($msg)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private function handleRetryableException(
|
||||
\Exception $e,
|
||||
$retryOptions,
|
||||
$message
|
||||
) {
|
||||
$isRetryable = true;
|
||||
if (!empty($status = $this->getExceptionStatusCode($e))
|
||||
&& isset($retryOptions['blacklist'])
|
||||
&& in_array($status, $retryOptions['blacklist'])
|
||||
) {
|
||||
$isRetryable = false;
|
||||
}
|
||||
if ($isRetryable && $this->attempts < $this->retries) {
|
||||
sleep((int) pow(1.2, $this->attempts));
|
||||
} else {
|
||||
throw new CredentialsException($message);
|
||||
}
|
||||
}
|
||||
|
||||
private function getExceptionStatusCode(\Exception $e)
|
||||
{
|
||||
if (method_exists($e, 'getResponse')
|
||||
&& !empty($e->getResponse())
|
||||
) {
|
||||
return $e->getResponse()->getStatusCode();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private function createErrorMessage($previous)
|
||||
{
|
||||
return "Error retrieving credentials from the instance profile "
|
||||
. "metadata service. ({$previous})";
|
||||
}
|
||||
|
||||
private function decodeResult($response)
|
||||
{
|
||||
$result = json_decode($response, true);
|
||||
|
||||
if (json_last_error() > 0) {
|
||||
throw new InvalidJsonException();
|
||||
}
|
||||
|
||||
if ($result['Code'] !== 'Success') {
|
||||
throw new CredentialsException('Unexpected instance profile '
|
||||
. 'response code: ' . $result['Code']);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* This functions checks for whether we should fall back to IMDSv1 or not.
|
||||
* If $ec2MetadataV1Disabled is null then we will try to resolve this value from
|
||||
* the following sources:
|
||||
* - From environment: "AWS_EC2_METADATA_V1_DISABLED".
|
||||
* - From config file: aws_ec2_metadata_v1_disabled
|
||||
* - Defaulted to false
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function shouldFallbackToIMDSv1(): bool
|
||||
{
|
||||
$isImdsV1Disabled = \Aws\boolean_value($this->ec2MetadataV1Disabled)
|
||||
?? \Aws\boolean_value(
|
||||
ConfigurationResolver::resolve(
|
||||
self::CFG_EC2_METADATA_V1_DISABLED,
|
||||
self::DEFAULT_AWS_EC2_METADATA_V1_DISABLED,
|
||||
'bool',
|
||||
$this->config
|
||||
)
|
||||
)
|
||||
?? self::DEFAULT_AWS_EC2_METADATA_V1_DISABLED;
|
||||
|
||||
return !$isImdsV1Disabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the metadata service endpoint. If the endpoint is not provided
|
||||
* or configured then, the default endpoint, based on the endpoint mode resolved,
|
||||
* will be used.
|
||||
* Example: if endpoint_mode is resolved to be IPv4 and the endpoint is not provided
|
||||
* then, the endpoint to be used will be http://169.254.169.254.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function resolveEndpoint(): string
|
||||
{
|
||||
$endpoint = $this->endpoint;
|
||||
if (is_null($endpoint)) {
|
||||
$endpoint = ConfigurationResolver::resolve(
|
||||
self::CFG_EC2_METADATA_SERVICE_ENDPOINT,
|
||||
$this->getDefaultEndpoint(),
|
||||
'string',
|
||||
$this->config
|
||||
);
|
||||
}
|
||||
|
||||
if (!$this->isValidEndpoint($endpoint)) {
|
||||
throw new CredentialsException('The provided URI "' . $endpoint . '" is invalid, or contains an unsupported host');
|
||||
}
|
||||
|
||||
if (substr($endpoint, strlen($endpoint) - 1) !== '/') {
|
||||
$endpoint = $endpoint . '/';
|
||||
}
|
||||
|
||||
return $endpoint . 'latest/';
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the default metadata service endpoint.
|
||||
* If endpoint_mode is resolved as IPv4 then:
|
||||
* - endpoint = http://169.254.169.254
|
||||
* If endpoint_mode is resolved as IPv6 then:
|
||||
* - endpoint = http://[fd00:ec2::254]
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function getDefaultEndpoint(): string
|
||||
{
|
||||
$endpointMode = $this->resolveEndpointMode();
|
||||
switch ($endpointMode) {
|
||||
case self::ENDPOINT_MODE_IPv4:
|
||||
return self::DEFAULT_METADATA_SERVICE_IPv4_ENDPOINT;
|
||||
case self::ENDPOINT_MODE_IPv6:
|
||||
return self::DEFAULT_METADATA_SERVICE_IPv6_ENDPOINT;
|
||||
}
|
||||
|
||||
throw new CredentialsException("Invalid endpoint mode '$endpointMode' resolved");
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the endpoint mode to be considered when resolving the default
|
||||
* metadata service endpoint.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function resolveEndpointMode(): string
|
||||
{
|
||||
$endpointMode = $this->endpointMode;
|
||||
if (is_null($endpointMode)) {
|
||||
$endpointMode = ConfigurationResolver::resolve(
|
||||
self::CFG_EC2_METADATA_SERVICE_ENDPOINT_MODE,
|
||||
self::ENDPOINT_MODE_IPv4,
|
||||
'string',
|
||||
$this->config
|
||||
);
|
||||
}
|
||||
|
||||
return $endpointMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method checks for whether a provide URI is valid.
|
||||
* @param string $uri this parameter is the uri to do the validation against to.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
private function isValidEndpoint(
|
||||
$uri
|
||||
): bool
|
||||
{
|
||||
// We make sure first the provided uri is a valid URL
|
||||
$isValidURL = filter_var($uri, FILTER_VALIDATE_URL) !== false;
|
||||
if (!$isValidURL) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// We make sure that if is a no secure host then it must be a loop back address.
|
||||
$parsedUri = parse_url($uri);
|
||||
if ($parsedUri['scheme'] !== 'https') {
|
||||
$host = trim($parsedUri['host'], '[]');
|
||||
|
||||
return CredentialsUtils::isLoopBackAddress(gethostbyname($host))
|
||||
|| in_array(
|
||||
$uri,
|
||||
[self::DEFAULT_METADATA_SERVICE_IPv4_ENDPOINT, self::DEFAULT_METADATA_SERVICE_IPv6_ENDPOINT]
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user