AuthTokenGenerator.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace Aws\Rds;
  3. use Aws\Credentials\CredentialsInterface;
  4. use Aws\Credentials\Credentials;
  5. use Aws\Signature\SignatureV4;
  6. use GuzzleHttp\Psr7\Request;
  7. use GuzzleHttp\Psr7\Uri;
  8. use GuzzleHttp\Promise;
  9. use Aws;
  10. /**
  11. * Generates RDS auth tokens for use with IAM authentication.
  12. */
  13. class AuthTokenGenerator
  14. {
  15. private $credentialProvider;
  16. /**
  17. * The constructor takes an instance of Credentials or a CredentialProvider
  18. *
  19. * @param callable|Credentials $creds
  20. */
  21. public function __construct($creds)
  22. {
  23. if ($creds instanceof CredentialsInterface) {
  24. $promise = new Promise\FulfilledPromise($creds);
  25. $this->credentialProvider = Aws\constantly($promise);
  26. } else {
  27. $this->credentialProvider = $creds;
  28. }
  29. }
  30. /**
  31. * Create the token for database login
  32. *
  33. * @param string $endpoint The database hostname with port number specified
  34. * (e.g., host:port)
  35. * @param string $region The region where the database is located
  36. * @param string $username The username to login as
  37. * @param int $lifetime The lifetime of the token in minutes
  38. *
  39. * @return string Token generated
  40. */
  41. public function createToken($endpoint, $region, $username, $lifetime = 15)
  42. {
  43. if (!is_numeric($lifetime) || $lifetime > 15 || $lifetime <= 0) {
  44. throw new \InvalidArgumentException(
  45. "Lifetime must be a positive number less than or equal to 15, was {$lifetime}",
  46. null
  47. );
  48. }
  49. $uri = new Uri($endpoint);
  50. $uri = $uri->withPath('/');
  51. $uri = $uri->withQuery('Action=connect&DBUser=' . $username);
  52. $request = new Request('GET', $uri);
  53. $signer = new SignatureV4('rds-db', $region);
  54. $provider = $this->credentialProvider;
  55. $url = (string) $signer->presign(
  56. $request,
  57. $provider()->wait(),
  58. '+' . $lifetime . ' minutes'
  59. )->getUri();
  60. // Remove 2 extra slash from the presigned url result
  61. return substr($url, 2);
  62. }
  63. }