Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 73 additions & 2 deletions src/CredentialSource/AwsNativeSource.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,21 @@ public function fetchSubjectToken(?callable $httpHandler = null): string
];
}

if (!$signingVars = self::getSigningVarsFromEnv()) {
$signingVars = self::getSigningVarsFromEnv();
if (!$signingVars) {
// Container Credentials (ECS Fargate task role / EKS Pod Identity /
// AWS Greengrass etc.) expose credentials via a localhost endpoint
// referenced by AWS_CONTAINER_CREDENTIALS_{RELATIVE,FULL}_URI rather
// than by the EC2 IMDS-style securityCredentialsUrl. Try that path
// before falling back to the configured securityCredentialsUrl.
$signingVars = self::getSigningVarsFromContainerCredentials($httpHandler);
}
if (!$signingVars) {
if (!$this->securityCredentialsUrl) {
throw new \LogicException('Unable to get credentials from ENV, and no security credentials URL provided');
throw new \LogicException(
'Unable to get credentials from ENV or container credentials, '
. 'and no security credentials URL provided'
);
}
$signingVars = self::getSigningVarsFromUrl(
$httpHandler,
Expand Down Expand Up @@ -328,6 +340,65 @@ public static function getSigningVarsFromEnv(): ?array
return null;
}

/**
* Retrieves AWS signing credentials from the container credentials
* provider, when running on ECS Fargate, EKS Pod Identity, AWS Greengrass,
* or any other environment that exposes credentials through the
* `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI` /
* `AWS_CONTAINER_CREDENTIALS_FULL_URI` interface.
*
* The endpoint returns a JSON body with `AccessKeyId`, `SecretAccessKey`
* and `Token` fields, mirroring the format used by the EC2 instance
* metadata service but addressed directly without the role-name
* suffix used by IMDS.
*
* @see https://docs.aws.amazon.com/sdkref/latest/guide/feature-container-credentials.html
*
* @internal
*
* @param callable $httpHandler
*
* @return array{string, string, ?string}|null `null` when neither container
* credentials env var is set, signaling that the caller should fall
* through to the next credentials provider.
*/
public static function getSigningVarsFromContainerCredentials(callable $httpHandler): ?array
{
$relativeUri = getenv('AWS_CONTAINER_CREDENTIALS_RELATIVE_URI');
$fullUri = getenv('AWS_CONTAINER_CREDENTIALS_FULL_URI');
if (empty($relativeUri) && empty($fullUri)) {
return null;
}

$url = !empty($relativeUri)
? 'http://169.254.170.2' . $relativeUri
: (string) $fullUri;

$headers = [];
if ($authToken = getenv('AWS_CONTAINER_AUTHORIZATION_TOKEN')) {
$headers['Authorization'] = $authToken;
} elseif ($authTokenFile = getenv('AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE')) {
if (is_readable($authTokenFile)) {
$headers['Authorization'] = trim((string) file_get_contents($authTokenFile));
}
}

$request = new Request('GET', $url, $headers);
$response = $httpHandler($request);
$awsCreds = json_decode((string) $response->getBody(), true);
if (!is_array($awsCreds)
|| !isset($awsCreds['AccessKeyId'], $awsCreds['SecretAccessKey'])
) {
return null;
}

return [
$awsCreds['AccessKeyId'],
$awsCreds['SecretAccessKey'],
$awsCreds['Token'] ?? null,
];
}

/**
* Gets the unique key for caching
* For AwsNativeSource the values are:
Expand Down
150 changes: 149 additions & 1 deletion tests/CredentialSource/AwsNativeSourceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ public function testFetchSubjectTokenWithoutSecurityCredentialsUrlOrEnvThrowsExc
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage(
'Unable to get credentials from ENV, and no security credentials URL provided'
'Unable to get credentials from ENV or container credentials, and no security credentials URL provided'
);

$aws = new AwsNativeSource(
Expand All @@ -258,6 +258,154 @@ public function testFetchSubjectTokenWithoutSecurityCredentialsUrlOrEnvThrowsExc
$aws->fetchSubjectToken($httpHandler);
}

/** @runInSeparateProcess */
public function testGetSigningVarsFromContainerCredentialsReturnsNullWhenEnvNotSet()
{
// Neither AWS_CONTAINER_CREDENTIALS_RELATIVE_URI nor _FULL_URI is set.
$httpHandler = function (RequestInterface $request): ResponseInterface {
throw new \LogicException('HTTP handler should not be invoked when no container credentials env is set.');
};

$this->assertNull(
AwsNativeSource::getSigningVarsFromContainerCredentials($httpHandler)
);
}

/** @runInSeparateProcess */
public function testGetSigningVarsFromContainerCredentialsRelativeUri()
{
putenv('AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=/v2/credentials/abcdef');

$httpHandler = function (RequestInterface $request): ResponseInterface {
$this->assertEquals('GET', $request->getMethod());
$this->assertEquals(
'http://169.254.170.2/v2/credentials/abcdef',
(string) $request->getUri()
);
$this->assertFalse($request->hasHeader('Authorization'));

$body = $this->prophesize(StreamInterface::class);
$body->__toString()->willReturn(json_encode([
'AccessKeyId' => 'expected-access-key-id',
'SecretAccessKey' => 'expected-secret-access-key',
'Token' => 'expected-token',
]));
$response = $this->prophesize(ResponseInterface::class);
$response->getBody()->willReturn($body->reveal());

return $response->reveal();
};

$signingVars = AwsNativeSource::getSigningVarsFromContainerCredentials($httpHandler);

$this->assertEquals('expected-access-key-id', $signingVars[0]);
$this->assertEquals('expected-secret-access-key', $signingVars[1]);
$this->assertEquals('expected-token', $signingVars[2]);
}

/** @runInSeparateProcess */
public function testGetSigningVarsFromContainerCredentialsFullUriWithAuthToken()
{
$fullUri = 'http://eks-pod-identity.example/credentials';
putenv('AWS_CONTAINER_CREDENTIALS_FULL_URI=' . $fullUri);
putenv('AWS_CONTAINER_AUTHORIZATION_TOKEN=expected-bearer-token');

$httpHandler = function (RequestInterface $request) use ($fullUri): ResponseInterface {
$this->assertEquals('GET', $request->getMethod());
$this->assertEquals($fullUri, (string) $request->getUri());
$this->assertEquals('expected-bearer-token', $request->getHeaderLine('Authorization'));

$body = $this->prophesize(StreamInterface::class);
$body->__toString()->willReturn(json_encode([
'AccessKeyId' => 'full-access-key-id',
'SecretAccessKey' => 'full-secret-access-key',
// Token is optional in the response (e.g. long-lived creds).
]));
$response = $this->prophesize(ResponseInterface::class);
$response->getBody()->willReturn($body->reveal());

return $response->reveal();
};

$signingVars = AwsNativeSource::getSigningVarsFromContainerCredentials($httpHandler);

$this->assertEquals('full-access-key-id', $signingVars[0]);
$this->assertEquals('full-secret-access-key', $signingVars[1]);
$this->assertNull($signingVars[2]);
}

/** @runInSeparateProcess */
public function testFetchSubjectTokenFromContainerCredentials()
{
// Simulate ECS Fargate: AWS_ACCESS_KEY_ID is unset but
// AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is provided. fetchSubjectToken
// should fall through to the container credentials endpoint instead of
// throwing or hitting the (unconfigured) securityCredentialsUrl.
putenv('AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=/v2/credentials/task-role');

$aws = new AwsNativeSource(
$this->audience,
$this->regionUrl,
$this->regionalCredVerificationUrl,
);

// Mock response from container credentials endpoint
$containerBody = $this->prophesize(StreamInterface::class);
$containerBody->__toString()->willReturn(json_encode([
'AccessKeyId' => 'container-access-key-id',
'SecretAccessKey' => 'container-secret-access-key',
'Token' => 'container-session-token',
]));
$containerResponse = $this->prophesize(ResponseInterface::class);
$containerResponse->getBody()->willReturn($containerBody->reveal());

// Mock response from Region URL
$regionBody = $this->prophesize(StreamInterface::class);
$regionBody->__toString()->willReturn('us-east-2b');
$regionResponse = $this->prophesize(ResponseInterface::class);
$regionResponse->getBody()->willReturn($regionBody->reveal());

$requestCount = 0;
$httpHandler = function (RequestInterface $request) use (
$containerResponse,
$regionResponse,
&$requestCount
): ResponseInterface {
$requestCount++;
switch ($requestCount) {
case 1:
$this->assertEquals(
'http://169.254.170.2/v2/credentials/task-role',
(string) $request->getUri()
);
return $containerResponse->reveal();
case 2:
return $regionResponse->reveal();
}
throw new \Exception('Unexpected request');
};

$subjectToken = $aws->fetchSubjectToken($httpHandler);
$unserializedToken = json_decode(urldecode($subjectToken), true);
$this->assertArrayHasKey('headers', $unserializedToken);
$this->assertArrayHasKey('method', $unserializedToken);
$this->assertArrayHasKey('url', $unserializedToken);

// Sanity check: the SigV4 Authorization header must reference the
// access key fetched from the container credentials endpoint.
$authHeader = '';
foreach ($unserializedToken['headers'] as $header) {
if ($header['key'] === 'Authorization') {
$authHeader = $header['value'];
break;
}
}
$this->assertStringContainsString(
'Credential=container-access-key-id/',
$authHeader
);
}

/**
* @runInSeparateProcess
*/
Expand Down
Loading