v2: Updates

* Simplifies & beautifies everything
* Introduces a new Class system.
* Errors are defaulted to AWS's handler.
* New function names & more efficient handling.
* Should fix a majority of the errors.

Please read the README for more!
This commit is contained in:
Devang Srivastava 2020-09-28 15:32:51 +05:30
commit e6d7753dc8
1095 changed files with 45088 additions and 2911 deletions

View file

@ -1,15 +1,10 @@
<?php
namespace Aws\Credentials;
use Aws\Exception\AwsException;
use Aws\Exception\CredentialsException;
use Aws\Result;
use Aws\Sts\StsClient;
use GuzzleHttp\Promise;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
/**
* Credential provider that provides credentials via assuming a role
@ -19,7 +14,7 @@ class AssumeRoleCredentialProvider
{
const ERROR_MSG = "Missing required 'AssumeRoleCredentialProvider' configuration option: ";
/** @var callable */
/** @var StsClient */
private $client;
/** @var array */

View file

@ -0,0 +1,148 @@
<?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 $attempts;
/**
* 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
*
* @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->attempts = 0;
$this->session = isset($config['SessionName'])
? $config['SessionName']
: 'aws-sdk-php-' . round(microtime(true) * 1000);
$region = isset($config['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'
]);
}
}
/**
* Loads assume role with web identity credentials.
*
* @return Promise\PromiseInterface
*/
public function __invoke()
{
return Promise\coroutine(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);
$token = file_get_contents($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->attempts < $this->retries) {
sleep(pow(1.2, $this->attempts));
} 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->attempts++;
}
yield $this->client->createCredentials($result);
});
}
}

View file

@ -2,8 +2,10 @@
namespace Aws\Credentials;
use Aws;
use Aws\Api\DateTimeResult;
use Aws\CacheInterface;
use Aws\Exception\CredentialsException;
use Aws\Sts\StsClient;
use GuzzleHttp\Promise;
/**
@ -42,18 +44,23 @@ use GuzzleHttp\Promise;
*/
class CredentialProvider
{
const ENV_ARN = 'AWS_ROLE_ARN';
const ENV_KEY = 'AWS_ACCESS_KEY_ID';
const ENV_PROFILE = 'AWS_PROFILE';
const ENV_ROLE_SESSION_NAME = 'AWS_ROLE_SESSION_NAME';
const ENV_SECRET = 'AWS_SECRET_ACCESS_KEY';
const ENV_SESSION = 'AWS_SESSION_TOKEN';
const ENV_PROFILE = 'AWS_PROFILE';
const ENV_TOKEN_FILE = 'AWS_WEB_IDENTITY_TOKEN_FILE';
/**
* Create a default credential provider that first checks for environment
* variables, then checks for the "default" profile in ~/.aws/credentials,
* then checks for "profile default" profile in ~/.aws/config (which is
* the default profile of AWS CLI), then tries to make a GET Request to
* fetch credentials if Ecs environment variable is presented, and finally
* checks for EC2 instance profile credentials.
* fetch credentials if Ecs environment variable is presented, then checks
* for credential_process in the "default" profile in ~/.aws/credentials,
* then for credential_process in the "default profile" profile in
* ~/.aws/config, and finally checks for EC2 instance profile credentials.
*
* This provider is automatically wrapped in a memoize function that caches
* previously provided credentials.
@ -65,13 +72,63 @@ class CredentialProvider
*/
public static function defaultProvider(array $config = [])
{
$localCredentialProviders = self::localCredentialProviders();
$remoteCredentialProviders = self::remoteCredentialProviders($config);
$cacheable = [
'web_identity',
'sso',
'ecs',
'process_credentials',
'process_config',
'instance'
];
$defaultChain = [
'env' => self::env(),
'web_identity' => self::assumeRoleWithWebIdentityCredentialProvider($config),
];
if (
!isset($config['use_aws_shared_config_files'])
|| $config['use_aws_shared_config_files'] !== false
) {
$defaultChain['sso'] = self::sso(
'profile default',
self::getHomeDir() . '/.aws/config',
$config
);
$defaultChain['ini'] = self::ini();
$defaultChain['ini_config'] = self::ini(
'profile default',
self::getHomeDir() . '/.aws/config'
);
}
if (!empty(getenv(EcsCredentialProvider::ENV_URI))) {
$defaultChain['ecs'] = self::ecsCredentials($config);
}
$defaultChain['process_credentials'] = self::process();
$defaultChain['process_config'] = self::process(
'profile default',
self::getHomeDir() . '/.aws/config'
);
$defaultChain['instance'] = self::instanceProfile($config);
if (isset($config['credentials'])
&& $config['credentials'] instanceof CacheInterface
) {
foreach ($cacheable as $provider) {
if (isset($defaultChain[$provider])) {
$defaultChain[$provider] = self::cache(
$defaultChain[$provider],
$config['credentials'],
'aws_cached_' . $provider . '_credentials'
);
}
}
}
return self::memoize(
call_user_func_array(
'self::chain',
array_merge($localCredentialProviders, $remoteCredentialProviders)
array_values($defaultChain)
)
);
}
@ -158,6 +215,11 @@ class CredentialProvider
}
// Refresh the result and forward the promise.
return $result = $provider();
})
->otherwise(function($reason) use (&$result) {
// Cleanup rejected promise.
$result = null;
return new Promise\RejectedPromise($reason);
});
};
}
@ -167,8 +229,6 @@ class CredentialProvider
* instance of Aws\CacheInterface. Forwards calls when no credentials found
* in cache and updates cache with the results.
*
* Defaults to using a simple file-based cache when none provided.
*
* @param callable $provider Credentials provider function to wrap
* @param CacheInterface $cache Cache to store credentials
* @param string|null $cacheKey (optional) Cache key to use
@ -242,6 +302,85 @@ class CredentialProvider
return new InstanceProfileProvider($config);
}
/**
* Credential provider that retrieves cached SSO credentials from the CLI
*
* @return callable
*/
public static function sso($ssoProfileName, $filename = null, $config = [])
{
$filename = $filename ?: (self::getHomeDir() . '/.aws/config');
return function () use ($ssoProfileName, $filename, $config) {
if (!is_readable($filename)) {
return self::reject("Cannot read credentials from $filename");
}
$data = self::loadProfiles($filename);
$ssoProfile = $data[$ssoProfileName];
if (empty($ssoProfile['sso_start_url'])
|| empty($ssoProfile['sso_region'])
|| empty($ssoProfile['sso_account_id'])
|| empty($ssoProfile['sso_role_name'])
) {
return self::reject(
"Profile {$ssoProfileName} in {$filename} must contain the following keys: "
. 'sso_start_url, sso_region, sso_account_id, and sso_role_name'
);
}
$tokenLocation = self::getHomeDir()
. '/.aws/sso/cache/'
. utf8_encode(sha1($ssoProfile['sso_start_url']))
. ".json";
if (!is_readable($tokenLocation)) {
return self::reject("Unable to read token file at $tokenLocation");
}
$tokenData = json_decode(file_get_contents($tokenLocation), true);
if (empty($tokenData['accessToken']) || empty($tokenData['expiresAt'])) {
return self::reject(
"Token file at {$tokenLocation} must contain an access token and an expiration"
);
}
try {
$expiration = (new DateTimeResult($tokenData['expiresAt']))->getTimestamp();
} catch (\Exception $e) {
return self::reject("Cached SSO credentials returned an invalid expiration");
}
$now = time();
if ($expiration < $now) {
return self::reject("Cached SSO credentials returned expired credentials");
}
$ssoClient = null;
if (empty($config['ssoClient'])) {
$ssoClient = new Aws\SSO\SSOClient([
'region' => $ssoProfile['sso_region'],
'version' => '2019-06-10',
'credentials' => false
]);
} else {
$ssoClient = $config['ssoClient'];
}
$ssoResponse = $ssoClient->getRoleCredentials([
'accessToken' => $tokenData['accessToken'],
'accountId' => $ssoProfile['sso_account_id'],
'roleName' => $ssoProfile['sso_role_name']
]);
$ssoCredentials = $ssoResponse['roleCredentials'];
return Promise\promise_for(
new Credentials(
$ssoCredentials['accessKeyId'],
$ssoCredentials['secretAccessKey'],
$ssoCredentials['sessionToken'],
$expiration
)
);
};
}
/**
* Credential provider that creates credentials using
* ecs credentials by a GET request, whose uri is specified
@ -269,33 +408,151 @@ class CredentialProvider
return new AssumeRoleCredentialProvider($config);
}
/**
* Credential provider that creates credentials by assuming role from a
* Web Identity Token
*
* @param array $config Array of configuration data
* @return callable
* @see Aws\Credentials\AssumeRoleWithWebIdentityCredentialProvider for
* $config details.
*/
public static function assumeRoleWithWebIdentityCredentialProvider(array $config = [])
{
return function () use ($config) {
$arnFromEnv = getenv(self::ENV_ARN);
$tokenFromEnv = getenv(self::ENV_TOKEN_FILE);
$stsClient = isset($config['stsClient'])
? $config['stsClient']
: null;
$region = isset($config['region'])
? $config['region']
: null;
if ($tokenFromEnv && $arnFromEnv) {
$sessionName = getenv(self::ENV_ROLE_SESSION_NAME)
? getenv(self::ENV_ROLE_SESSION_NAME)
: null;
$provider = new AssumeRoleWithWebIdentityCredentialProvider([
'RoleArn' => $arnFromEnv,
'WebIdentityTokenFile' => $tokenFromEnv,
'SessionName' => $sessionName,
'client' => $stsClient,
'region' => $region
]);
return $provider();
}
$profileName = getenv(self::ENV_PROFILE) ?: 'default';
if (isset($config['filename'])) {
$profiles = self::loadProfiles($config['filename']);
} else {
$profiles = self::loadDefaultProfiles();
}
if (isset($profiles[$profileName])) {
$profile = $profiles[$profileName];
if (isset($profile['region'])) {
$region = $profile['region'];
}
if (isset($profile['web_identity_token_file'])
&& isset($profile['role_arn'])
) {
$sessionName = isset($profile['role_session_name'])
? $profile['role_session_name']
: null;
$provider = new AssumeRoleWithWebIdentityCredentialProvider([
'RoleArn' => $profile['role_arn'],
'WebIdentityTokenFile' => $profile['web_identity_token_file'],
'SessionName' => $sessionName,
'client' => $stsClient,
'region' => $region
]);
return $provider();
}
} else {
return self::reject("Unknown profile: $profileName");
}
return self::reject("No RoleArn or WebIdentityTokenFile specified");
};
}
/**
* Credentials provider that creates credentials using an ini file stored
* in the current user's home directory.
* in the current user's home directory. A source can be provided
* in this file for assuming a role using the credential_source config option.
*
* @param string|null $profile Profile to use. If not specified will use
* the "default" profile in "~/.aws/credentials".
* @param string|null $filename If provided, uses a custom filename rather
* than looking in the home directory.
* @param array|null $config If provided, may contain the following:
* preferStaticCredentials: If true, prefer static
* credentials to role_arn if both are present
* disableAssumeRole: If true, disable support for
* roles that assume an IAM role. If true and role profile
* is selected, an error is raised.
* stsClient: StsClient used to assume role specified in profile
*
* @return callable
*/
public static function ini($profile = null, $filename = null)
public static function ini($profile = null, $filename = null, array $config = [])
{
$filename = $filename ?: (self::getHomeDir() . '/.aws/credentials');
$profile = $profile ?: (getenv(self::ENV_PROFILE) ?: 'default');
return function () use ($profile, $filename) {
return function () use ($profile, $filename, $config) {
$preferStaticCredentials = isset($config['preferStaticCredentials'])
? $config['preferStaticCredentials']
: false;
$disableAssumeRole = isset($config['disableAssumeRole'])
? $config['disableAssumeRole']
: false;
$stsClient = isset($config['stsClient']) ? $config['stsClient'] : null;
if (!is_readable($filename)) {
return self::reject("Cannot read credentials from $filename");
}
$data = parse_ini_file($filename, true);
$data = self::loadProfiles($filename);
if ($data === false) {
return self::reject("Invalid credentials file: $filename");
}
if (!isset($data[$profile])) {
return self::reject("'$profile' not found in credentials file");
}
/*
In the CLI, the presence of both a role_arn and static credentials have
different meanings depending on how many profiles have been visited. For
the first profile processed, role_arn takes precedence over any static
credentials, but for all subsequent profiles, static credentials are
used if present, and only in their absence will the profile's
source_profile and role_arn keys be used to load another set of
credentials. This bool is intended to yield compatible behaviour in this
sdk.
*/
$preferStaticCredentialsToRoleArn = ($preferStaticCredentials
&& isset($data[$profile]['aws_access_key_id'])
&& isset($data[$profile]['aws_secret_access_key']));
if (isset($data[$profile]['role_arn'])
&& !$preferStaticCredentialsToRoleArn
) {
if ($disableAssumeRole) {
return self::reject(
"Role assumption profiles are disabled. "
. "Failed to load profile " . $profile);
}
return self::loadRoleProfile(
$data,
$profile,
$filename,
$stsClient
);
}
if (!isset($data[$profile]['aws_access_key_id'])
|| !isset($data[$profile]['aws_secret_access_key'])
) {
@ -321,53 +578,149 @@ class CredentialProvider
}
/**
* Local credential providers returns a list of local credential providers
* in following order:
* - credentials from environment variables
* - 'default' profile in '.aws/credentials' file
* - 'profile default' profile in '.aws/config' file
* Credentials provider that creates credentials using a process configured in
* ini file stored in the current user's home directory.
*
* @return array
* @param string|null $profile Profile to use. If not specified will use
* the "default" profile in "~/.aws/credentials".
* @param string|null $filename If provided, uses a custom filename rather
* than looking in the home directory.
*
* @return callable
*/
private static function localCredentialProviders()
public static function process($profile = null, $filename = null)
{
return [
self::env(),
self::ini(),
self::ini('profile default', self::getHomeDir() . '/.aws/config')
];
$filename = $filename ?: (self::getHomeDir() . '/.aws/credentials');
$profile = $profile ?: (getenv(self::ENV_PROFILE) ?: 'default');
return function () use ($profile, $filename) {
if (!is_readable($filename)) {
return self::reject("Cannot read process credentials from $filename");
}
$data = \Aws\parse_ini_file($filename, true, INI_SCANNER_RAW);
if ($data === false) {
return self::reject("Invalid credentials file: $filename");
}
if (!isset($data[$profile])) {
return self::reject("'$profile' not found in credentials file");
}
if (!isset($data[$profile]['credential_process'])) {
return self::reject("No credential_process present in INI profile "
. "'$profile' ($filename)");
}
$credentialProcess = $data[$profile]['credential_process'];
$json = shell_exec($credentialProcess);
$processData = json_decode($json, true);
// Only support version 1
if (isset($processData['Version'])) {
if ($processData['Version'] !== 1) {
return self::reject("credential_process does not return Version == 1");
}
}
if (!isset($processData['AccessKeyId'])
|| !isset($processData['SecretAccessKey']))
{
return self::reject("credential_process does not return valid credentials");
}
if (isset($processData['Expiration'])) {
try {
$expiration = new DateTimeResult($processData['Expiration']);
} catch (\Exception $e) {
return self::reject("credential_process returned invalid expiration");
}
$now = new DateTimeResult();
if ($expiration < $now) {
return self::reject("credential_process returned expired credentials");
}
$expires = $expiration->getTimestamp();
} else {
$expires = null;
}
if (empty($processData['SessionToken'])) {
$processData['SessionToken'] = null;
}
return Promise\promise_for(
new Credentials(
$processData['AccessKeyId'],
$processData['SecretAccessKey'],
$processData['SessionToken'],
$expires
)
);
};
}
/**
* Remote credential providers returns a list of credentials providers
* for the remote endpoints such as EC2 or ECS Roles.
* Assumes role for profile that includes role_arn
*
* @param array $config Array of configuration data.
*
* @return array
* @see Aws\Credentials\InstanceProfileProvider for $config details.
* @see Aws\Credentials\EcsCredentialProvider for $config details.
* @return callable
*/
private static function remoteCredentialProviders(array $config = [])
private static function loadRoleProfile($profiles, $profileName, $filename, $stsClient)
{
if (!empty(getenv(EcsCredentialProvider::ENV_URI))) {
$providers['ecs'] = self::ecsCredentials($config);
}
$providers['instance'] = self::instanceProfile($config);
$roleProfile = $profiles[$profileName];
$roleArn = isset($roleProfile['role_arn']) ? $roleProfile['role_arn'] : '';
$roleSessionName = isset($roleProfile['role_session_name'])
? $roleProfile['role_session_name']
: 'aws-sdk-php-' . round(microtime(true) * 1000);
if (isset($config['credentials'])
&& $config['credentials'] instanceof CacheInterface
if (
empty($roleProfile['source_profile'])
== empty($roleProfile['credential_source'])
) {
foreach ($providers as $key => $provider) {
$providers[$key] = self::cache(
$provider,
$config['credentials'],
'aws_cached_' . $key . '_credentials'
return self::reject("Either source_profile or credential_source must be set " .
"using profile " . $profileName . ", but not both."
);
}
$sourceProfileName = "";
if (!empty($roleProfile['source_profile'])) {
$sourceProfileName = $roleProfile['source_profile'];
if (!isset($profiles[$sourceProfileName])) {
return self::reject("source_profile " . $sourceProfileName
. " using profile " . $profileName . " does not exist"
);
}
}
$sourceRegion = isset($profiles[$sourceProfileName]['region'])
? $profiles[$sourceProfileName]['region']
: 'us-east-1';
return $providers;
if (empty($stsClient)) {
$config = [
'preferStaticCredentials' => true
];
$sourceCredentials = null;
if ($roleProfile['source_profile']){
$sourceCredentials = call_user_func(
CredentialProvider::ini($sourceProfileName, $filename, $config)
)->wait();
} else {
$sourceCredentials = self::getCredentialsFromSource(
$profileName,
$filename
);
}
$stsClient = new StsClient([
'credentials' => $sourceCredentials,
'region' => $sourceRegion,
'version' => '2011-06-15',
]);
}
$result = $stsClient->assumeRole([
'RoleArn' => $roleArn,
'RoleSessionName' => $roleSessionName
]);
$credentials = $stsClient->createCredentials($result);
return Promise\promise_for($credentials);
}
/**
@ -389,6 +742,97 @@ class CredentialProvider
return ($homeDrive && $homePath) ? $homeDrive . $homePath : null;
}
/**
* Gets profiles from specified $filename, or default ini files.
*/
private static function loadProfiles($filename)
{
$profileData = \Aws\parse_ini_file($filename, true, INI_SCANNER_RAW);
// If loading .aws/credentials, also load .aws/config when AWS_SDK_LOAD_NONDEFAULT_CONFIG is set
if ($filename === self::getHomeDir() . '/.aws/credentials'
&& getenv('AWS_SDK_LOAD_NONDEFAULT_CONFIG')
) {
$configFilename = self::getHomeDir() . '/.aws/config';
$configProfileData = \Aws\parse_ini_file($configFilename, true, INI_SCANNER_RAW);
foreach ($configProfileData as $name => $profile) {
// standardize config profile names
$name = str_replace('profile ', '', $name);
if (!isset($profileData[$name])) {
$profileData[$name] = $profile;
}
}
}
return $profileData;
}
/**
* Gets profiles from ~/.aws/credentials and ~/.aws/config ini files
*/
private static function loadDefaultProfiles() {
$profiles = [];
$credFile = self::getHomeDir() . '/.aws/credentials';
$configFile = self::getHomeDir() . '/.aws/config';
if (file_exists($credFile)) {
$profiles = \Aws\parse_ini_file($credFile, true, INI_SCANNER_RAW);
}
if (file_exists($configFile)) {
$configProfileData = \Aws\parse_ini_file($configFile, true, INI_SCANNER_RAW);
foreach ($configProfileData as $name => $profile) {
// standardize config profile names
$name = str_replace('profile ', '', $name);
if (!isset($profiles[$name])) {
$profiles[$name] = $profile;
}
}
}
return $profiles;
}
public static function getCredentialsFromSource(
$profileName = '',
$filename = '',
$config = []
) {
$data = self::loadProfiles($filename);
$credentialSource = !empty($data[$profileName]['credential_source']) ? $data[$profileName]['credential_source'] : null;
$credentialsPromise = null;
switch ($credentialSource) {
case 'Environment':
$credentialsPromise = self::env();
break;
case 'Ec2InstanceMetadata':
$credentialsPromise = self::instanceProfile($config);
break;
case 'EcsContainer':
$credentialsPromise = self::ecsCredentials($config);
break;
default:
throw new CredentialsException (
"Invalid credential_source found in config file: {$credentialSource}. Valid inputs "
. "include Environment, Ec2InstanceMetadata, and EcsContainer."
);
}
$credentialsResult = null;
try {
$credentialsResult = $credentialsPromise()->wait();
} catch (\Exception $reason) {
return self::reject(
"Unable to successfully retrieve credentials from the source specified in the"
. " credentials file: {$credentialSource}; failure message was: "
. $reason->getMessage()
);
}
return function () use ($credentialsResult) {
return Promise\promise_for($credentialsResult);
};
}
private static function reject($msg)
{
return new Promise\RejectedPromise(new CredentialsException($msg));

View file

@ -2,7 +2,6 @@
namespace Aws\Credentials;
use Aws\Exception\CredentialsException;
use GuzzleHttp\Promise;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\ResponseInterface;
@ -15,10 +14,14 @@ class EcsCredentialProvider
{
const SERVER_URI = 'http://169.254.170.2';
const ENV_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI";
const ENV_TIMEOUT = 'AWS_METADATA_SERVICE_TIMEOUT';
/** @var callable */
private $client;
/** @var float|mixed */
private $timeout;
/**
* The constructor accepts following options:
* - timeout: (optional) Connection timeout, in seconds, default 1.0
@ -28,7 +31,7 @@ class EcsCredentialProvider
*/
public function __construct(array $config = [])
{
$this->timeout = isset($config['timeout']) ? $config['timeout'] : 1.0;
$this->timeout = (float) getenv(self::ENV_TIMEOUT) ?: (isset($config['timeout']) ? $config['timeout'] : 1.0);
$this->client = isset($config['client'])
? $config['client']
: \Aws\default_http_handler();
@ -45,7 +48,10 @@ class EcsCredentialProvider
$request = new Request('GET', self::getEcsUri());
return $client(
$request,
['timeout' => $this->timeout]
[
'timeout' => $this->timeout,
'proxy' => '',
]
)->then(function (ResponseInterface $response) {
$result = $this->decodeResult((string) $response->getBody());
return new Credentials(

View file

@ -2,18 +2,26 @@
namespace Aws\Credentials;
use Aws\Exception\CredentialsException;
use Aws\Exception\InvalidJsonException;
use Aws\Sdk;
use GuzzleHttp\Promise;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Credential provider that provides credentials from the EC2 metadata server.
* Credential provider that provides credentials from the EC2 metadata service.
*/
class InstanceProfileProvider
{
const SERVER_URI = 'http://169.254.169.254/latest/';
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';
/** @var string */
private $profile;
@ -21,18 +29,33 @@ class InstanceProfileProvider
/** @var callable */
private $client;
/** @var int */
private $retries;
/** @var int */
private $attempts;
/** @var float|mixed */
private $timeout;
/** @var bool */
private $secureMode = true;
/**
* 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.
*
* @param array $config Configuration options.
*/
public function __construct(array $config = [])
{
$this->timeout = isset($config['timeout']) ? $config['timeout'] : 1.0;
$this->timeout = (float) getenv(self::ENV_TIMEOUT) ?: (isset($config['timeout']) ? $config['timeout'] : 1.0);
$this->profile = isset($config['profile']) ? $config['profile'] : null;
$this->retries = (int) getenv(self::ENV_RETRIES) ?: (isset($config['retries']) ? $config['retries'] : 3);
$this->attempts = 0;
$this->client = isset($config['client'])
? $config['client'] // internal use only
: \Aws\default_http_handler();
@ -46,11 +69,107 @@ class InstanceProfileProvider
public function __invoke()
{
return Promise\coroutine(function () {
if (!$this->profile) {
$this->profile = (yield $this->request(self::CRED_PATH));
// 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' => 21600
]
));
} catch (RequestException $e) {
if (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 (RequestException $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 (RequestException $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++;
}
$json = (yield $this->request(self::CRED_PATH . $this->profile));
$result = $this->decodeResult($json);
yield new Credentials(
$result['AccessKeyId'],
$result['SecretAccessKey'],
@ -62,36 +181,90 @@ class InstanceProfileProvider
/**
* @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)
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('GET', self::SERVER_URI . $url);
$request = new Request($method, self::SERVER_URI . $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 \GuzzleHttp\Exception\RequestException) {
throw $reason;
}
$msg = $reason->getMessage();
throw new CredentialsException(
$this->createErrorMessage($msg, 0, $reason)
$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(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 server. ({$previous})";
. "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']);