class GCECredentials extends CredentialsLoader implements SignBlobInterface, ProjectIdProviderInterface, GetQuotaProjectInterface (View source)

GCECredentials supports authorization on Google Compute Engine.

It can be used to authorize requests using the AuthTokenMiddleware, but will only succeed if being run on GCE:

use Google\Auth\Credentials\GCECredentials; use Google\Auth\Middleware\AuthTokenMiddleware; use GuzzleHttp\Client; use GuzzleHttp\HandlerStack;

$gce = new GCECredentials(); $middleware = new AuthTokenMiddleware($gce); $stack = HandlerStack::create(); $stack->push($middleware);

$client = new Client([ 'handler' => $stack, 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/', 'auth' => 'google_auth' ]);

$res = $client->get('myproject/taskqueues/myqueue');

Traits

Provides shared methods for updating request metadata (request headers).

Trait containing helper methods required for enabling observability metrics in the library.

Constants

TOKEN_CREDENTIAL_URI

ENV_VAR

QUOTA_PROJECT_ENV_VAR

WELL_KNOWN_PATH

NON_WINDOWS_WELL_KNOWN_PATH_BASE

MTLS_WELL_KNOWN_PATH

MTLS_CERT_ENV_VAR

cacheKey

METADATA_IP

The metadata IP address on appengine instances.

The IP is used instead of the domain 'metadata' to avoid slow responses when not on Compute Engine.

TOKEN_URI_PATH

The metadata path of the default token.

ID_TOKEN_URI_PATH

The metadata path of the default id token.

CLIENT_ID_URI_PATH

The metadata path of the client ID.

PROJECT_ID_URI_PATH

The metadata path of the project ID.

UNIVERSE_DOMAIN_URI_PATH

The metadata path of the project ID.

FLAVOR_HEADER

The header whose presence indicates GCE presence.

private GKE_PRODUCT_NAME_FILE

The Linux file which contains the product name.

private WINDOWS_REGISTRY_KEY_PATH

The Windows Registry key path to the product name

private WINDOWS_REGISTRY_KEY_NAME

The Windows registry key name for the product name

private PRODUCT_NAME

The Name of the product expected from the windows registry

private CRED_TYPE

MAX_COMPUTE_PING_TRIES

Note: the explicit timeout and tries below is a workaround. The underlying issue is that resolving an unknown host on some networks will take 20-30 seconds; making this timeout short fixes the issue, but could lead to false negatives in the event that we are on GCE, but the metadata resolution was particularly slow. The latter case is "unlikely" since the expected 4-nines time is about 0.5 seconds.

This allows us to limit the total ping maximum timeout to 1.5 seconds for developer desktop scenarios.

COMPUTE_PING_CONNECTION_TIMEOUT_S

Properties

static protected string $metricMetadataKey from  MetricsTrait
protected array $lastReceivedToken

Result of fetchAuthToken.

Methods

static string
getMetricsHeader(string $credType = '', string $authRequestType = '')

No description

array
applyServiceApiUsageMetrics(array $metadata)

No description

array
applyTokenEndpointMetrics(array $metadata, string $authRequestType)

No description

static string
getVersion()

No description

string
getCredType()

No description

callable
getUpdateMetadataFunc() deprecated

export a callback function which updates runtime metadata.

array
updateMetadata(array $metadata, string $authUri = null, callable $httpHandler = null)

Updates metadata with the authorization token.

static array|null
fromEnv()

Load a JSON key from the path specified in the environment.

static array|null
fromWellKnownFile()

Load a JSON key from a well known path.

makeCredentials(string|string[] $scope, array $jsonKey, string|string[] $defaultScope = null)

Create a new Credentials instance.

static Client
makeHttpClient(FetchAuthTokenInterface $fetcher, array $httpClientOptions = [], callable $httpHandler = null, callable $tokenCallback = null)

Create an authorized HTTP Client from an instance of FetchAuthTokenInterface.

makeInsecureCredentials()

Create a new instance of InsecureCredentials.

static string|null
quotaProjectFromEnv()

Fetch a quota project from the environment variable GOOGLE_CLOUD_QUOTA_PROJECT. Return null if GOOGLE_CLOUD_QUOTA_PROJECT is not specified.

static callable|null
getDefaultClientCertSource()

Gets a callable which returns the default device certification.

static bool
shouldLoadClientCertSource()

Determines whether or not the default device certificate should be loaded.

string
getUniverseDomain(callable $httpHandler = null)

Fetch the default universe domain from the metadata server.

string
signBlob(string $stringToSign, bool $forceOpenSsl = false, string $accessToken = null)

Sign a string using the default service account private key.

__construct(Iam $iam = null, string|string[] $scope = null, string $targetAudience = null, string $quotaProject = null, string $serviceAccountIdentity = null, string $universeDomain = null)

No description

static string
getTokenUri(string $serviceAccountIdentity = null)

The full uri for accessing the default token.

static string
getClientNameUri(string $serviceAccountIdentity = null)

The full uri for accessing the default service account.

static bool
onAppEngineFlexible()

Determines if this an App Engine Flexible instance, by accessing the GAE_INSTANCE environment variable.

static bool
onGce(callable $httpHandler = null)

Determines if this a GCE instance, by accessing the expected metadata host.

array
fetchAuthToken(callable $httpHandler = null)

Implements FetchAuthTokenInterface#fetchAuthToken.

string
getCacheKey()

No description

null|array
getLastReceivedToken()

No description

string
getClientName(callable $httpHandler = null)

Get the client name from GCE metadata.

string|null
getProjectId(callable $httpHandler = null)

Fetch the default Project ID from compute engine.

string|null
getQuotaProject()

Get the quota project used for this API request

void
setIsOnGce(bool $isOnGce)

Set whether or not we've already checked the GCE environment.

Details

static protected string getMetricsHeader(string $credType = '', string $authRequestType = '')

No description

Parameters

string $credType

[Optional] The credential type. Empty value will not add any credential type to the header. Should be one of 'sa', 'jwt', 'imp', 'mds', 'u'.

string $authRequestType

[Optional] The auth request type. Empty value will not add any auth request type to the header. Should be one of 'at', 'it', 'mds'.

Return Value

string

The header value for the observability metrics.

protected array applyServiceApiUsageMetrics(array $metadata)

No description

Parameters

array $metadata

The metadata to update and return.

Return Value

array

The updated metadata.

protected array applyTokenEndpointMetrics(array $metadata, string $authRequestType)

No description

Parameters

array $metadata

The metadata to update and return.

string $authRequestType

The auth request type. Possible values are 'at', 'it', 'mds'.

Return Value

array

The updated metadata.

static protected string getVersion()

No description

Return Value

string

protected string getCredType()

No description

Return Value

string

callable getUpdateMetadataFunc() deprecated

deprecated

export a callback function which updates runtime metadata.

Return Value

callable

updateMetadata function

array updateMetadata(array $metadata, string $authUri = null, callable $httpHandler = null)

Updates metadata with the authorization token.

Parameters

array $metadata

metadata hashmap

string $authUri

optional auth uri

callable $httpHandler

callback which delivers psr7 request

Return Value

array

updated metadata hashmap

static array|null fromEnv()

Load a JSON key from the path specified in the environment.

Load a JSON key from the path specified in the environment variable GOOGLE_APPLICATION_CREDENTIALS. Return null if GOOGLE_APPLICATION_CREDENTIALS is not specified.

Return Value

array|null

JSON key | null

static array|null fromWellKnownFile()

Load a JSON key from a well known path.

The well known path is OS dependent:

  • windows: %APPDATA%/gcloud/application_default_credentials.json
  • others: $HOME/.config/gcloud/application_default_credentials.json

If the file does not exist, this returns null.

Return Value

array|null

JSON key | null

static ServiceAccountCredentials|UserRefreshCredentials|ImpersonatedServiceAccountCredentials|ExternalAccountCredentials makeCredentials(string|string[] $scope, array $jsonKey, string|string[] $defaultScope = null)

Create a new Credentials instance.

Parameters

string|string[] $scope

the scope of the access request, expressed either as an Array or as a space-delimited String.

array $jsonKey

the JSON credentials.

string|string[] $defaultScope

The default scope to use if no user-defined scopes exist, expressed either as an Array or as a space-delimited string.

Return Value

ServiceAccountCredentials|UserRefreshCredentials|ImpersonatedServiceAccountCredentials|ExternalAccountCredentials

static Client makeHttpClient(FetchAuthTokenInterface $fetcher, array $httpClientOptions = [], callable $httpHandler = null, callable $tokenCallback = null)

Create an authorized HTTP Client from an instance of FetchAuthTokenInterface.

Parameters

FetchAuthTokenInterface $fetcher

is used to fetch the auth token

array $httpClientOptions

(optional) Array of request options to apply.

callable $httpHandler

(optional) http client to fetch the token.

callable $tokenCallback

(optional) function to be called when a new token is fetched.

Return Value

Client

static InsecureCredentials makeInsecureCredentials()

Create a new instance of InsecureCredentials.

Return Value

InsecureCredentials

static string|null quotaProjectFromEnv()

Fetch a quota project from the environment variable GOOGLE_CLOUD_QUOTA_PROJECT. Return null if GOOGLE_CLOUD_QUOTA_PROJECT is not specified.

Return Value

string|null

static callable|null getDefaultClientCertSource()

Gets a callable which returns the default device certification.

Return Value

callable|null

Exceptions

UnexpectedValueException

static bool shouldLoadClientCertSource()

Determines whether or not the default device certificate should be loaded.

Return Value

bool

string getUniverseDomain(callable $httpHandler = null)

Fetch the default universe domain from the metadata server.

Parameters

callable $httpHandler

Callback which delivers psr7 request

Return Value

string

string signBlob(string $stringToSign, bool $forceOpenSsl = false, string $accessToken = null)

Sign a string using the default service account private key.

This implementation uses IAM's signBlob API.

Parameters

string $stringToSign

The string to sign.

bool $forceOpenSsl

[optional] Does not apply to this credentials type.

string $accessToken

The access token to use to sign the blob. If provided, saves a call to the metadata server for a new access token. Defaults to null.

Return Value

string

Exceptions

Exception

See also

https://cloud.google.com/iam/credentials/reference/rest/v1/projects.serviceAccounts/signBlob SignBlob

__construct(Iam $iam = null, string|string[] $scope = null, string $targetAudience = null, string $quotaProject = null, string $serviceAccountIdentity = null, string $universeDomain = null)

No description

Parameters

Iam $iam

[optional] An IAM instance.

string|string[] $scope

[optional] the scope of the access request, expressed either as an array or as a space-delimited string.

string $targetAudience

[optional] The audience for the ID token.

string $quotaProject

[optional] Specifies a project to bill for access charges associated with the request.

string $serviceAccountIdentity

[optional] Specify a service account identity name to use instead of "default".

string $universeDomain

[optional] Specify a universe domain to use instead of fetching one from the metadata server.

static string getTokenUri(string $serviceAccountIdentity = null)

The full uri for accessing the default token.

Parameters

string $serviceAccountIdentity

[optional] Specify a service account identity name to use instead of "default".

Return Value

string

static string getClientNameUri(string $serviceAccountIdentity = null)

The full uri for accessing the default service account.

Parameters

string $serviceAccountIdentity

[optional] Specify a service account identity name to use instead of "default".

Return Value

string

static bool onAppEngineFlexible()

Determines if this an App Engine Flexible instance, by accessing the GAE_INSTANCE environment variable.

Return Value

bool

true if this an App Engine Flexible Instance, false otherwise

static bool onGce(callable $httpHandler = null)

Determines if this a GCE instance, by accessing the expected metadata host.

If $httpHandler is not specified a the default HttpHandler is used.

Parameters

callable $httpHandler

callback which delivers psr7 request

Return Value

bool

True if this a GCEInstance, false otherwise

array fetchAuthToken(callable $httpHandler = null)

Implements FetchAuthTokenInterface#fetchAuthToken.

Fetches the auth tokens from the GCE metadata host if it is available. If $httpHandler is not specified a the default HttpHandler is used.

Parameters

callable $httpHandler

callback which delivers psr7 request

Return Value

array

a hash of auth tokens

Exceptions

Exception

string getCacheKey()

No description

Return Value

string

a key that may be used to cache the auth token.

null|array getLastReceivedToken()

No description

Return Value

null|array

{ The last received access token.

@type string $access_token The access token string.
@type int $expires_at The time the token expires as a UNIX timestamp.

}

string getClientName(callable $httpHandler = null)

Get the client name from GCE metadata.

Subsequent calls will return a cached value.

Parameters

callable $httpHandler

callback which delivers psr7 request, if one is required to obtain a client name.

Return Value

string

string|null getProjectId(callable $httpHandler = null)

Fetch the default Project ID from compute engine.

Returns null if called outside GCE.

Parameters

callable $httpHandler

Callback which delivers psr7 request

Return Value

string|null

string|null getQuotaProject()

Get the quota project used for this API request

Return Value

string|null

void setIsOnGce(bool $isOnGce)

Set whether or not we've already checked the GCE environment.

Parameters

bool $isOnGce

Return Value

void