xp-forge / aws

AWS Core for the XP Framework
0 stars 0 forks source link

Container credential provider #7

Closed thekid closed 3 months ago

thekid commented 3 months ago

Support https://docs.aws.amazon.com/sdkref/latest/guide/feature-container-credentials.html

The container credential provider fetches credentials for customer’s containerized application. This credential provider is useful for Amazon Elastic Container Service (Amazon ECS) and Amazon Elastic Kubernetes Service (Amazon EKS) customers. SDKs attempt to load credentials from the specified HTTP endpoint through a GET request.

API

use com\amazon\aws\{Credentials, CredentialProviders};

$credentials= Credentials::provided(
  CredentialProviders::environment(),
  CredentialProviders::containerService(),
);

Basic implementation

use lang\Environment;
use peer\http\HttpConnection;
use text\json\{Json, StreamInput};

// Check AWS_CONTAINER_CREDENTIALS_*
if (null === ($relative= Environment::variable('AWS_CONTAINER_CREDENTIALS_RELATIVE_URI'))) {
  $uri= Environment::variable('AWS_CONTAINER_CREDENTIALS_FULL_URI');
} else {
  $uri= 'http://169.254.170.2/'.ltrim($relative, '/'); // default Amazon ECS hostname
}

$res= (new HttpConnection($uri))->get();
$payload= Json::read(new StreamInput($res->in(), 'utf-8'));

// ['RoleArn' => ..., 'AccessKeyId' => ..., 'SecretAccessKey' => ..., 'Token' => ..., 'Expiration' => ...]

On top of this, these variables need to be taken into account:

The result can be cached by checking the Expiration date (e.g. 2024-06-21T14:22:07Z)


See also:

thekid commented 3 months ago

✅ Implemented