AssumeRoleCredentialProvider.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace Aws\Credentials;
  3. use Aws\Exception\AwsException;
  4. use Aws\Exception\CredentialsException;
  5. use Aws\Result;
  6. use Aws\Sts\StsClient;
  7. use GuzzleHttp\Promise;
  8. use GuzzleHttp\Psr7\Request;
  9. use GuzzleHttp\Promise\PromiseInterface;
  10. use GuzzleHttp\Psr7\Response;
  11. use Psr\Http\Message\ResponseInterface;
  12. /**
  13. * Credential provider that provides credentials via assuming a role
  14. * More Information, see: http://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sts-2011-06-15.html#assumerole
  15. */
  16. class AssumeRoleCredentialProvider
  17. {
  18. const ERROR_MSG = "Missing required 'AssumeRoleCredentialProvider' configuration option: ";
  19. /** @var callable */
  20. private $client;
  21. /** @var array */
  22. private $assumeRoleParams;
  23. /**
  24. * The constructor requires following configure parameters:
  25. * - client: a StsClient
  26. * - assume_role_params: Parameters used to make assumeRole call
  27. *
  28. * @param array $config Configuration options
  29. * @throws \InvalidArgumentException
  30. */
  31. public function __construct(array $config = [])
  32. {
  33. if (!isset($config['assume_role_params'])) {
  34. throw new \InvalidArgumentException(self::ERROR_MSG . "'assume_role_params'.");
  35. }
  36. if (!isset($config['client'])) {
  37. throw new \InvalidArgumentException(self::ERROR_MSG . "'client'.");
  38. }
  39. $this->client = $config['client'];
  40. $this->assumeRoleParams = $config['assume_role_params'];
  41. }
  42. /**
  43. * Loads assume role credentials.
  44. *
  45. * @return PromiseInterface
  46. */
  47. public function __invoke()
  48. {
  49. $client = $this->client;
  50. return $client->assumeRoleAsync($this->assumeRoleParams)
  51. ->then(function (Result $result) {
  52. return $this->client->createCredentials($result);
  53. })->otherwise(function (\RuntimeException $exception) {
  54. throw new CredentialsException(
  55. "Error in retrieving assume role credentials.",
  56. 0,
  57. $exception
  58. );
  59. });
  60. }
  61. }