allow vendord
All checks were successful
Build, Push and Deploy / build-and-push (push) Successful in 3m3s
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 16s
Build, Push and Deploy / deploy-staging (push) Successful in 32s
Build, Push and Deploy / deploy-production (push) Has been skipped
Build, Push and Deploy / cleanup (push) Successful in 1s

This commit is contained in:
2026-03-30 14:54:57 +07:00
parent 66aed7c4e8
commit b5e3a778ce
21316 changed files with 2777892 additions and 13 deletions

View File

@@ -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
);
});
}
}

View File

@@ -0,0 +1,201 @@
<?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);
if (isset($config['client'])) {
$this->client = $config['client'];
} else {
$region = $config['region']
?? getEnv(CredentialProvider::ENV_REGION)
?: null;
$this->client = $this->createDefaultStsClient($region);
}
$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
);
});
}
/**
* @param string|null $region
*
* @return StsClient
*/
private function createDefaultStsClient(
?string $region
): StsClient
{
if (empty($region)) {
$region = CredentialProvider::FALLBACK_REGION;
trigger_error(
'NOTICE: STS client created without explicit `region` configuration.' . PHP_EOL
. "Defaulting to {$region}. This fallback behavior may be removed." . PHP_EOL
. 'To avoid potential disruptions, configure a region using one of the following methods:' . PHP_EOL
. '(1) Pass `region` in the `$config` array when calling the provider,' . PHP_EOL
. '(2) Set the `AWS_REGION` environment variable.' . PHP_EOL
. 'OR provide an STS client in the `$config` array when creating the provider as `client`.' . PHP_EOL
. 'See: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/assume-role-with-web-identity-provider.html'
. PHP_EOL,
E_USER_NOTICE
);
}
return new StsClient([
'credentials' => false,
'region' => $region
]);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,23 @@
<?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';
const PROFILE_LOGIN = 'profile_login';
}

View File

@@ -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);
}
}

View File

@@ -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();
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -0,0 +1,527 @@
<?php
namespace Aws\Credentials;
use Aws\Configuration\ConfigurationResolver;
use Aws\Exception\CredentialsException;
use Aws\Signin\SigninClient;
use Aws\Signin\Exception\SigninException;
use GuzzleHttp\Promise;
/**
* Credential provider for login using console credentials
*/
final class LoginCredentialProvider
{
private const EXT_OPENSSL = 'openssl';
private const DEFAULT_REFRESH_THRESHOLD = 180; // 3 minutes
private const ENV_CACHE_DIRECTORY = 'AWS_LOGIN_CACHE_DIRECTORY';
private const DEFAULT_CACHE_DIRECTORY = '/.aws/login/cache';
private const REAUTHENTICATE_MSG = ' Please reauthenticate using `aws login`.';
private const PROFILE_DEFAULT = 'default';
private const PROFILE_SECONDARY = 'profile ';
private const GRANT_TYPE = 'refresh_token';
private const REQUEST_KEY_GRANT_TYPE = 'grantType';
private const REQUEST_KEY_CLIENT_ID = 'clientId';
private const REQUEST_KEY_REFRESH_TOKEN = 'refreshToken';
private const REQUEST_KEY_TOKEN_INPUT = 'tokenInput';
private const RESULT_TOKEN_OUTPUT = 'tokenOutput';
private const RESULT_EXPIRES_IN = 'expiresIn';
private const CLIENT_SIGNATURE_DPOP = 'dpop';
private const KEY_CLIENT_SIGNATURE_VERSION = 'signature_version';
private const KEY_CLIENT_REGION = 'region';
private const KEY_CLIENT_CREDENTIALS = 'credentials';
private const KEY_PROFILE_LOGIN_SESSION = 'login_session';
private const KEY_ACCESS_TOKEN = 'accessToken';
private const KEY_DPOP_KEY = 'dpopKey';
private const KEY_ACCESS_KEY_ID = 'accessKeyId';
private const KEY_SECRET_ACCESS_KEY = 'secretAccessKey';
private const KEY_SESSION_TOKEN = 'sessionToken';
private const KEY_ACCOUNT_ID = 'accountId';
private const KEY_EXPIRES_AT = 'expiresAt';
private const REQUIRED_CACHE_KEYS = [
self::KEY_ACCESS_TOKEN,
self::REQUEST_KEY_CLIENT_ID,
self::REQUEST_KEY_REFRESH_TOKEN,
self::KEY_DPOP_KEY
];
private const REQUIRED_ACCESS_TOKEN_KEYS = [
self::KEY_ACCESS_KEY_ID,
self::KEY_SECRET_ACCESS_KEY,
self::KEY_SESSION_TOKEN,
self::KEY_ACCOUNT_ID,
self::KEY_EXPIRES_AT
];
/** @var string The profile name used for login session configuration */
private string $profileName;
/** @var SigninClient The Signin service client used for token refresh operations */
private SigninClient $client;
/** @var string The file path to the cached token location */
private string $tokenLocation;
/** @var array|null The cached token data including access token, refresh token, and DPoP key */
private ?array $token = null;
/**
* @param string $profileName Profile containing your console login session information
* @param string|null $region Region used for refresh requests. If not provided,
* attempts will be made to resolve a region using
* `AWS_REGION`, then the profile specified for `login`.
*/
public function __construct(
string $profileName,
?string $region = null
) {
if (!extension_loaded(self::EXT_OPENSSL)) {
throw new \RuntimeException(
'The `openssl` extension is required to use Login credentials. '
. 'Please install or enable the `openssl` extension.'
);
}
$this->profileName = $profileName;
$this->client = $this->createSigninClient($profileName, $region);
$this->tokenLocation = $this->resolveTokenLocation($profileName);
}
/**
* Returns a promise that resolves to AWS credentials
*
* This method loads the cached token, refreshes it if necessary,
* and returns AWS credentials sourced from the access token.
*
* @return Promise\PromiseInterface A promise that resolves to a Credentials object
* @throws CredentialsException If re-authentication is required or credentials cannot be loaded
* @throws SigninException If the token refresh fails with a SigninException
*/
public function __invoke(): Promise\PromiseInterface
{
return Promise\Coroutine::of(function () {
$this->token ??= $this->loadToken();
$credentials = $this->token[self::KEY_ACCESS_TOKEN];
if ($this->shouldRefresh($credentials)) {
try {
$credentials = yield from $this->refresh($credentials);
} catch (CredentialsException $e) {
// For specific re-authentication errors, re-throw
throw $e;
} catch (SigninException $e) {
// For SigninException not handled by refresh(), re-throw
throw new CredentialsException(
'Unable to refresh login credentials: ' . $e->getAwsErrorMessage(),
$e->getCode(),
$e
);
} catch (\Exception $e) {
// For other refresh failures, log and continue with existing token
trigger_error(
'Continuing with existing token after refresh failure: ' . $e->getMessage(),
E_USER_NOTICE
);
}
}
yield $credentials;
});
}
/**
* Refreshes the access token using the refresh token and returns new credentials,
* or, if refreshed from another source, returns the externally refreshed credentials.
*
* @param Credentials $currentCredentials The current credentials to refresh
*
* @return \Generator Generator that yields and returns refreshed credentials
* @throws CredentialsException If re-authentication is required due to expired or changed credentials
* @throws SigninException If the token refresh fails with a SigninException
* @throws \Exception For unexpected errors during refresh
*/
private function refresh(Credentials $currentCredentials): \Generator
{
// Check for external refresh
if ($refreshedToken = $this->getExternalRefresh($currentCredentials)) {
$this->token = $refreshedToken;
return $refreshedToken[self::KEY_ACCESS_TOKEN];
}
try {
$refreshed = (yield $this->client->createOAuth2TokenAsync([
self::REQUEST_KEY_TOKEN_INPUT => [
self::REQUEST_KEY_CLIENT_ID => $this->token[self::REQUEST_KEY_CLIENT_ID],
self::REQUEST_KEY_GRANT_TYPE => self::GRANT_TYPE,
self::REQUEST_KEY_REFRESH_TOKEN => $this->token[self::REQUEST_KEY_REFRESH_TOKEN]
],
self::KEY_DPOP_KEY => $this->token[self::KEY_DPOP_KEY]
]))->get(self::RESULT_TOKEN_OUTPUT);
$newCredentials = self::createCredentials(
$refreshed[self::KEY_ACCESS_TOKEN],
time() + $refreshed[self::RESULT_EXPIRES_IN],
$currentCredentials->getAccountId()
);
$this->token[self::KEY_ACCESS_TOKEN] = $newCredentials;
$this->token[self::REQUEST_KEY_REFRESH_TOKEN] = $refreshed[self::REQUEST_KEY_REFRESH_TOKEN];
} catch (\Exception $e) {
throw $this->handleRefreshException($e);
}
try {
$this->writeToCache();
} catch (\JsonException|\RuntimeException $e) {
trigger_error(
'Failed to update credential cache during refresh: ' . $e->getMessage()
. '. Using refreshed credentials in memory.',
E_USER_NOTICE
);
}
return $newCredentials;
}
/**
* Gets externally refreshed token if token has been refreshed from another source.
* If the new token does not need refreshing, returns it.
*
* @param Credentials $currentCredentials Current credentials to compare against
* @return array|null Returns the updated token array if externally refreshed, null otherwise
*/
private function getExternalRefresh(Credentials $currentCredentials): ?array
{
try {
$latestToken = $this->loadToken();
$latestCredentials = $latestToken[self::KEY_ACCESS_TOKEN];
// Refresh token must be different
if ($latestToken[self::REQUEST_KEY_REFRESH_TOKEN]
=== $this->token[self::REQUEST_KEY_REFRESH_TOKEN]
) {
return null;
}
// Expiration must be newer
if ($latestCredentials->getExpiration()
<= $currentCredentials->getExpiration()
) {
return null;
}
// New token should not need refresh itself
if ($this->shouldRefresh($latestCredentials)) {
return null;
}
return $latestToken;
} catch (\Exception $e) {
return null;
}
}
/**
* Writes the updated access token and refresh token to the cache file
*
* @throws \JsonException|\RuntimeException
*/
private function writeToCache(): void
{
$credentials = $this->token[self::KEY_ACCESS_TOKEN];
$updates = [
self::KEY_ACCESS_TOKEN => [
self::KEY_ACCESS_KEY_ID => $credentials->getAccessKeyId(),
self::KEY_SECRET_ACCESS_KEY => $credentials->getSecretKey(),
self::KEY_SESSION_TOKEN => $credentials->getSecurityToken(),
self::KEY_ACCOUNT_ID => $credentials->getAccountId(),
self::KEY_EXPIRES_AT => gmdate('Y-m-d\TH:i:s\Z', $credentials->getExpiration())
],
self::REQUEST_KEY_REFRESH_TOKEN => $this->token[self::REQUEST_KEY_REFRESH_TOKEN]
];
$existing = json_decode(
file_get_contents($this->tokenLocation), true, 512, JSON_THROW_ON_ERROR
);
$merged = array_merge($existing, $updates);
$result = file_put_contents(
$this->tokenLocation,
json_encode($merged, JSON_THROW_ON_ERROR),
LOCK_EX
);
if (!$result) {
throw new \RuntimeException('Failed to write cache file');
}
}
/**
* Loads and validates the token from the cache file
*
* @return array The loaded token data with Credentials object, DPoP key, and other fields
* @throws CredentialsException If the cache file is invalid, missing required keys,
* or DPoP key cannot be loaded
*/
private function loadToken(): array
{
try {
$cached = json_decode(
file_get_contents($this->tokenLocation),
true, 512, JSON_THROW_ON_ERROR
);
} catch (\JsonException $e) {
throw new CredentialsException(
'Invalid JSON in cache file: ' . $e->getMessage(),
0,
$e
);
}
if (self::hasAllRequiredKeys($cached, self::REQUIRED_CACHE_KEYS)
&& self::hasAllRequiredKeys(
$cached[self::KEY_ACCESS_TOKEN] ?? [],
self::REQUIRED_ACCESS_TOKEN_KEYS
)
) {
// Convert expiresAt to Unix timestamp
$expiresAt = strtotime($cached[self::KEY_ACCESS_TOKEN][self::KEY_EXPIRES_AT]);
if ($expiresAt === false) {
throw new CredentialsException(
'Invalid expiration date format in cached token `'
. self::KEY_EXPIRES_AT . '` field.' . self::REAUTHENTICATE_MSG
);
}
$cached[self::KEY_ACCESS_TOKEN] = self::createCredentials(
$cached[self::KEY_ACCESS_TOKEN],
$expiresAt,
$cached[self::KEY_ACCESS_TOKEN][self::KEY_ACCOUNT_ID]
);
// Load DPoP key
$cached[self::KEY_DPOP_KEY] = openssl_pkey_get_private($cached[self::KEY_DPOP_KEY]);
if ($cached[self::KEY_DPOP_KEY] === false) {
$error = openssl_error_string();
throw new CredentialsException(
'Failed to load DPoP private key from cached token for profile '
. "{$this->profileName}: " . ($error ? ": {$error}" : '.')
. self::REAUTHENTICATE_MSG
);
}
return $cached;
}
throw new CredentialsException(
'Missing required keys in cached token for profile '
. $this->profileName . '.' . self::REAUTHENTICATE_MSG
);
}
/**
* @param Credentials $credentials The credentials to check for expiration
*
* @return bool True if the token expires within the refresh threshold
*/
private function shouldRefresh(Credentials $credentials): bool
{
return ($credentials->getExpiration() - time()) <= self::DEFAULT_REFRESH_THRESHOLD;
}
/**
* Handles exceptions thrown during token refresh
*
* @param \Exception $e The exception thrown during refresh
*
* @return \Exception The exception to be thrown (either transformed or original)
*/
private function handleRefreshException(\Exception $e): \Exception
{
if ($e instanceof SigninException) {
trigger_error(
'Failed to refresh login credentials: ' . $e->getAwsErrorMessage(),
E_USER_NOTICE
);
if ($e->getAwsErrorCode() === 'AccessDeniedException') {
$error = strtolower($e->get('error'));
switch ($error) {
case 'token_expired':
return new CredentialsException(
'Your session has expired.' . self::REAUTHENTICATE_MSG,
0,
$e
);
case 'user_credentials_changed':
return new CredentialsException(
'Unable to refresh credentials because of a change in your password. '
. 'Please reauthenticate with your new password.',
0,
$e
);
case 'insufficient_permissions':
return new CredentialsException(
'Unable to refresh credentials due to insufficient permissions. '
. 'You may be missing permission for the `CreateOAuth2Token` action.',
0,
$e
);
}
}
return $e;
}
// For all other exceptions
trigger_error(
'Unexpected error refreshing login credentials: ' . $e->getMessage(),
E_USER_NOTICE
);
return $e;
}
/**
* Resolves the cache file location for the given profile
*
* @param string $profileName The profile name to resolve the token location for
*
* @return string The full path to the cache file
* @throws CredentialsException If the profile doesn't exist, lacks login_session,
* or cache file is not readable
*/
private function resolveTokenLocation(string $profileName): string
{
$configFile = CredentialProvider::getConfigFileName();
if (!is_readable($configFile)) {
throw new CredentialsException(
'Unable to load configuration file at ' . $configFile
. '. Please ensure the file exists at the specified location.'
);
}
// Ensure profile and session are set
$profiles = CredentialProvider::loadProfiles($configFile);
if ($profileName === self::PROFILE_DEFAULT) {
$profileData = $profiles[self::PROFILE_DEFAULT] ?? null;
} elseif (str_starts_with($profileName, self::PROFILE_SECONDARY)) {
$profileData = $profiles[$profileName] ?? null;
} else {
// Try without prefix first, then with prefix
$profileData = $profiles[$profileName]
?? $profiles[self::PROFILE_SECONDARY . $profileName]
?? null;
}
if (!$profileData) {
throw new CredentialsException(
"Profile '{$profileName}' does not exist. "
. "Please ensure the specified profile is set at {$configFile}."
);
}
if (empty($session = $profileData[self::KEY_PROFILE_LOGIN_SESSION] ?? null)) {
throw new CredentialsException(
"Profile '{$profileName}' did not contain a "
. self::KEY_PROFILE_LOGIN_SESSION . " value. "
. 're-authentication using `aws login` may be needed.'
);
}
// Resolve location and ensure it exists
$cacheDirectory = getenv(self::ENV_CACHE_DIRECTORY)
?: CredentialProvider::getHomeDir() . self::DEFAULT_CACHE_DIRECTORY;
$cacheFile = $cacheDirectory . DIRECTORY_SEPARATOR . hash('sha256', trim($session)) . '.json';
if (!@is_readable($cacheFile)) {
throw new CredentialsException(
"Failed to load cached credentials for profile "
. "'{$profileName}'." . self::REAUTHENTICATE_MSG
);
}
return $cacheFile;
}
/**
* Creates a SigninClient configured for DPoP authentication
*
* @param string $profile
* @param string|null $region The AWS region for the Signin service
*
* @return SigninClient A configured SigninClient instance with DPoP signature version
*/
private function createSigninClient(string $profile, ?string $region): SigninClient
{
$resolvedRegion = $region
?? ConfigurationResolver::env(self::KEY_CLIENT_REGION)
?? ConfigurationResolver::ini(self::KEY_CLIENT_REGION, 'string', $profile)
?? ConfigurationResolver::ini(
self::KEY_CLIENT_REGION,
'string',
self::PROFILE_SECONDARY . $profile
);
if (empty($resolvedRegion)) {
throw new CredentialsException(
'Unable to determine region for the Sign-In service client '
. ' used for refreshing Login credentials. You can provide a region in-code '
. 'when constructing the provider, by setting the AWS_REGION environment variable'
. ', or by setting a `region` in your specified profile.'
);
}
return new SigninClient([
self::KEY_CLIENT_REGION => $resolvedRegion,
self::KEY_CLIENT_SIGNATURE_VERSION => self::CLIENT_SIGNATURE_DPOP,
self::KEY_CLIENT_CREDENTIALS => false
]);
}
/**
* Creates a Credentials object from token data
*
* @param array $tokenData The token data containing access key, secret, and session token
* @param int $expiration Unix timestamp for credential expiration
* @param string $accountId The AWS account ID
*
* @return Credentials The created Credentials object
*/
private static function createCredentials(
array $tokenData,
int $expiration,
string $accountId
): Credentials
{
return new Credentials(
$tokenData[self::KEY_ACCESS_KEY_ID],
$tokenData[self::KEY_SECRET_ACCESS_KEY],
$tokenData[self::KEY_SESSION_TOKEN],
$expiration,
$accountId,
CredentialSources::PROFILE_LOGIN
);
}
/**
* Checks if all required keys are present and non-empty in the data array
*
* @param array $data The data array to check
* @param array $requiredKeys The list of keys that must be present and non-empty
*
* @return bool True if all required keys are present and non-empty, false otherwise
*/
private static function hasAllRequiredKeys(
array $data,
array $requiredKeys
): bool
{
foreach ($requiredKeys as $key) {
if (empty($data[$key])) {
return false;
}
}
return true;
}
}