Debian Codegraph @

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

raw symbols SCIP
1 <?php
2 namespace Aws\Credentials;
3
4 use Aws;
5 use Aws\Api\DateTimeResult;
6 use Aws\CacheInterface;
7 use Aws\Exception\CredentialsException;
8 use Aws\Sts\StsClient;
9 use GuzzleHttp\Promise;
10 /**
11 * Credential providers are functions that accept no arguments and return a
12 * promise that is fulfilled with an {@see \Aws\Credentials\CredentialsInterface}
13 * or rejected with an {@see \Aws\Exception\CredentialsException}.
14 *
15 * <code>
16 * use Aws\Credentials\CredentialProvider;
17 * $provider = CredentialProvider::defaultProvider();
18 * // Returns a CredentialsInterface or throws.
19 * $creds = $provider()->wait();
20 * </code>
21 *
22 * Credential providers can be composed to create credentials using conditional
23 * logic that can create different credentials in different environments. You
24 * can compose multiple providers into a single provider using
25 * {@see Aws\Credentials\CredentialProvider::chain}. This function accepts
26 * providers as variadic arguments and returns a new function that will invoke
27 * each provider until a successful set of credentials is returned.
28 *
29 * <code>
30 * // First try an INI file at this location.
31 * $a = CredentialProvider::ini(null, '/path/to/file.ini');
32 * // Then try an INI file at this location.
33 * $b = CredentialProvider::ini(null, '/path/to/other-file.ini');
34 * // Then try loading from environment variables.
35 * $c = CredentialProvider::env();
36 * // Combine the three providers together.
37 * $composed = CredentialProvider::chain($a, $b, $c);
38 * // Returns a promise that is fulfilled with credentials or throws.
39 * $promise = $composed();
40 * // Wait on the credentials to resolve.
41 * $creds = $promise->wait();
42 * </code>
43 */
44 class CredentialProvider
45 {
46 public const ENV_ARN = 'AWS_ROLE_ARN';
47 public const ENV_KEY = 'AWS_ACCESS_KEY_ID';
48 public const ENV_PROFILE = 'AWS_PROFILE';
49 public const ENV_ROLE_SESSION_NAME = 'AWS_ROLE_SESSION_NAME';
50 public const ENV_SECRET = 'AWS_SECRET_ACCESS_KEY';
51 public const ENV_ACCOUNT_ID = 'AWS_ACCOUNT_ID';
52 public const ENV_SESSION = 'AWS_SESSION_TOKEN';
53 public const ENV_TOKEN_FILE = 'AWS_WEB_IDENTITY_TOKEN_FILE';
54 public const ENV_SHARED_CREDENTIALS_FILE = 'AWS_SHARED_CREDENTIALS_FILE';
55 public const ENV_CONFIG_FILE = 'AWS_CONFIG_FILE';
56 public const ENV_REGION = 'AWS_REGION';
57 public const FALLBACK_REGION = 'us-east-1';
58 public const REFRESH_WINDOW = 60;
59
60 /**
61 * Create a default credential provider that
62 * first checks for environment variables,
63 * then checks for assumed role via web identity,
64 * then checks for cached SSO credentials from the CLI,
65 * then check for credential_process in the "default" profile in ~/.aws/credentials,
66 * then checks for the "default" profile in ~/.aws/credentials,
67 * then for credential_process in the "default profile" profile in ~/.aws/config,
68 * then checks for "profile default" profile in ~/.aws/config (which is
69 * the default profile of AWS CLI),
70 * then tries to make a GET Request to fetch credentials if ECS environment variable is presented,
71 * finally checks for EC2 instance profile credentials.
72 *
73 * This provider is automatically wrapped in a memoize function that caches
74 * previously provided credentials.
75 *
76 * @param array $config Optional array of ecs/instance profile credentials
77 * provider options.
78 *
79 * @return callable
80 */
81 public static function defaultProvider(array $config = [])
82 {
83 $cacheable = [
84 'web_identity',
85 'sso',
86 'login',
87 'process_credentials',
88 'process_config',
89 'ecs',
90 'instance'
91 ];
92
93 $profileName = getenv(self::ENV_PROFILE) ?: 'default';
94
95 $defaultChain = [
96 'env' => self::env(),
97 'web_identity' => self::assumeRoleWithWebIdentityCredentialProvider($config),
98 ];
99 if (!isset($config['use_aws_shared_config_files'])
100 || $config['use_aws_shared_config_files'] !== false
101 ) {
102 $defaultChain['sso'] = self::sso(
103 $profileName,
104 self::getConfigFileName(),
105 $config
106 );
107 $defaultChain['login'] = self::login($profileName, $config);
108 $defaultChain['process_credentials'] = self::process();
109 $defaultChain['ini'] = self::ini(null, null, $config);
110 $defaultChain['process_config'] = self::process(
111 'profile ' . $profileName,
112 self::getConfigFileName()
113 );
114 $defaultChain['ini_config'] = self::ini(
115 'profile '. $profileName,
116 self::getConfigFileName()
117 );
118 }
119
120 if (self::shouldUseEcs()) {
121 $defaultChain['ecs'] = self::ecsCredentials($config);
122 } else {
123 $defaultChain['instance'] = self::instanceProfile($config);
124 }
125
126 if (isset($config['credentials'])
127 && $config['credentials'] instanceof CacheInterface
128 ) {
129 foreach ($cacheable as $provider) {
130 if (isset($defaultChain[$provider])) {
131 $defaultChain[$provider] = self::cache(
132 $defaultChain[$provider],
133 $config['credentials'],
134 'aws_cached_' . $provider . '_credentials'
135 );
136 }
137 }
138 }
139
140 return self::memoize(
141 call_user_func_array(
142 [CredentialProvider::class, 'chain'],
143 array_values($defaultChain)
144 )
145 );
146 }
147
148 /**
149 * Create a credential provider function from a set of static credentials.
150 *
151 * @param CredentialsInterface $creds
152 *
153 * @return callable
154 */
155 public static function fromCredentials(CredentialsInterface $creds)
156 {
157 $promise = Promise\Create::promiseFor($creds);
158
159 return function () use ($promise) {
160 return $promise;
161 };
162 }
163
164 /**
165 * Creates an aggregate credentials provider that invokes the provided
166 * variadic providers one after the other until a provider returns
167 * credentials.
168 *
169 * @return callable
170 */
171 public static function chain()
172 {
173 $links = func_get_args();
174 if (empty($links)) {
175 throw new \InvalidArgumentException('No providers in chain');
176 }
177
178 return function ($previousCreds = null) use ($links) {
179 /** @var callable $parent */
180 $parent = array_shift($links);
181 $promise = $parent();
182 while ($next = array_shift($links)) {
183 if ($next instanceof InstanceProfileProvider
184 && $previousCreds instanceof Credentials
185 ) {
186 $promise = $promise->otherwise(
187 function () use ($next, $previousCreds) {return $next($previousCreds);}
188 );
189 } else {
190 $promise = $promise->otherwise($next);
191 }
192 }
193 return $promise;
194 };
195 }
196
197 /**
198 * Wraps a credential provider and caches previously provided credentials.
199 *
200 * Ensures that cached credentials are refreshed when they expire.
201 *
202 * @param callable $provider Credentials provider function to wrap.
203 *
204 * @return callable
205 */
206 public static function memoize(callable $provider)
207 {
208 return function () use ($provider) {
209 static $result;
210 static $isConstant;
211
212 // Constant credentials will be returned constantly.
213 if ($isConstant) {
214 return $result;
215 }
216
217 // Create the initial promise that will be used as the cached value
218 // until it expires.
219 if (null === $result) {
220 $result = $provider();
221 }
222
223 // Return credentials that could expire and refresh when needed.
224 return $result
225 ->then(function (CredentialsInterface $creds) use ($provider, &$isConstant, &$result) {
226 // Determine if these are constant credentials.
227 if (!$creds->getExpiration()) {
228 $isConstant = true;
229 return $creds;
230 }
231
232 // Check if credentials are expired or will expire in 1 minute
233 $needsRefresh = $creds->getExpiration() - time() <= self::REFRESH_WINDOW;
234
235 // Refresh if expired or expiring soon
236 if (!$needsRefresh && !$creds->isExpired()) {
237 return $creds;
238 }
239
240 // Refresh the result and forward the promise.
241 return $result = $provider($creds);
242 })
243 ->otherwise(function($reason) use (&$result) {
244 // Cleanup rejected promise.
245 $result = null;
246 return new Promise\RejectedPromise($reason);
247 });
248 };
249 }
250
251 /**
252 * Wraps a credential provider and saves provided credentials in an
253 * instance of Aws\CacheInterface. Forwards calls when no credentials found
254 * in cache and updates cache with the results.
255 *
256 * @param callable $provider Credentials provider function to wrap
257 * @param CacheInterface $cache Cache to store credentials
258 * @param string|null $cacheKey (optional) Cache key to use
259 *
260 * @return callable
261 */
262 public static function cache(
263 callable $provider,
264 CacheInterface $cache,
265 $cacheKey = null
266 ) {
267 $cacheKey = $cacheKey ?: 'aws_cached_credentials';
268
269 return function () use ($provider, $cache, $cacheKey) {
270 $found = $cache->get($cacheKey);
271 if ($found instanceof CredentialsInterface && !$found->isExpired()) {
272 return Promise\Create::promiseFor($found);
273 }
274
275 return $provider()
276 ->then(function (CredentialsInterface $creds) use (
277 $cache,
278 $cacheKey
279 ) {
280 $cache->set(
281 $cacheKey,
282 $creds,
283 null === $creds->getExpiration() ?
284 0 : $creds->getExpiration() - time()
285 );
286
287 return $creds;
288 });
289 };
290 }
291
292 /**
293 * Provider that creates credentials from environment variables
294 * AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN.
295 *
296 * @return callable
297 */
298 public static function env()
299 {
300 return function () {
301 // Use credentials from environment variables, if available
302 $key = getenv(self::ENV_KEY);
303 $secret = getenv(self::ENV_SECRET);
304 $accountId = getenv(self::ENV_ACCOUNT_ID) ?: null;
305 $token = getenv(self::ENV_SESSION) ?: null;
306
307 if ($key && $secret) {
308 return Promise\Create::promiseFor(
309 new Credentials(
310 $key,
311 $secret,
312 $token,
313 null,
314 $accountId,
315 CredentialSources::ENVIRONMENT
316 )
317 );
318 }
319
320 return self::reject('Could not find environment variable '
321 . 'credentials in ' . self::ENV_KEY . '/' . self::ENV_SECRET);
322 };
323 }
324
325 /**
326 * Credential provider that creates credentials using instance profile
327 * credentials.
328 *
329 * @param array $config Array of configuration data.
330 *
331 * @return InstanceProfileProvider
332 * @see Aws\Credentials\InstanceProfileProvider for $config details.
333 */
334 public static function instanceProfile(array $config = [])
335 {
336 return new InstanceProfileProvider($config);
337 }
338
339 /**
340 * Credential provider that retrieves cached SSO credentials from the CLI
341 *
342 * @return callable
343 */
344 public static function sso(
345 $ssoProfileName = 'default',
346 $filename = null,
347 $config = []
348 ) {
349 $filename = $filename ?? self::getConfigFileName();
350
351 return function () use ($ssoProfileName, $filename, $config) {
352 if (!@is_readable($filename)) {
353 return self::reject("Cannot read credentials from $filename");
354 }
355 $profiles = self::loadProfiles($filename);
356
357 if (isset($profiles[$ssoProfileName])) {
358 $ssoProfile = $profiles[$ssoProfileName];
359 } elseif (isset($profiles['profile ' . $ssoProfileName])) {
360 $ssoProfileName = 'profile ' . $ssoProfileName;
361 $ssoProfile = $profiles[$ssoProfileName];
362 } else {
363 return self::reject("Profile {$ssoProfileName} does not exist in {$filename}.");
364 }
365
366 if (!empty($ssoProfile['sso_session'])) {
367 return CredentialProvider::getSsoCredentials($profiles, $ssoProfileName, $filename, $config);
368 } else {
369 return CredentialProvider::getSsoCredentialsLegacy($profiles, $ssoProfileName, $filename, $config);
370 }
371 };
372 }
373
374 /**
375 * Credential provider that creates credentials using
376 * ecs credentials by a GET request, whose uri is specified
377 * by environment variable
378 *
379 * @param array $config Array of configuration data.
380 *
381 * @return EcsCredentialProvider
382 * @see Aws\Credentials\EcsCredentialProvider for $config details.
383 */
384 public static function ecsCredentials(array $config = [])
385 {
386 return new EcsCredentialProvider($config);
387 }
388
389 /**
390 * Credential provider that creates credentials using assume role
391 *
392 * @param array $config Array of configuration data
393 * @return callable
394 * @see Aws\Credentials\AssumeRoleCredentialProvider for $config details.
395 */
396 public static function assumeRole(array $config=[])
397 {
398 return new AssumeRoleCredentialProvider($config);
399 }
400
401 /**
402 * Credential provider that creates credentials by assuming role from a
403 * Web Identity Token
404 *
405 * @param array $config Array of configuration data
406 * @return callable
407 * @see Aws\Credentials\AssumeRoleWithWebIdentityCredentialProvider for
408 * $config details.
409 */
410 public static function assumeRoleWithWebIdentityCredentialProvider(array $config = [])
411 {
412 return function () use ($config) {
413 $arnFromEnv = getenv(self::ENV_ARN);
414 $tokenFromEnv = getenv(self::ENV_TOKEN_FILE);
415 $stsClient = isset($config['stsClient'])
416 ? $config['stsClient']
417 : null;
418 $region = isset($config['region'])
419 ? $config['region']
420 : null;
421
422 if ($tokenFromEnv && $arnFromEnv) {
423 $sessionName = getenv(self::ENV_ROLE_SESSION_NAME)
424 ? getenv(self::ENV_ROLE_SESSION_NAME)
425 : null;
426 $provider = new AssumeRoleWithWebIdentityCredentialProvider([
427 'RoleArn' => $arnFromEnv,
428 'WebIdentityTokenFile' => $tokenFromEnv,
429 'SessionName' => $sessionName,
430 'client' => $stsClient,
431 'region' => $region,
432 'source' => CredentialSources::ENVIRONMENT_STS_WEB_ID_TOKEN
433 ]);
434
435 return $provider();
436 }
437
438 $profileName = getenv(self::ENV_PROFILE) ?: 'default';
439 if (isset($config['filename'])) {
440 $profiles = self::loadProfiles($config['filename']);
441 } else {
442 $profiles = self::loadDefaultProfiles();
443 }
444
445 if (isset($profiles[$profileName])) {
446 $profile = $profiles[$profileName];
447 if (isset($profile['region'])) {
448 $region = $profile['region'];
449 }
450 if (isset($profile['web_identity_token_file'])
451 && isset($profile['role_arn'])
452 ) {
453 $sessionName = isset($profile['role_session_name'])
454 ? $profile['role_session_name']
455 : null;
456 $provider = new AssumeRoleWithWebIdentityCredentialProvider([
457 'RoleArn' => $profile['role_arn'],
458 'WebIdentityTokenFile' => $profile['web_identity_token_file'],
459 'SessionName' => $sessionName,
460 'client' => $stsClient,
461 'region' => $region,
462 'source' => CredentialSources::PROFILE_STS_WEB_ID_TOKEN
463 ]);
464
465 return $provider();
466 }
467 } else {
468 return self::reject("Unknown profile: $profileName");
469 }
470 return self::reject("No RoleArn or WebIdentityTokenFile specified");
471 };
472 }
473
474 /**
475 * Credentials provider that creates credentials using an ini file stored
476 * in the current user's home directory. A source can be provided
477 * in this file for assuming a role using the credential_source config option.
478 *
479 * @param string|null $profile Profile to use. If not specified will use
480 * the "default" profile in "~/.aws/credentials".
481 * @param string|null $filename If provided, uses a custom filename rather
482 * than looking in the home directory.
483 * @param array|null $config If provided, may contain the following:
484 * preferStaticCredentials: If true, prefer static
485 * credentials to role_arn if both are present
486 * disableAssumeRole: If true, disable support for
487 * roles that assume an IAM role. If true and role profile
488 * is selected, an error is raised.
489 * stsClient: StsClient used to assume role specified in profile
490 *
491 * @return callable
492 */
493 public static function ini($profile = null, $filename = null, array $config = [])
494 {
495 $filename = self::getCredentialsFileName($filename);
496 $profile = $profile ?: (getenv(self::ENV_PROFILE) ?: 'default');
497
498 return function () use ($profile, $filename, $config) {
499 $preferStaticCredentials = $config['preferStaticCredentials'] ?? false;
500 $disableAssumeRole = $config['disableAssumeRole'] ?? false;
501 $stsClient = $config['stsClient'] ?? null;
502
503 if (!@is_readable($filename)) {
504 return self::reject("Cannot read credentials from $filename");
505 }
506 $data = self::loadProfiles($filename);
507 if ($data === false) {
508 return self::reject("Invalid credentials file: $filename");
509 }
510 if (!isset($data[$profile])) {
511 return self::reject("'$profile' not found in credentials file");
512 }
513
514 /*
515 In the CLI, the presence of both a role_arn and static credentials have
516 different meanings depending on how many profiles have been visited. For
517 the first profile processed, role_arn takes precedence over any static
518 credentials, but for all subsequent profiles, static credentials are
519 used if present, and only in their absence will the profile's
520 source_profile and role_arn keys be used to load another set of
521 credentials. This bool is intended to yield compatible behaviour in this
522 sdk.
523 */
524 $preferStaticCredentialsToRoleArn = ($preferStaticCredentials
525 && isset($data[$profile]['aws_access_key_id'])
526 && isset($data[$profile]['aws_secret_access_key']));
527
528 if (isset($data[$profile]['role_arn'])
529 && !$preferStaticCredentialsToRoleArn
530 ) {
531 if ($disableAssumeRole) {
532 return self::reject(
533 "Role assumption profiles are disabled. "
534 . "Failed to load profile " . $profile);
535 }
536 return self::loadRoleProfile(
537 $data,
538 $profile,
539 $filename,
540 $stsClient,
541 $config
542 );
543 }
544
545 if (!isset($data[$profile]['aws_access_key_id'])
546 || !isset($data[$profile]['aws_secret_access_key'])
547 ) {
548 return self::reject("No credentials present in INI profile "
549 . "'$profile' ($filename)");
550 }
551
552 if (empty($data[$profile]['aws_session_token'])) {
553 $data[$profile]['aws_session_token']
554 = isset($data[$profile]['aws_security_token'])
555 ? $data[$profile]['aws_security_token']
556 : null;
557 }
558
559 return Promise\Create::promiseFor(
560 new Credentials(
561 $data[$profile]['aws_access_key_id'],
562 $data[$profile]['aws_secret_access_key'],
563 $data[$profile]['aws_session_token'],
564 null,
565 $data[$profile]['aws_account_id'] ?? null,
566 CredentialSources::PROFILE
567 )
568 );
569 };
570 }
571
572 /**
573 * Credentials provider that creates credentials using a process configured in
574 * ini file stored in the current user's home directory.
575 *
576 * @param string|null $profile Profile to use. If not specified will use
577 * the "default" profile in "~/.aws/credentials".
578 * @param string|null $filename If provided, uses a custom filename rather
579 * than looking in the home directory.
580 *
581 * @return callable
582 */
583 public static function process($profile = null, $filename = null)
584 {
585 $filename = self::getCredentialsFileName($filename);
586 $profile = $profile ?: (getenv(self::ENV_PROFILE) ?: 'default');
587
588 return function () use ($profile, $filename) {
589 if (!@is_readable($filename)) {
590 return self::reject("Cannot read process credentials from $filename");
591 }
592 $data = \Aws\parse_ini_file($filename, true, INI_SCANNER_RAW);
593 if ($data === false) {
594 return self::reject("Invalid credentials file: $filename");
595 }
596 if (!isset($data[$profile])) {
597 return self::reject("'$profile' not found in credentials file");
598 }
599 if (!isset($data[$profile]['credential_process'])) {
600 return self::reject("No credential_process present in INI profile "
601 . "'$profile' ($filename)");
602 }
603
604 $credentialProcess = $data[$profile]['credential_process'];
605 $json = shell_exec($credentialProcess);
606
607 $processData = json_decode($json, true);
608
609 // Only support version 1
610 if (isset($processData['Version'])) {
611 if ($processData['Version'] !== 1) {
612 return self::reject("credential_process does not return Version == 1");
613 }
614 }
615
616 if (!isset($processData['AccessKeyId'])
617 || !isset($processData['SecretAccessKey']))
618 {
619 return self::reject("credential_process does not return valid credentials");
620 }
621
622 if (isset($processData['Expiration'])) {
623 try {
624 $expiration = new DateTimeResult($processData['Expiration']);
625 } catch (\Exception $e) {
626 return self::reject("credential_process returned invalid expiration");
627 }
628 $now = new DateTimeResult();
629 if ($expiration < $now) {
630 return self::reject("credential_process returned expired credentials");
631 }
632 $expires = $expiration->getTimestamp();
633 } else {
634 $expires = null;
635 }
636
637 if (empty($processData['SessionToken'])) {
638 $processData['SessionToken'] = null;
639 }
640
641 $accountId = null;
642 if (!empty($processData['AccountId'])) {
643 $accountId = $processData['AccountId'];
644 } elseif (!empty($data[$profile]['aws_account_id'])) {
645 $accountId = $data[$profile]['aws_account_id'];
646 }
647
648 return Promise\Create::promiseFor(
649 new Credentials(
650 $processData['AccessKeyId'],
651 $processData['SecretAccessKey'],
652 $processData['SessionToken'],
653 $expires,
654 $accountId,
655 CredentialSources::PROFILE_PROCESS
656 )
657 );
658 };
659 }
660
661 /**
662 * Login credential provider for AWS local development using console credentials
663 *
664 * @param string|null $profileName profile containing your console login session information
665 * @param array $config region used for refresh requests.
666 * pass `'region' => <your_region>` to configure a region,
667 * otherwise, provider construction falls back to AWS_REGION,
668 * then the profile specified for `login`
669 *
670 * @return callable
671 */
672 public static function login(
673 ?string $profileName = null,
674 array $config = [],
675 ): callable
676 {
677 $resolvedProfile = $profileName ?? getenv(self::ENV_PROFILE) ?: 'default';
678
679 return static function () use ($resolvedProfile, $config) {
680 try {
681 $provider = new LoginCredentialProvider(
682 $resolvedProfile,
683 $config['region'] ?? null
684 );
685 } catch (\Exception $e) {
686 return self::reject(
687 "Failed to initialize login credential provider for profile '{$resolvedProfile}': "
688 . $e->getMessage()
689 );
690 }
691
692 return $provider();
693 };
694 }
695
696 /**
697 * Assumes role for profile that includes role_arn
698 *
699 * @return callable
700 */
701 private static function loadRoleProfile(
702 $profiles,
703 $profileName,
704 $filename,
705 $stsClient,
706 $config = []
707 ) {
708 $roleProfile = $profiles[$profileName];
709 $roleArn = $roleProfile['role_arn'] ?? '';
710 $roleSessionName = $roleProfile['role_session_name']
711 ?? 'aws-sdk-php-' . round(microtime(true) * 1000);
712
713 if (empty($roleProfile['source_profile'])
714 == empty($roleProfile['credential_source'])
715 ) {
716 return self::reject("Either source_profile or credential_source must be set " .
717 "using profile " . $profileName . ", but not both."
718 );
719 }
720
721 $sourceProfileName = "";
722 if (!empty($roleProfile['source_profile'])) {
723 $sourceProfileName = $roleProfile['source_profile'];
724 if (!isset($profiles[$sourceProfileName])) {
725 return self::reject("source_profile " . $sourceProfileName
726 . " using profile " . $profileName . " does not exist"
727 );
728 }
729 if (isset($config['visited_profiles']) &&
730 in_array($roleProfile['source_profile'], $config['visited_profiles'])
731 ) {
732 return self::reject("Circular source_profile reference found.");
733 }
734 $config['visited_profiles'] [] = $roleProfile['source_profile'];
735 } else {
736 if (empty($roleArn)) {
737 return self::reject(
738 "A role_arn must be provided with credential_source in " .
739 "file {$filename} under profile {$profileName} "
740 );
741 }
742 }
743
744 if (empty($stsClient)) {
745 $config['preferStaticCredentials'] = true;
746 $sourceCredentials = null;
747 if (!empty($roleProfile['source_profile'])){
748 $sourceCredentials = call_user_func(
749 CredentialProvider::ini($sourceProfileName, $filename, $config)
750 )->wait();
751 } else {
752 $sourceCredentials = self::getCredentialsFromSource(
753 $profileName,
754 $filename
755 );
756 }
757
758 $region = $profiles[$sourceProfileName]['region']
759 ?? $config['region']
760 ?? getEnv(self::ENV_REGION)
761 ?: null;
762
763 $stsClient = self::createDefaultStsClient($sourceCredentials, $region);
764 }
765
766 $result = $stsClient->assumeRole([
767 'RoleArn' => $roleArn,
768 'RoleSessionName' => $roleSessionName
769 ]);
770 $credentials = $stsClient->createCredentials(
771 $result,
772 CredentialSources::STS_ASSUME_ROLE
773 );
774
775 return Promise\Create::promiseFor($credentials);
776 }
777
778 /**
779 * Gets the environment's HOME directory if available.
780 *
781 * @return null|string
782 */
783 public static function getHomeDir()
784 {
785 // On Linux/Unix-like systems, use the HOME environment variable
786 if ($homeDir = getenv('HOME')) {
787 return $homeDir;
788 }
789
790 // Get the HOMEDRIVE and HOMEPATH values for Windows hosts
791 $homeDrive = getenv('HOMEDRIVE');
792 $homePath = getenv('HOMEPATH');
793
794 return ($homeDrive && $homePath) ? $homeDrive . $homePath : null;
795 }
796
797 /**
798 * Gets profiles from specified $filename, or default ini files.
799 */
800 public static function loadProfiles($filename)
801 {
802 $profileData = \Aws\parse_ini_file($filename, true, INI_SCANNER_RAW);
803
804 // If loading .aws/credentials, also load .aws/config when AWS_SDK_LOAD_NONDEFAULT_CONFIG is set
805 if ($filename === self::getHomeDir() . '/.aws/credentials'
806 && getenv('AWS_SDK_LOAD_NONDEFAULT_CONFIG')
807 ) {
808 $configFilename = self::getConfigFileName();
809 $configProfileData = \Aws\parse_ini_file($configFilename, true, INI_SCANNER_RAW);
810 foreach ($configProfileData as $name => $profile) {
811 // standardize config profile names
812 $name = str_replace('profile ', '', $name);
813 if (!isset($profileData[$name])) {
814 $profileData[$name] = $profile;
815 }
816 }
817 }
818
819 return $profileData;
820 }
821
822 /**
823 * Gets profiles from ~/.aws/credentials and ~/.aws/config ini files
824 */
825 private static function loadDefaultProfiles()
826 {
827 $profiles = [];
828 $credFile = self::getHomeDir() . '/.aws/credentials';
829 $configFile = self::getHomeDir() . '/.aws/config';
830 if (file_exists($credFile)) {
831 $profiles = \Aws\parse_ini_file($credFile, true, INI_SCANNER_RAW);
832 }
833
834 if (file_exists($configFile)) {
835 $configProfileData = \Aws\parse_ini_file($configFile, true, INI_SCANNER_RAW);
836 foreach ($configProfileData as $name => $profile) {
837 // standardize config profile names
838 $name = str_replace('profile ', '', $name);
839 if (!isset($profiles[$name])) {
840 $profiles[$name] = $profile;
841 }
842 }
843 }
844
845 return $profiles;
846 }
847
848 public static function getCredentialsFromSource(
849 $profileName = '',
850 $filename = '',
851 $config = []
852 ) {
853 $data = self::loadProfiles($filename);
854 $credentialSource = !empty($data[$profileName]['credential_source'])
855 ? $data[$profileName]['credential_source']
856 : null;
857 $credentialsPromise = null;
858
859 switch ($credentialSource) {
860 case 'Environment':
861 $credentialsPromise = self::env();
862 break;
863 case 'Ec2InstanceMetadata':
864 $credentialsPromise = self::instanceProfile($config);
865 break;
866 case 'EcsContainer':
867 $credentialsPromise = self::ecsCredentials($config);
868 break;
869 default:
870 throw new CredentialsException(
871 "Invalid credential_source found in config file: {$credentialSource}. Valid inputs "
872 . "include Environment, Ec2InstanceMetadata, and EcsContainer."
873 );
874 }
875
876 $credentialsResult = null;
877 try {
878 $credentialsResult = $credentialsPromise()->wait();
879 } catch (\Exception $reason) {
880 return self::reject(
881 "Unable to successfully retrieve credentials from the source specified in the"
882 . " credentials file: {$credentialSource}; failure message was: "
883 . $reason->getMessage()
884 );
885 }
886 return function () use ($credentialsResult) {
887 return Promise\Create::promiseFor($credentialsResult);
888 };
889 }
890
891 private static function reject($msg)
892 {
893 return new Promise\RejectedPromise(new CredentialsException($msg));
894 }
895
896 /**
897 * Locates shared configuration file by first checking for AWS_CONFIG,
898 * then falling back to the default location. Returns the path of the
899 * resolved configuration file.
900 *
901 * @return string
902 */
903 public static function getConfigFileName(): string
904 {
905 return getenv(self::ENV_CONFIG_FILE) ?: self::getHomeDir() . '/.aws/config';
906 }
907
908 /**
909 * Locates credentials file by first checking for AWS_SHARED_CREDENTIALS_FILE,
910 * then falling back to the default location. Returns the path of the
911 * resolved credentials file.
912 *
913 * @param $filename
914 * @return string
915 */
916 public static function getCredentialsFileName($filename): string
917 {
918 if (!isset($filename)) {
919 $filename = getenv(self::ENV_SHARED_CREDENTIALS_FILE) ?:
920 (self::getHomeDir() . '/.aws/credentials');
921 }
922
923 return $filename;
924 }
925
926 /**
927 * @return boolean
928 */
929 public static function shouldUseEcs()
930 {
931 //Check for relative uri. if not, then full uri.
932 //fall back to server for each as getenv is not thread-safe.
933 return !empty(getenv(EcsCredentialProvider::ENV_URI))
934 || !empty($_SERVER[EcsCredentialProvider::ENV_URI])
935 || !empty(getenv(EcsCredentialProvider::ENV_FULL_URI))
936 || !empty($_SERVER[EcsCredentialProvider::ENV_FULL_URI]);
937 }
938
939 /**
940 * @param $profiles
941 * @param $ssoProfileName
942 * @param $filename
943 * @param $config
944 * @return Promise\PromiseInterface
945 */
946 private static function getSsoCredentials($profiles, $ssoProfileName, $filename, $config)
947 {
948 if (empty($config['ssoOidcClient'])) {
949 $ssoProfile = $profiles[$ssoProfileName];
950 $sessionName = $ssoProfile['sso_session'];
951 if (empty($profiles['sso-session ' . $sessionName])) {
952 return self::reject(
953 "Could not find sso-session {$sessionName} in {$filename}"
954 );
955 }
956 $ssoSession = $profiles['sso-session ' . $ssoProfile['sso_session']];
957 $ssoOidcClient = new Aws\SSOOIDC\SSOOIDCClient([
958 'region' => $ssoSession['sso_region'],
959 'version' => '2019-06-10',
960 'credentials' => false
961 ]);
962 } else {
963 $ssoOidcClient = $config['ssoClient'];
964 }
965
966 $tokenPromise = new Aws\Token\SsoTokenProvider(
967 $ssoProfileName,
968 $filename,
969 $ssoOidcClient
970 );
971 $token = $tokenPromise()->wait();
972 $ssoCredentials = CredentialProvider::getCredentialsFromSsoService(
973 $ssoProfile,
974 $ssoSession['sso_region'],
975 $token->getToken(),
976 $config
977 );
978
979 //Expiration value is returned in epoch milliseconds. Conversion to seconds
980 $expiration = intdiv($ssoCredentials['expiration'], 1000);
981 return Promise\Create::promiseFor(
982 new Credentials(
983 $ssoCredentials['accessKeyId'],
984 $ssoCredentials['secretAccessKey'],
985 $ssoCredentials['sessionToken'],
986 $expiration,
987 $ssoProfile['sso_account_id'],
988 CredentialSources::PROFILE_SSO
989 )
990 );
991 }
992
993 /**
994 * @param $profiles
995 * @param $ssoProfileName
996 * @param $filename
997 * @param $config
998 * @return Promise\PromiseInterface
999 */
1000 private static function getSsoCredentialsLegacy($profiles, $ssoProfileName, $filename, $config)
1001 {
1002 $ssoProfile = $profiles[$ssoProfileName];
1003 if (empty($ssoProfile['sso_start_url'])
1004 || empty($ssoProfile['sso_region'])
1005 || empty($ssoProfile['sso_account_id'])
1006 || empty($ssoProfile['sso_role_name'])
1007 ) {
1008 return self::reject(
1009 "Profile {$ssoProfileName} in {$filename} must contain the following keys: "
1010 . "sso_start_url, sso_region, sso_account_id, and sso_role_name."
1011 );
1012 }
1013 $tokenLocation = self::getHomeDir()
1014 . '/.aws/sso/cache/'
1015 . sha1($ssoProfile['sso_start_url'])
1016 . ".json";
1017
1018 if (!@is_readable($tokenLocation)) {
1019 return self::reject("Unable to read token file at $tokenLocation");
1020 }
1021 $tokenData = json_decode(file_get_contents($tokenLocation), true);
1022 if (empty($tokenData['accessToken']) || empty($tokenData['expiresAt'])) {
1023 return self::reject(
1024 "Token file at {$tokenLocation} must contain an access token and an expiration"
1025 );
1026 }
1027 try {
1028 $expiration = (new DateTimeResult($tokenData['expiresAt']))->getTimestamp();
1029 } catch (\Exception $e) {
1030 return self::reject("Cached SSO credentials returned an invalid expiration");
1031 }
1032 $now = time();
1033 if ($expiration < $now) {
1034 return self::reject("Cached SSO credentials returned expired credentials");
1035 }
1036 $ssoCredentials = CredentialProvider::getCredentialsFromSsoService(
1037 $ssoProfile,
1038 $ssoProfile['sso_region'],
1039 $tokenData['accessToken'],
1040 $config
1041 );
1042 return Promise\Create::promiseFor(
1043 new Credentials(
1044 $ssoCredentials['accessKeyId'],
1045 $ssoCredentials['secretAccessKey'],
1046 $ssoCredentials['sessionToken'],
1047 $expiration,
1048 $ssoProfile['sso_account_id'],
1049 CredentialSources::PROFILE_SSO_LEGACY
1050 )
1051 );
1052 }
1053 /**
1054 * @param array $ssoProfile
1055 * @param string $clientRegion
1056 * @param string $accessToken
1057 * @param array $config
1058 * @return array|null
1059 */
1060 private static function getCredentialsFromSsoService($ssoProfile, $clientRegion, $accessToken, $config)
1061 {
1062 if (empty($config['ssoClient'])) {
1063 $ssoClient = new Aws\SSO\SSOClient([
1064 'region' => $clientRegion,
1065 'version' => '2019-06-10',
1066 'credentials' => false
1067 ]);
1068 } else {
1069 $ssoClient = $config['ssoClient'];
1070 }
1071 $ssoResponse = $ssoClient->getRoleCredentials([
1072 'accessToken' => $accessToken,
1073 'accountId' => $ssoProfile['sso_account_id'],
1074 'roleName' => $ssoProfile['sso_role_name']
1075 ]);
1076
1077 $ssoCredentials = $ssoResponse['roleCredentials'];
1078 return $ssoCredentials;
1079 }
1080
1081 /**
1082 * @param CredentialsInterface $credentials
1083 * @param string|null $region
1084 *
1085 * @return StsClient
1086 */
1087 private static function createDefaultStsClient(
1088 CredentialsInterface|callable $credentials,
1089 ?string $region
1090 ): StsClient
1091 {
1092 if (empty($region)) {
1093 $region = self::FALLBACK_REGION;
1094 trigger_error(
1095 'NOTICE: STS client created without explicit `region` configuration.' . PHP_EOL
1096 . "Defaulting to `{$region}`. This fallback behavior may be removed." . PHP_EOL
1097 . 'To avoid potential disruptions, configure a `region` using one of the following methods:' . PHP_EOL
1098 . '(1) Add `region` to your source profile in ~/.aws/credentials,' . PHP_EOL
1099 . '(2) Pass `region` in the `$config` array when calling the provider,' . PHP_EOL
1100 . '(3) Set the `AWS_REGION` environment variable.' . PHP_EOL
1101 . 'See: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials_assume_role.html#assume-role-with-profile'
1102 . PHP_EOL,
1103 E_USER_NOTICE
1104 );
1105 }
1106
1107 return new StsClient([
1108 'credentials' => $credentials,
1109 'region' => $region
1110 ]);
1111 }
1112 }
1113