TokenProvider.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. <?php
  2. namespace Aws\Token;
  3. use Aws;
  4. use Aws\Api\DateTimeResult;
  5. use Aws\CacheInterface;
  6. use Aws\Exception\TokenException;
  7. use GuzzleHttp\Promise;
  8. /**
  9. * Token providers are functions that accept no arguments and return a
  10. * promise that is fulfilled with an {@see \Aws\Token\TokenInterface}
  11. * or rejected with an {@see \Aws\Exception\TokenException}.
  12. *
  13. * <code>
  14. * use Aws\Token\TokenProvider;
  15. * $provider = TokenProvider::defaultProvider();
  16. * // Returns a TokenInterface or throws.
  17. * $token = $provider()->wait();
  18. * </code>
  19. *
  20. * Token providers can be composed to create a token using conditional
  21. * logic that can create different tokens in different environments. You
  22. * can compose multiple providers into a single provider using
  23. * {@see Aws\Token\TokenProvider::chain}. This function accepts
  24. * providers as variadic arguments and returns a new function that will invoke
  25. * each provider until a token is successfully returned.
  26. */
  27. class TokenProvider
  28. {
  29. use ParsesIniTrait;
  30. const ENV_PROFILE = 'AWS_PROFILE';
  31. /**
  32. * Create a default token provider tha checks for cached a SSO token from
  33. * the CLI
  34. *
  35. * This provider is automatically wrapped in a memoize function that caches
  36. * previously provided tokens.
  37. *
  38. * @param array $config Optional array of token provider options.
  39. *
  40. * @return callable
  41. */
  42. public static function defaultProvider(array $config = [])
  43. {
  44. $cacheable = [
  45. 'sso',
  46. ];
  47. $defaultChain = [];
  48. if (
  49. !isset($config['use_aws_shared_config_files'])
  50. || $config['use_aws_shared_config_files'] !== false
  51. ) {
  52. $profileName = getenv(self::ENV_PROFILE) ?: 'default';
  53. $defaultChain['sso'] = self::sso(
  54. $profileName,
  55. self::getHomeDir() . '/.aws/config',
  56. $config
  57. );
  58. }
  59. if (isset($config['token'])
  60. && $config['token'] instanceof CacheInterface
  61. ) {
  62. foreach ($cacheable as $provider) {
  63. if (isset($defaultChain[$provider])) {
  64. $defaultChain[$provider] = self::cache(
  65. $defaultChain[$provider],
  66. $config['token'],
  67. 'aws_cached_' . $provider . '_token'
  68. );
  69. }
  70. }
  71. }
  72. return self::memoize(
  73. call_user_func_array(
  74. [TokenProvider::class, 'chain'],
  75. array_values($defaultChain)
  76. )
  77. );
  78. }
  79. /**
  80. * Create a token provider function from a static token.
  81. *
  82. * @param TokenInterface $token
  83. *
  84. * @return callable
  85. */
  86. public static function fromToken(TokenInterface $token)
  87. {
  88. $promise = Promise\Create::promiseFor($token);
  89. return function () use ($promise) {
  90. return $promise;
  91. };
  92. }
  93. /**
  94. * Creates an aggregate token provider that invokes the provided
  95. * variadic providers one after the other until a provider returns
  96. * a token.
  97. *
  98. * @return callable
  99. */
  100. public static function chain()
  101. {
  102. $links = func_get_args();
  103. //Common use case for when aws_shared_config_files is false
  104. if (empty($links)) {
  105. return function () {
  106. return Promise\Create::promiseFor(false);
  107. };
  108. }
  109. return function () use ($links) {
  110. /** @var callable $parent */
  111. $parent = array_shift($links);
  112. $promise = $parent();
  113. while ($next = array_shift($links)) {
  114. $promise = $promise->otherwise($next);
  115. }
  116. return $promise;
  117. };
  118. }
  119. /**
  120. * Wraps a token provider and caches a previously provided token.
  121. * Ensures that cached tokens are refreshed when they expire.
  122. *
  123. * @param callable $provider Token provider function to wrap.
  124. * @return callable
  125. */
  126. public static function memoize(callable $provider)
  127. {
  128. return function () use ($provider) {
  129. static $result;
  130. static $isConstant;
  131. // Constant tokens will be returned constantly.
  132. if ($isConstant) {
  133. return $result;
  134. }
  135. // Create the initial promise that will be used as the cached value
  136. // until it expires.
  137. if (null === $result) {
  138. $result = $provider();
  139. }
  140. // Return a token that could expire and refresh when needed.
  141. return $result
  142. ->then(function (TokenInterface $token) use ($provider, &$isConstant, &$result) {
  143. // Determine if the token is constant.
  144. if (!$token->getExpiration()) {
  145. $isConstant = true;
  146. return $token;
  147. }
  148. if (!$token->isExpired()) {
  149. return $token;
  150. }
  151. return $result = $provider();
  152. })
  153. ->otherwise(function($reason) use (&$result) {
  154. // Cleanup rejected promise.
  155. $result = null;
  156. return Promise\Create::promiseFor(null);
  157. });
  158. };
  159. }
  160. /**
  161. * Wraps a token provider and saves provided token in an
  162. * instance of Aws\CacheInterface. Forwards calls when no token found
  163. * in cache and updates cache with the results.
  164. *
  165. * @param callable $provider Token provider function to wrap
  166. * @param CacheInterface $cache Cache to store the token
  167. * @param string|null $cacheKey (optional) Cache key to use
  168. *
  169. * @return callable
  170. */
  171. public static function cache(
  172. callable $provider,
  173. CacheInterface $cache,
  174. $cacheKey = null
  175. ) {
  176. $cacheKey = $cacheKey ?: 'aws_cached_token';
  177. return function () use ($provider, $cache, $cacheKey) {
  178. $found = $cache->get($cacheKey);
  179. if (is_array($found) && isset($found['token'])) {
  180. $foundToken = $found['token'];
  181. if ($foundToken instanceof TokenInterface) {
  182. if (!$foundToken->isExpired()) {
  183. return Promise\Create::promiseFor($foundToken);
  184. }
  185. if (isset($found['refreshMethod']) && is_callable($found['refreshMethod'])) {
  186. return Promise\Create::promiseFor($found['refreshMethod']());
  187. }
  188. }
  189. }
  190. return $provider()
  191. ->then(function (TokenInterface $token) use (
  192. $cache,
  193. $cacheKey
  194. ) {
  195. $cache->set(
  196. $cacheKey,
  197. $token,
  198. null === $token->getExpiration() ?
  199. 0 : $token->getExpiration() - time()
  200. );
  201. return $token;
  202. });
  203. };
  204. }
  205. /**
  206. * Gets profiles from the ~/.aws/config ini file
  207. */
  208. private static function loadDefaultProfiles() {
  209. $profiles = [];
  210. $configFile = self::getHomeDir() . '/.aws/config';
  211. if (file_exists($configFile)) {
  212. $configProfileData = \Aws\parse_ini_file($configFile, true, INI_SCANNER_RAW);
  213. foreach ($configProfileData as $name => $profile) {
  214. // standardize config profile names
  215. $name = str_replace('profile ', '', $name);
  216. if (!isset($profiles[$name])) {
  217. $profiles[$name] = $profile;
  218. }
  219. }
  220. }
  221. return $profiles;
  222. }
  223. private static function reject($msg)
  224. {
  225. return new Promise\RejectedPromise(new TokenException($msg));
  226. }
  227. /**
  228. * Token provider that creates a token from cached sso credentials
  229. *
  230. * @param string $profileName the name of the ini profile name
  231. * @param string $filename the location of the ini file
  232. * @param array $config configuration options
  233. *
  234. * @return SsoTokenProvider
  235. * @see Aws\Token\SsoTokenProvider for $config details.
  236. */
  237. public static function sso($profileName, $filename, $config = [])
  238. {
  239. $ssoClient = isset($config['ssoClient']) ? $config['ssoClient'] : null;
  240. return new SsoTokenProvider($profileName, $filename, $ssoClient);
  241. }
  242. }