Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/Credentials/LoginCredentialProvider.php

raw symbols SCIP
1 <?php
2 namespace Aws\Credentials;
3
4 use Aws\Configuration\ConfigurationResolver;
5 use Aws\Exception\CredentialsException;
6 use Aws\Signin\SigninClient;
7 use Aws\Signin\Exception\SigninException;
8 use GuzzleHttp\Promise;
9
10 /**
11 * Credential provider for login using console credentials
12 */
13 final class LoginCredentialProvider
14 {
15 private const EXT_OPENSSL = 'openssl';
16 private const DEFAULT_REFRESH_THRESHOLD = 180; // 3 minutes
17 private const ENV_CACHE_DIRECTORY = 'AWS_LOGIN_CACHE_DIRECTORY';
18 private const DEFAULT_CACHE_DIRECTORY = '/.aws/login/cache';
19 private const REAUTHENTICATE_MSG = ' Please reauthenticate using `aws login`.';
20 private const PROFILE_DEFAULT = 'default';
21 private const PROFILE_SECONDARY = 'profile ';
22 private const GRANT_TYPE = 'refresh_token';
23 private const REQUEST_KEY_GRANT_TYPE = 'grantType';
24 private const REQUEST_KEY_CLIENT_ID = 'clientId';
25 private const REQUEST_KEY_REFRESH_TOKEN = 'refreshToken';
26 private const REQUEST_KEY_TOKEN_INPUT = 'tokenInput';
27 private const RESULT_TOKEN_OUTPUT = 'tokenOutput';
28 private const RESULT_EXPIRES_IN = 'expiresIn';
29 private const CLIENT_SIGNATURE_DPOP = 'dpop';
30 private const KEY_CLIENT_SIGNATURE_VERSION = 'signature_version';
31 private const KEY_CLIENT_REGION = 'region';
32 private const KEY_CLIENT_CREDENTIALS = 'credentials';
33 private const KEY_PROFILE_LOGIN_SESSION = 'login_session';
34 private const KEY_ACCESS_TOKEN = 'accessToken';
35 private const KEY_DPOP_KEY = 'dpopKey';
36 private const KEY_ACCESS_KEY_ID = 'accessKeyId';
37 private const KEY_SECRET_ACCESS_KEY = 'secretAccessKey';
38 private const KEY_SESSION_TOKEN = 'sessionToken';
39 private const KEY_ACCOUNT_ID = 'accountId';
40 private const KEY_EXPIRES_AT = 'expiresAt';
41 private const REQUIRED_CACHE_KEYS = [
42 self::KEY_ACCESS_TOKEN,
43 self::REQUEST_KEY_CLIENT_ID,
44 self::REQUEST_KEY_REFRESH_TOKEN,
45 self::KEY_DPOP_KEY
46 ];
47 private const REQUIRED_ACCESS_TOKEN_KEYS = [
48 self::KEY_ACCESS_KEY_ID,
49 self::KEY_SECRET_ACCESS_KEY,
50 self::KEY_SESSION_TOKEN,
51 self::KEY_ACCOUNT_ID,
52 self::KEY_EXPIRES_AT
53 ];
54
55 /** @var string The profile name used for login session configuration */
56 private string $profileName;
57
58 /** @var SigninClient The Signin service client used for token refresh operations */
59 private SigninClient $client;
60
61 /** @var string The file path to the cached token location */
62 private string $tokenLocation;
63
64 /** @var array|null The cached token data including access token, refresh token, and DPoP key */
65 private ?array $token = null;
66
67 /**
68 * @param string $profileName Profile containing your console login session information
69 * @param string|null $region Region used for refresh requests. If not provided,
70 * attempts will be made to resolve a region using
71 * `AWS_REGION`, then the profile specified for `login`.
72 */
73 public function __construct(
74 string $profileName,
75 ?string $region = null
76 ) {
77 if (!extension_loaded(self::EXT_OPENSSL)) {
78 throw new \RuntimeException(
79 'The `openssl` extension is required to use Login credentials. '
80 . 'Please install or enable the `openssl` extension.'
81 );
82 }
83
84 $this->profileName = $profileName;
85 $this->client = $this->createSigninClient($profileName, $region);
86 $this->tokenLocation = $this->resolveTokenLocation($profileName);
87 }
88
89 /**
90 * Returns a promise that resolves to AWS credentials
91 *
92 * This method loads the cached token, refreshes it if necessary,
93 * and returns AWS credentials sourced from the access token.
94 *
95 * @return Promise\PromiseInterface A promise that resolves to a Credentials object
96 * @throws CredentialsException If re-authentication is required or credentials cannot be loaded
97 * @throws SigninException If the token refresh fails with a SigninException
98 */
99 public function __invoke(): Promise\PromiseInterface
100 {
101 return Promise\Coroutine::of(function () {
102 $this->token ??= $this->loadToken();
103 $credentials = $this->token[self::KEY_ACCESS_TOKEN];
104
105 if ($this->shouldRefresh($credentials)) {
106 try {
107 $credentials = yield from $this->refresh($credentials);
108 } catch (CredentialsException $e) {
109 // For specific re-authentication errors, re-throw
110 throw $e;
111 } catch (SigninException $e) {
112 // For SigninException not handled by refresh(), re-throw
113 throw new CredentialsException(
114 'Unable to refresh login credentials: ' . $e->getAwsErrorMessage(),
115 $e->getCode(),
116 $e
117 );
118 } catch (\Exception $e) {
119 // For other refresh failures, log and continue with existing token
120 trigger_error(
121 'Continuing with existing token after refresh failure: ' . $e->getMessage(),
122 E_USER_NOTICE
123 );
124 }
125 }
126
127 yield $credentials;
128 });
129 }
130
131 /**
132 * Refreshes the access token using the refresh token and returns new credentials,
133 * or, if refreshed from another source, returns the externally refreshed credentials.
134 *
135 * @param Credentials $currentCredentials The current credentials to refresh
136 *
137 * @return \Generator Generator that yields and returns refreshed credentials
138 * @throws CredentialsException If re-authentication is required due to expired or changed credentials
139 * @throws SigninException If the token refresh fails with a SigninException
140 * @throws \Exception For unexpected errors during refresh
141 */
142 private function refresh(Credentials $currentCredentials): \Generator
143 {
144 // Check for external refresh
145 if ($refreshedToken = $this->getExternalRefresh($currentCredentials)) {
146 $this->token = $refreshedToken;
147
148 return $refreshedToken[self::KEY_ACCESS_TOKEN];
149 }
150
151 try {
152 $refreshed = (yield $this->client->createOAuth2TokenAsync([
153 self::REQUEST_KEY_TOKEN_INPUT => [
154 self::REQUEST_KEY_CLIENT_ID => $this->token[self::REQUEST_KEY_CLIENT_ID],
155 self::REQUEST_KEY_GRANT_TYPE => self::GRANT_TYPE,
156 self::REQUEST_KEY_REFRESH_TOKEN => $this->token[self::REQUEST_KEY_REFRESH_TOKEN]
157 ],
158 self::KEY_DPOP_KEY => $this->token[self::KEY_DPOP_KEY]
159 ]))->get(self::RESULT_TOKEN_OUTPUT);
160
161 $newCredentials = self::createCredentials(
162 $refreshed[self::KEY_ACCESS_TOKEN],
163 time() + $refreshed[self::RESULT_EXPIRES_IN],
164 $currentCredentials->getAccountId()
165 );
166
167 $this->token[self::KEY_ACCESS_TOKEN] = $newCredentials;
168 $this->token[self::REQUEST_KEY_REFRESH_TOKEN] = $refreshed[self::REQUEST_KEY_REFRESH_TOKEN];
169 } catch (\Exception $e) {
170 throw $this->handleRefreshException($e);
171 }
172
173 try {
174 $this->writeToCache();
175 } catch (\JsonException|\RuntimeException $e) {
176 trigger_error(
177 'Failed to update credential cache during refresh: ' . $e->getMessage()
178 . '. Using refreshed credentials in memory.',
179 E_USER_NOTICE
180 );
181 }
182
183 return $newCredentials;
184 }
185
186 /**
187 * Gets externally refreshed token if token has been refreshed from another source.
188 * If the new token does not need refreshing, returns it.
189 *
190 * @param Credentials $currentCredentials Current credentials to compare against
191 * @return array|null Returns the updated token array if externally refreshed, null otherwise
192 */
193 private function getExternalRefresh(Credentials $currentCredentials): ?array
194 {
195 try {
196 $latestToken = $this->loadToken();
197 $latestCredentials = $latestToken[self::KEY_ACCESS_TOKEN];
198
199 // Refresh token must be different
200 if ($latestToken[self::REQUEST_KEY_REFRESH_TOKEN]
201 === $this->token[self::REQUEST_KEY_REFRESH_TOKEN]
202 ) {
203 return null;
204 }
205
206 // Expiration must be newer
207 if ($latestCredentials->getExpiration()
208 <= $currentCredentials->getExpiration()
209 ) {
210 return null;
211 }
212
213 // New token should not need refresh itself
214 if ($this->shouldRefresh($latestCredentials)) {
215 return null;
216 }
217
218 return $latestToken;
219 } catch (\Exception $e) {
220 return null;
221 }
222 }
223
224 /**
225 * Writes the updated access token and refresh token to the cache file
226 *
227 * @throws \JsonException|\RuntimeException
228 */
229 private function writeToCache(): void
230 {
231 $credentials = $this->token[self::KEY_ACCESS_TOKEN];
232 $updates = [
233 self::KEY_ACCESS_TOKEN => [
234 self::KEY_ACCESS_KEY_ID => $credentials->getAccessKeyId(),
235 self::KEY_SECRET_ACCESS_KEY => $credentials->getSecretKey(),
236 self::KEY_SESSION_TOKEN => $credentials->getSecurityToken(),
237 self::KEY_ACCOUNT_ID => $credentials->getAccountId(),
238 self::KEY_EXPIRES_AT => gmdate('Y-m-d\TH:i:s\Z', $credentials->getExpiration())
239 ],
240 self::REQUEST_KEY_REFRESH_TOKEN => $this->token[self::REQUEST_KEY_REFRESH_TOKEN]
241 ];
242
243 $existing = json_decode(
244 file_get_contents($this->tokenLocation), true, 512, JSON_THROW_ON_ERROR
245 );
246 $merged = array_merge($existing, $updates);
247
248 $result = file_put_contents(
249 $this->tokenLocation,
250 json_encode($merged, JSON_THROW_ON_ERROR),
251 LOCK_EX
252 );
253
254 if (!$result) {
255 throw new \RuntimeException('Failed to write cache file');
256 }
257 }
258
259 /**
260 * Loads and validates the token from the cache file
261 *
262 * @return array The loaded token data with Credentials object, DPoP key, and other fields
263 * @throws CredentialsException If the cache file is invalid, missing required keys,
264 * or DPoP key cannot be loaded
265 */
266 private function loadToken(): array
267 {
268 try {
269 $cached = json_decode(
270 file_get_contents($this->tokenLocation),
271 true, 512, JSON_THROW_ON_ERROR
272 );
273 } catch (\JsonException $e) {
274 throw new CredentialsException(
275 'Invalid JSON in cache file: ' . $e->getMessage(),
276 0,
277 $e
278 );
279 }
280
281 if (self::hasAllRequiredKeys($cached, self::REQUIRED_CACHE_KEYS)
282 && self::hasAllRequiredKeys(
283 $cached[self::KEY_ACCESS_TOKEN] ?? [],
284 self::REQUIRED_ACCESS_TOKEN_KEYS
285 )
286 ) {
287 // Convert expiresAt to Unix timestamp
288 $expiresAt = strtotime($cached[self::KEY_ACCESS_TOKEN][self::KEY_EXPIRES_AT]);
289 if ($expiresAt === false) {
290 throw new CredentialsException(
291 'Invalid expiration date format in cached token `'
292 . self::KEY_EXPIRES_AT . '` field.' . self::REAUTHENTICATE_MSG
293 );
294 }
295
296 $cached[self::KEY_ACCESS_TOKEN] = self::createCredentials(
297 $cached[self::KEY_ACCESS_TOKEN],
298 $expiresAt,
299 $cached[self::KEY_ACCESS_TOKEN][self::KEY_ACCOUNT_ID]
300 );
301
302 // Load DPoP key
303 $cached[self::KEY_DPOP_KEY] = openssl_pkey_get_private($cached[self::KEY_DPOP_KEY]);
304 if ($cached[self::KEY_DPOP_KEY] === false) {
305 $error = openssl_error_string();
306 throw new CredentialsException(
307 'Failed to load DPoP private key from cached token for profile '
308 . "{$this->profileName}: " . ($error ? ": {$error}" : '.')
309 . self::REAUTHENTICATE_MSG
310 );
311 }
312
313 return $cached;
314 }
315
316 throw new CredentialsException(
317 'Missing required keys in cached token for profile '
318 . $this->profileName . '.' . self::REAUTHENTICATE_MSG
319 );
320 }
321
322 /**
323 * @param Credentials $credentials The credentials to check for expiration
324 *
325 * @return bool True if the token expires within the refresh threshold
326 */
327 private function shouldRefresh(Credentials $credentials): bool
328 {
329 return ($credentials->getExpiration() - time()) <= self::DEFAULT_REFRESH_THRESHOLD;
330 }
331
332 /**
333 * Handles exceptions thrown during token refresh
334 *
335 * @param \Exception $e The exception thrown during refresh
336 *
337 * @return \Exception The exception to be thrown (either transformed or original)
338 */
339 private function handleRefreshException(\Exception $e): \Exception
340 {
341 if ($e instanceof SigninException) {
342 trigger_error(
343 'Failed to refresh login credentials: ' . $e->getAwsErrorMessage(),
344 E_USER_NOTICE
345 );
346
347 if ($e->getAwsErrorCode() === 'AccessDeniedException') {
348 $error = strtolower($e->get('error'));
349 switch ($error) {
350 case 'token_expired':
351 return new CredentialsException(
352 'Your session has expired.' . self::REAUTHENTICATE_MSG,
353 0,
354 $e
355 );
356 case 'user_credentials_changed':
357 return new CredentialsException(
358 'Unable to refresh credentials because of a change in your password. '
359 . 'Please reauthenticate with your new password.',
360 0,
361 $e
362 );
363 case 'insufficient_permissions':
364 return new CredentialsException(
365 'Unable to refresh credentials due to insufficient permissions. '
366 . 'You may be missing permission for the `CreateOAuth2Token` action.',
367 0,
368 $e
369 );
370 }
371 }
372
373 return $e;
374 }
375
376 // For all other exceptions
377 trigger_error(
378 'Unexpected error refreshing login credentials: ' . $e->getMessage(),
379 E_USER_NOTICE
380 );
381
382 return $e;
383 }
384
385 /**
386 * Resolves the cache file location for the given profile
387 *
388 * @param string $profileName The profile name to resolve the token location for
389 *
390 * @return string The full path to the cache file
391 * @throws CredentialsException If the profile doesn't exist, lacks login_session,
392 * or cache file is not readable
393 */
394 private function resolveTokenLocation(string $profileName): string
395 {
396 $configFile = CredentialProvider::getConfigFileName();
397 if (!is_readable($configFile)) {
398 throw new CredentialsException(
399 'Unable to load configuration file at ' . $configFile
400 . '. Please ensure the file exists at the specified location.'
401 );
402 }
403
404 // Ensure profile and session are set
405 $profiles = CredentialProvider::loadProfiles($configFile);
406 if ($profileName === self::PROFILE_DEFAULT) {
407 $profileData = $profiles[self::PROFILE_DEFAULT] ?? null;
408 } elseif (str_starts_with($profileName, self::PROFILE_SECONDARY)) {
409 $profileData = $profiles[$profileName] ?? null;
410 } else {
411 // Try without prefix first, then with prefix
412 $profileData = $profiles[$profileName]
413 ?? $profiles[self::PROFILE_SECONDARY . $profileName]
414 ?? null;
415 }
416
417 if (!$profileData) {
418 throw new CredentialsException(
419 "Profile '{$profileName}' does not exist. "
420 . "Please ensure the specified profile is set at {$configFile}."
421 );
422 }
423
424 if (empty($session = $profileData[self::KEY_PROFILE_LOGIN_SESSION] ?? null)) {
425 throw new CredentialsException(
426 "Profile '{$profileName}' did not contain a "
427 . self::KEY_PROFILE_LOGIN_SESSION . " value. "
428 . 're-authentication using `aws login` may be needed.'
429 );
430 }
431
432 // Resolve location and ensure it exists
433 $cacheDirectory = getenv(self::ENV_CACHE_DIRECTORY)
434 ?: CredentialProvider::getHomeDir() . self::DEFAULT_CACHE_DIRECTORY;
435 $cacheFile = $cacheDirectory . DIRECTORY_SEPARATOR . hash('sha256', trim($session)) . '.json';
436 if (!@is_readable($cacheFile)) {
437 throw new CredentialsException(
438 "Failed to load cached credentials for profile "
439 . "'{$profileName}'." . self::REAUTHENTICATE_MSG
440 );
441 }
442
443 return $cacheFile;
444 }
445
446 /**
447 * Creates a SigninClient configured for DPoP authentication
448 *
449 * @param string $profile
450 * @param string|null $region The AWS region for the Signin service
451 *
452 * @return SigninClient A configured SigninClient instance with DPoP signature version
453 */
454 private function createSigninClient(string $profile, ?string $region): SigninClient
455 {
456 $resolvedRegion = $region
457 ?? ConfigurationResolver::env(self::KEY_CLIENT_REGION)
458 ?? ConfigurationResolver::ini(self::KEY_CLIENT_REGION, 'string', $profile)
459 ?? ConfigurationResolver::ini(
460 self::KEY_CLIENT_REGION,
461 'string',
462 self::PROFILE_SECONDARY . $profile
463 );
464
465 if (empty($resolvedRegion)) {
466 throw new CredentialsException(
467 'Unable to determine region for the Sign-In service client '
468 . ' used for refreshing Login credentials. You can provide a region in-code '
469 . 'when constructing the provider, by setting the AWS_REGION environment variable'
470 . ', or by setting a `region` in your specified profile.'
471 );
472 }
473
474 return new SigninClient([
475 self::KEY_CLIENT_REGION => $resolvedRegion,
476 self::KEY_CLIENT_SIGNATURE_VERSION => self::CLIENT_SIGNATURE_DPOP,
477 self::KEY_CLIENT_CREDENTIALS => false
478 ]);
479 }
480
481 /**
482 * Creates a Credentials object from token data
483 *
484 * @param array $tokenData The token data containing access key, secret, and session token
485 * @param int $expiration Unix timestamp for credential expiration
486 * @param string $accountId The AWS account ID
487 *
488 * @return Credentials The created Credentials object
489 */
490 private static function createCredentials(
491 array $tokenData,
492 int $expiration,
493 string $accountId
494 ): Credentials
495 {
496 return new Credentials(
497 $tokenData[self::KEY_ACCESS_KEY_ID],
498 $tokenData[self::KEY_SECRET_ACCESS_KEY],
499 $tokenData[self::KEY_SESSION_TOKEN],
500 $expiration,
501 $accountId,
502 CredentialSources::PROFILE_LOGIN
503 );
504 }
505
506 /**
507 * Checks if all required keys are present and non-empty in the data array
508 *
509 * @param array $data The data array to check
510 * @param array $requiredKeys The list of keys that must be present and non-empty
511 *
512 * @return bool True if all required keys are present and non-empty, false otherwise
513 */
514 private static function hasAllRequiredKeys(
515 array $data,
516 array $requiredKeys
517 ): bool
518 {
519 foreach ($requiredKeys as $key) {
520 if (empty($data[$key])) {
521 return false;
522 }
523 }
524
525 return true;
526 }
527 }