Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add STS #462

Closed
wants to merge 33 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
d6d296e
feat: add STS
bshaffer Jun 26, 2023
b7b3a76
fix mistake
bshaffer Jun 26, 2023
dbc9600
ensure scope is string
bshaffer Jun 26, 2023
406edbe
add STS tests
bshaffer Jun 26, 2023
9c58a48
add ExternalAccountCredentials type
bshaffer Jun 26, 2023
765c6e6
remove aws for now - we will add this later
bshaffer Jun 27, 2023
8675762
fix return type
bshaffer Jun 27, 2023
c972dfb
WIP - add aws integration
bshaffer Jun 27, 2023
c59a613
WIP
bshaffer Jun 30, 2023
633bb13
WIP
bshaffer Jul 5, 2023
85dcdb2
fix order
bshaffer Jul 5, 2023
26540bc
style fix
bshaffer Jul 5, 2023
f099654
add tests
bshaffer Jul 18, 2023
94885c8
remove trailing comma syntax error for earlier versions of php
bshaffer Jul 20, 2023
be5df0d
fix cs and static analysis
bshaffer Jul 20, 2023
ce72006
get rid of utf8_encode
bshaffer Jul 20, 2023
d30cf8f
testing for CredentialsSource classes
bshaffer Jul 21, 2023
9f59d66
mark all AwsNative public static methods as internal
bshaffer Jul 21, 2023
b1953bf
more testing
bshaffer Jul 24, 2023
acdc8bd
add support for aws token
bshaffer Jul 24, 2023
3409fd5
substitude region in credVerificationUrl
bshaffer Jul 24, 2023
89bb375
fix date format
bshaffer Jul 25, 2023
5fd66ae
fixing signature format
bshaffer Jul 25, 2023
374373e
add json
bshaffer Aug 1, 2023
0995802
fix tests
bshaffer Aug 15, 2023
f74cff1
style fix
bshaffer Aug 15, 2023
a691f36
add CredentialSourceInterface
bshaffer Aug 24, 2023
14d5045
fix ExternalAccountCredentials
bshaffer Aug 24, 2023
40481a2
misc fixes
bshaffer Aug 24, 2023
c210f73
add region and host
bshaffer Aug 24, 2023
b05f1d5
typo-fix
bshaffer Aug 24, 2023
cab53e3
fix formatted headers
bshaffer Aug 24, 2023
2603ce5
add ADC tests
bshaffer Aug 24, 2023
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ composer.lock
.cache
.docs
.gitmodules
.phpunit.result.cache

# IntelliJ
.idea
Expand Down
315 changes: 315 additions & 0 deletions src/CredentialSource/AwsNativeSource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,315 @@
<?php
/*
* Copyright 2023 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Google\Auth\CredentialSource;

use Google\Auth\CredentialSourceInterface;
use Google\Auth\HttpHandler\HttpClientCache;
use Google\Auth\HttpHandler\HttpHandlerFactory;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Uri;

/**
* Authenticates requests using IAM credentials.
*/
class AwsNativeSource implements CredentialSourceInterface
{
private const CRED_VERIFICATION_QUERY = 'Action=GetCallerIdentity&Version=2011-06-15';

private string $audience;
private string $regionUrl;
private string $regionalCredVerificationUrl;
private ?string $securityCredentialsUrl;

public function __construct(
string $audience,
string $regionUrl,
string $regionalCredVerificationUrl,
string $securityCredentialsUrl = null
) {
$this->audience = $audience;
$this->regionUrl = $regionUrl;
$this->regionalCredVerificationUrl = $regionalCredVerificationUrl;
$this->securityCredentialsUrl = $securityCredentialsUrl;
}

public function fetchSubjectToken(callable $httpHandler = null): string
{
if (is_null($httpHandler)) {
$httpHandler = HttpHandlerFactory::build(HttpClientCache::getHttpClient());
}

$awsToken = self::fetchAwsTokenFromMetadata($httpHandler);

$signingVars = $this->securityCredentialsUrl
? self::getSigningVarsFromUrl(
$httpHandler,
$this->securityCredentialsUrl,
self::getRoleName($httpHandler, $this->securityCredentialsUrl, $awsToken),
$awsToken
)
: self::getSigningVarsFromEnv();

if (is_null($signingVars)) {
throw new \LogicException('Unable to get credentials from ENV, and no security credentials URL provided');
}

$region = self::getRegion($httpHandler, $this->regionUrl, $awsToken);
$url = str_replace('{region}', $region, $this->regionalCredVerificationUrl);
$parts = parse_url($url);

// From here we use the signing vars to create the signed request to receive a token
[$accessKeyId, $secretAccessKey, $securityToken] = $signingVars;
$headers = self::getSignedRequestHeaders($region, $parts['host'], $accessKeyId, $secretAccessKey, $securityToken);

Check failure on line 77 in src/CredentialSource/AwsNativeSource.php

View workflow job for this annotation

GitHub Actions / PHPStan Static Analysis

Cannot access offset 'host' on array{scheme?: string, host?: string, port?: int<0, 65535>, user?: string, pass?: string, path?: string, query?: string, fragment?: string}|false.

// Inject x-goog-cloud-target-resource into header
$headers['x-goog-cloud-target-resource'] = $this->audience;

// Format headers as they're expected in the subject token
$formattedHeaders= array_map(
fn ($k, $v) => ['key' => $k, 'value' => $v],
array_keys($headers),
$headers,
);

$request = [
'headers' => $formattedHeaders,
'method' => 'POST',
'url' => $url,
];

return urlencode(json_encode($request));

Check failure on line 95 in src/CredentialSource/AwsNativeSource.php

View workflow job for this annotation

GitHub Actions / PHPStan Static Analysis

Parameter #1 $string of function urlencode expects string, string|false given.
}

/**
* @internal
*/
public static function fetchAwsTokenFromMetadata(callable $httpHandler): string
{
$url = 'http://169.254.169.254/latest/api/token';
$headers = [
'X-aws-ec2-metadata-token-ttl-seconds' => '21600'
];
$request = new Request(
'PUT',
$url,
$headers
);

$response = $httpHandler($request);
return (string) $response->getBody();
}

/**
* @see http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
*
* @internal
*
* @return array<string, string>
*/
public static function getSignedRequestHeaders(
string $region,
string $host,
string $accessKeyId,
string $secretAccessKey,
?string $securityToken
): array {
$service = 'sts';

# Create a date for headers and the credential string in ISO-8601 format
$amzdate = date('Ymd\THis\Z');
$datestamp = date('Ymd'); # Date w/o time, used in credential scope

# Create the canonical headers and signed headers. Header names
# must be trimmed and lowercase, and sorted in code point order from
# low to high. Note that there is a trailing \n.
$canonicalHeaders = sprintf("host:%s\nx-amz-date:%s\n", $host, $amzdate);
if ($securityToken) {
$canonicalHeaders .= sprintf("x-amz-security-token:%s\n", $securityToken);
}

# Step 5: Create the list of signed headers. This lists the headers
# in the canonicalHeaders list, delimited with ";" and in alpha order.
# Note: The request can include any headers; $canonicalHeaders and
# $signedHeaders lists those that you want to be included in the
# hash of the request. "Host" and "x-amz-date" are always required.
$signedHeaders = 'host;x-amz-date';
if ($securityToken) {
$signedHeaders .= ';x-amz-security-token';
}

# Step 6: Create payload hash (hash of the request body content). For GET
# requests, the payload is an empty string ("").
$payloadHash = hash('sha256', '');

# Step 7: Combine elements to create canonical request
$canonicalRequest = implode("\n", [
'POST', // method
'/', // canonical URL
self::CRED_VERIFICATION_QUERY, // query string
$canonicalHeaders,
$signedHeaders,
$payloadHash
]);

# ************* TASK 2: CREATE THE STRING TO SIGN*************
# Match the algorithm to the hashing algorithm you use, either SHA-1 or
# SHA-256 (recommended)
$algorithm = 'AWS4-HMAC-SHA256';
$scope = implode('/', [$datestamp, $region, $service, 'aws4_request']);
$stringToSign = implode("\n", [$algorithm, $amzdate, $scope, hash('sha256', $canonicalRequest)]);

# ************* TASK 3: CALCULATE THE SIGNATURE *************
# Create the signing key using the function defined above.
// (done above)
$signingKey = self::getSignatureKey($secretAccessKey, $datestamp, $region, $service);

# Sign the string_to_sign using the signing_key
$signature = bin2hex(self::hmacSign($signingKey, $stringToSign));

# ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************
# The signing information can be either in a query string value or in
# a header named Authorization. This code shows how to use a header.
# Create authorization header and add to request headers
$authorizationHeader = sprintf(
'%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
$algorithm,
$accessKeyId,
$scope,
$signedHeaders,
$signature
);

# The request can include any headers, but MUST include "host", "x-amz-date",
# and (for this scenario) "Authorization". "host" and "x-amz-date" must
# be included in the canonical_headers and signed_headers, as noted
# earlier. Order here is not significant.
$headers = [
'host' => $host,
'x-amz-date' => $amzdate,
'Authorization' => $authorizationHeader,
];
if ($securityToken) {
$headers['x-amz-security-token'] = $securityToken;
}

return $headers;
}

/**
* @internal
*/
public static function getRegion(callable $httpHandler, string $regionUrl, string $awsToken): string
{
// get the region/zone from the region URL
$regionRequest = new Request('GET', $regionUrl, ['X-aws-ec2-metadata-token' => $awsToken]);
$regionResponse = $httpHandler($regionRequest);

// Remove last character. For example, if us-east-2b is returned,
// the region would be us-east-2.
return substr((string) $regionResponse->getBody(), 0, -1);
}

/**
* @internal
*/
public static function getRoleName(callable $httpHandler, string $securityCredentialsUrl, string $awsToken): string
{
// Get the AWS role name
$roleRequest = new Request('GET', $securityCredentialsUrl, ['X-aws-ec2-metadata-token' => $awsToken]);
$roleResponse = $httpHandler($roleRequest);
$roleName = (string) $roleResponse->getBody();

return $roleName;
}

/**
* @internal
*
* @return array{string, string, ?string}
*/
public static function getSigningVarsFromUrl(
callable $httpHandler,
string $securityCredentialsUrl,
string $roleName,
string $awsToken
): array {
// Get the AWS credentials
$credsRequest = new Request(
'GET',
$securityCredentialsUrl . '/' . $roleName,
['X-aws-ec2-metadata-token' => $awsToken]
);
$credsResponse = $httpHandler($credsRequest);
$awsCreds = json_decode((string) $credsResponse->getBody(), true);
return [
$awsCreds['AccessKeyId'], // accessKeyId
$awsCreds['SecretAccessKey'], // secretAccessKey
$awsCreds['Token'], // token
];
}

/**
* @internal
*
* @return array{string, string, ?string}
*/
public static function getSigningVarsFromEnv(): ?array
{
$accessKeyId = getenv('AWS_ACCESS_KEY_ID');
$secretAccessKey = getenv('AWS_SECRET_ACCESS_KEY');
if ($accessKeyId && $secretAccessKey) {
return [
$accessKeyId,
$secretAccessKey,
getenv('AWS_SESSION_TOKEN') ?: null, // session token (can be null)
];
}

return null;
}

/**
* Return HMAC hash in binary string
*/
private static function hmacSign(string $key, string $msg): string
{
return hash_hmac('sha256', self::utf8Encode($msg), $key, true);
}

/**
* @TODO add a fallback when mbstring is not available
*/
private static function utf8Encode(string $string): string
{
return mb_convert_encoding($string, 'UTF-8', 'ISO-8859-1');
}

private static function getSignatureKey(
string $key,
string $dateStamp,
string $regionName,
string $serviceName
): string {
$kDate = self::hmacSign(self::utf8Encode('AWS4' . $key), $dateStamp);
$kRegion = self::hmacSign($kDate, $regionName);
$kService = self::hmacSign($kRegion, $serviceName);
$kSigning = self::hmacSign($kService, 'aws4_request');

return $kSigning;
}
}
69 changes: 69 additions & 0 deletions src/CredentialSource/FileSource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php
/*
* Copyright 2023 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Google\Auth\CredentialSource;

use Google\Auth\CredentialSourceInterface;
use InvalidArgumentException;
use UnexpectedValueException;

/**
* Retrieve a token from a file.
*/
class FileSource implements CredentialSourceInterface
{
private string $file;
private ?string $format;
private ?string $subjectTokenFieldName;

public function __construct(
string $file,
string $format = null,
string $subjectTokenFieldName = null
) {
$this->file = $file;

if ($format === 'json' && is_null($subjectTokenFieldName)) {
throw new InvalidArgumentException(
'subject_token_field_name must be set when format is JSON'
);
}

$this->format = $format;
$this->subjectTokenFieldName = $subjectTokenFieldName;
}

public function fetchSubjectToken(callable $httpHandler = null): string
{
$contents = file_get_contents($this->file);
if ($this->format === 'json') {
if (!$json = json_decode((string) $contents, true)) {
throw new UnexpectedValueException(
'Unable to decode JSON file'
);
}
if (!isset($json[$this->subjectTokenFieldName])) {
throw new UnexpectedValueException(
'subject_token_field_name not found in JSON file'
);
}
$contents = $json[$this->subjectTokenFieldName];
}

return $contents;
}
}
Loading
Loading