Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/Token/TokenProvider.php

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