| 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 |
|
| 12 |
|
| 13 |
final class LoginCredentialProvider |
| 14 |
{ |
| 15 |
private const EXT_OPENSSL = 'openssl'; |
| 16 |
private const DEFAULT_REFRESH_THRESHOLD = 180; |
| 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 |
|
| 56 |
private string $profileName; |
| 57 |
|
| 58 |
|
| 59 |
private SigninClient $client; |
| 60 |
|
| 61 |
|
| 62 |
private string $tokenLocation; |
| 63 |
|
| 64 |
|
| 65 |
private ?array $token = null; |
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 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 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 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 |
|
| 110 |
throw $e; |
| 111 |
} catch (SigninException $e) { |
| 112 |
|
| 113 |
throw new CredentialsException( |
| 114 |
'Unable to refresh login credentials: ' . $e->getAwsErrorMessage(), |
| 115 |
$e->getCode(), |
| 116 |
$e |
| 117 |
); |
| 118 |
} catch (\Exception $e) { |
| 119 |
|
| 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 |
|
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
private function refresh(Credentials $currentCredentials): \Generator |
| 143 |
{ |
| 144 |
|
| 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 |
|
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
private function getExternalRefresh(Credentials $currentCredentials): ?array |
| 194 |
{ |
| 195 |
try { |
| 196 |
$latestToken = $this->loadToken(); |
| 197 |
$latestCredentials = $latestToken[self::KEY_ACCESS_TOKEN]; |
| 198 |
|
| 199 |
|
| 200 |
if ($latestToken[self::REQUEST_KEY_REFRESH_TOKEN] |
| 201 |
=== $this->token[self::REQUEST_KEY_REFRESH_TOKEN] |
| 202 |
) { |
| 203 |
return null; |
| 204 |
} |
| 205 |
|
| 206 |
|
| 207 |
if ($latestCredentials->getExpiration() |
| 208 |
<= $currentCredentials->getExpiration() |
| 209 |
) { |
| 210 |
return null; |
| 211 |
} |
| 212 |
|
| 213 |
|
| 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 |
|
| 226 |
|
| 227 |
|
| 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 |
|
| 261 |
|
| 262 |
|
| 263 |
|
| 264 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 324 |
|
| 325 |
|
| 326 |
|
| 327 |
private function shouldRefresh(Credentials $credentials): bool |
| 328 |
{ |
| 329 |
return ($credentials->getExpiration() - time()) <= self::DEFAULT_REFRESH_THRESHOLD; |
| 330 |
} |
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
|
| 337 |
|
| 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 |
|
| 377 |
trigger_error( |
| 378 |
'Unexpected error refreshing login credentials: ' . $e->getMessage(), |
| 379 |
E_USER_NOTICE |
| 380 |
); |
| 381 |
|
| 382 |
return $e; |
| 383 |
} |
| 384 |
|
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 448 |
|
| 449 |
|
| 450 |
|
| 451 |
|
| 452 |
|
| 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 |
|
| 483 |
|
| 484 |
|
| 485 |
|
| 486 |
|
| 487 |
|
| 488 |
|
| 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 |
|
| 508 |
|
| 509 |
|
| 510 |
|
| 511 |
|
| 512 |
|
| 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 |
} |