EcsRamRoleProvider.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace AlibabaCloud\Credentials\Providers;
  3. use AlibabaCloud\Credentials\Request\Request;
  4. use AlibabaCloud\Credentials\StsCredential;
  5. use Exception;
  6. use GuzzleHttp\Exception\GuzzleException;
  7. use AlibabaCloud\Tea\Response;
  8. use InvalidArgumentException;
  9. use Psr\Http\Message\ResponseInterface;
  10. use RuntimeException;
  11. /**
  12. * Class EcsRamRoleProvider
  13. *
  14. * @package AlibabaCloud\Credentials\Providers
  15. */
  16. class EcsRamRoleProvider extends Provider
  17. {
  18. /**
  19. * Expiration time slot for temporary security credentials.
  20. *
  21. * @var int
  22. */
  23. protected $expirationSlot = 10;
  24. /**
  25. * @var string
  26. */
  27. private $uri = 'http://100.100.100.200/latest/meta-data/ram/security-credentials/';
  28. /**
  29. * Get credential.
  30. *
  31. * @return StsCredential
  32. * @throws Exception
  33. * @throws GuzzleException
  34. */
  35. public function get()
  36. {
  37. $result = $this->getCredentialsInCache();
  38. if ($result === null) {
  39. $result = $this->request();
  40. if (!isset($result['AccessKeyId'], $result['AccessKeySecret'], $result['SecurityToken'])) {
  41. throw new RuntimeException($this->error);
  42. }
  43. $this->cache($result->toArray());
  44. }
  45. return new StsCredential(
  46. $result['AccessKeyId'],
  47. $result['AccessKeySecret'],
  48. strtotime($result['Expiration']),
  49. $result['SecurityToken']
  50. );
  51. }
  52. /**
  53. * Get credentials by request.
  54. *
  55. * @return ResponseInterface
  56. * @throws Exception
  57. * @throws GuzzleException
  58. */
  59. public function request()
  60. {
  61. $credential = $this->credential;
  62. $url = $this->uri . $credential->getRoleName();
  63. $options = [
  64. 'http_errors' => false,
  65. 'timeout' => 1,
  66. 'connect_timeout' => 1,
  67. ];
  68. $result = Request::createClient()->request('GET', $url, $options);
  69. if ($result->getStatusCode() === 404) {
  70. $message = 'The role was not found in the instance';
  71. throw new InvalidArgumentException($message);
  72. }
  73. if ($result->getStatusCode() !== 200) {
  74. throw new RuntimeException('Error retrieving credentials from result: ' . $result->toJson());
  75. }
  76. return $result;
  77. }
  78. }