Class ComputeEngineCredentials
- All Implemented Interfaces:
IdTokenProvider, QuotaProjectIdProvider, ServiceAccountSigner, Serializable
Fetches access tokens from the Google Compute Engine metadata server.
These credentials use the IAM API to sign data. See sign(byte[]) for more details.
- See Also:
-
Nested Class Summary
Nested ClassesNested classes/interfaces inherited from class OAuth2Credentials
OAuth2Credentials.AsyncRefreshResult, OAuth2Credentials.CacheState, OAuth2Credentials.CredentialsChangedListener, OAuth2Credentials.FutureCallbackToMetadataCallbackAdapter, OAuth2Credentials.OAuthValue, OAuth2Credentials.RefreshTask, OAuth2Credentials.RefreshTaskListenerNested classes/interfaces inherited from interface IdTokenProvider
IdTokenProvider.OptionNested classes/interfaces inherited from interface ServiceAccountSigner
ServiceAccountSigner.SigningException -
Field Summary
FieldsModifier and TypeFieldDescription(package private) static final Duration(package private) static final int(package private) static final Duration(package private) static final Stringprivate static final Stringprivate static final Stringprivate static final Logger(package private) static final intprivate static final Stringprivate static final Stringprivate static final Stringprivate final Collection<String> private static final longprivate String(package private) static final Stringprivate HttpTransportFactoryprivate final Stringprivate Stringprivate static final StringFields inherited from class GoogleCredentials
GDCH_SERVICE_ACCOUNT_FILE_TYPE, QUOTA_PROJECT_ID_HEADER_KEY, quotaProjectId, SERVICE_ACCOUNT_FILE_TYPE, USER_FILE_TYPEFields inherited from class OAuth2Credentials
clock, DEFAULT_EXPIRATION_MARGIN, DEFAULT_REFRESH_MARGIN, lock, refreshTaskFields inherited from class Credentials
GOOGLE_DEFAULT_UNIVERSE -
Constructor Summary
ConstructorsModifierConstructorDescriptionprivateAn internal constructor -
Method Summary
Modifier and TypeMethodDescription(package private) static boolean(package private) static booleanstatic ComputeEngineCredentialscreate()Create a new ComputeEngineCredentials instance with default behavior.createScoped(Collection<String> newScopes) Clones the compute engine account with the specified scopes.createScoped(Collection<String> newScopes, Collection<String> newDefaultScopes) Clones the compute engine account with the specified scopes and default scopes.(package private) StringIf scopes is specified, add "?scopes=comma-separated-list-of-scopes" to the token url.booleanReturns the email address associated with the GCE default service account.private Stringstatic Stringprivate com.google.api.client.http.HttpResponsegetMetadataResponse(String url, MetricsUtils.RequestType requestType, boolean shouldSendMetricsHeader) static Stringstatic StringGets the credential type used for internal metrics header.final Collection<String> static Stringstatic Stringstatic StringGets the universe domain from the GCE metadata server.private Stringstatic StringinthashCode()idTokenWithAudience(String targetAudience, List<IdTokenProvider.Option> options) Returns a Google ID Token from the metadata server on ComputeEngine(package private) static booleanisOnGce(HttpTransportFactory transportFactory, DefaultCredentialsProvider provider) Implements an algorithm to detect whether the code is running on Google Compute Environment (GCE) or equivalent runtime.private static booleanpingComputeEngineMetadata(HttpTransportFactory transportFactory, DefaultCredentialsProvider provider) private voidreadObject(ObjectInputStream input) Refresh the access token by getting it from the GCE metadata serverbyte[]sign(byte[] toSign) Signs the provided bytes using the private key associated with the service account.protected com.google.common.base.MoreObjects.ToStringHelperA helper for overriding the toString() method.Methods inherited from class GoogleCredentials
addQuotaProjectIdToRequestMetadata, create, create, createDelegated, createScoped, createScopedRequired, createWithCustomRetryStrategy, createWithQuotaProject, fromStream, fromStream, getAdditionalHeaders, getApplicationDefault, getApplicationDefault, getQuotaProjectId, isDefaultUniverseDomain, isExplicitUniverseDomain, toStringMethods inherited from class OAuth2Credentials
addChangeListener, getAccessToken, getAuthenticationType, getExpirationMargin, getFromServiceLoader, getRefreshMargin, getRequestMetadata, getRequestMetadata, getRequestMetadataInternal, hasRequestMetadata, hasRequestMetadataOnly, newInstance, refresh, refreshIfExpired, removeChangeListenerMethods inherited from class Credentials
blockingGetToCallback, getRequestMetadata
-
Field Details
-
COMPUTE_EXPIRATION_MARGIN
-
COMPUTE_REFRESH_MARGIN
-
LOGGER
-
DEFAULT_METADATA_SERVER_URL
- See Also:
-
SIGN_BLOB_URL_FORMAT
- See Also:
-
MAX_COMPUTE_PING_TRIES
static final int MAX_COMPUTE_PING_TRIES- See Also:
-
COMPUTE_PING_CONNECTION_TIMEOUT_MS
static final int COMPUTE_PING_CONNECTION_TIMEOUT_MS- See Also:
-
METADATA_FLAVOR
- See Also:
-
GOOGLE
- See Also:
-
WINDOWS
- See Also:
-
LINUX
- See Also:
-
PARSE_ERROR_PREFIX
- See Also:
-
PARSE_ERROR_ACCOUNT
- See Also:
-
serialVersionUID
private static final long serialVersionUID- See Also:
-
transportFactoryClassName
-
scopes
-
transportFactory
-
serviceAccountEmail
-
universeDomainFromMetadata
-
-
Constructor Details
-
ComputeEngineCredentials
An internal constructor- Parameters:
builder- A builder forComputeEngineCredentialsSeeComputeEngineCredentials.Builder
-
-
Method Details
-
getMetricsCredentialType
Description copied from class:CredentialsGets the credential type used for internal metrics header.The default is
CredentialTypeForMetrics.DO_NOT_SEND. For a credential that is established to track for metrics, this default should be overridden.- Overrides:
getMetricsCredentialTypein classCredentials- Returns:
- a enum value for credential type
-
createScoped
Clones the compute engine account with the specified scopes.- Overrides:
createScopedin classGoogleCredentials- Parameters:
newScopes- Collection of scopes to request.- Returns:
- GoogleCredentials with requested scopes.
-
createScoped
public GoogleCredentials createScoped(Collection<String> newScopes, Collection<String> newDefaultScopes) Clones the compute engine account with the specified scopes and default scopes.- Overrides:
createScopedin classGoogleCredentials- Parameters:
newScopes- Collection of scopes to request.newDefaultScopes- Collection of default scopes to request.- Returns:
- GoogleCredentials with requested scopes.
-
create
Create a new ComputeEngineCredentials instance with default behavior.- Returns:
- new ComputeEngineCredentials
-
getScopes
-
createTokenUrlWithScopes
String createTokenUrlWithScopes()If scopes is specified, add "?scopes=comma-separated-list-of-scopes" to the token url.- Returns:
- token url with the given scopes
-
getUniverseDomain
Gets the universe domain from the GCE metadata server.Returns an explicit universe domain if it was provided during credential initialization.
Returns the
Credentials.GOOGLE_DEFAULT_UNIVERSEif universe domain endpoint is not found (404) or returns an empty string.Otherwise, returns universe domain from GCE metadata service.
Any above value is cached for the credential lifetime.
- Overrides:
getUniverseDomainin classGoogleCredentials- Returns:
- string representing a universe domain in the format some-domain.xyz
- Throws:
IOException- if a call to GCE metadata service was unsuccessful. Check if exception implements theRetryableandisRetryable()will return true if the operation may be retried.
-
getUniverseDomainFromMetadata
- Throws:
IOException
-
refreshAccessToken
Refresh the access token by getting it from the GCE metadata server- Overrides:
refreshAccessTokenin classOAuth2Credentials- Returns:
- never
- Throws:
IOException
-
idTokenWithAudience
public IdToken idTokenWithAudience(String targetAudience, List<IdTokenProvider.Option> options) throws IOException Returns a Google ID Token from the metadata server on ComputeEngine- Specified by:
idTokenWithAudiencein interfaceIdTokenProvider- Parameters:
targetAudience- the aud: field the IdToken should includeoptions- list of Credential specific options for the token. For example, an IDToken for a ComputeEngineCredential could have the full formatted claims returned if IdTokenProvider.Option.FORMAT_FULL) is provided as a list option. Valid option values are:
IdTokenProvider.Option.FORMAT_FULL
IdTokenProvider.Option.LICENSES_TRUE
If no options are set, the defaults are "&format=standard&licenses=false"- Returns:
- IdToken object which includes the raw id_token, JsonWebSignature
- Throws:
IOException- if the attempt to get an IdToken failed
-
getMetadataResponse
private com.google.api.client.http.HttpResponse getMetadataResponse(String url, MetricsUtils.RequestType requestType, boolean shouldSendMetricsHeader) throws IOException - Throws:
IOException
-
isOnGce
Implements an algorithm to detect whether the code is running on Google Compute Environment (GCE) or equivalent runtime. See AIP-4115 for more details The algorithm consists of active and passive checks:
Active: to check that GCE Metadata service is present by sending a http request to send a request toComputeEngineCredentials.DEFAULT_METADATA_SERVER_URLPassive: to check if SMBIOS variable is present and contains expected value. This step is platform specific:
For Linux: check if the file "/sys/class/dmi/id/product_name" exists and contains a line that starts with Google.
For Windows: to be implemented
Other platforms: not supported
This algorithm can be disabled with environment variable
DefaultCredentialsProvider.NO_GCE_CHECK_ENV_VARset totrue. In this case, the algorithm will always returnfalseReturnstrueif currently running on Google Compute Environment (GCE) or equivalent runtime. Returnsfalseif detection fails, platform is not supported or if detection disabled using the environment variable. -
checkProductNameOnLinux
- Throws:
IOException
-
checkStaticGceDetection
-
pingComputeEngineMetadata
private static boolean pingComputeEngineMetadata(HttpTransportFactory transportFactory, DefaultCredentialsProvider provider) -
getMetadataServerUrl
-
getMetadataServerUrl
-
getTokenServerEncodedUrl
-
getTokenServerEncodedUrl
-
getUniverseDomainUrl
-
getServiceAccountsUrl
-
getIdentityDocumentUrl
-
hashCode
public int hashCode()- Overrides:
hashCodein classGoogleCredentials
-
toStringHelper
protected com.google.common.base.MoreObjects.ToStringHelper toStringHelper()Description copied from class:GoogleCredentialsA helper for overriding the toString() method. This allows inheritance of super class fields. Extending classes can override this implementation and call super implementation and add more fields. Same cannot be done with overriding the toString() directly.- Overrides:
toStringHelperin classGoogleCredentials- Returns:
- an instance of the ToStringHelper that has public fields added
-
equals
- Overrides:
equalsin classGoogleCredentials
-
readObject
- Throws:
IOExceptionClassNotFoundException
-
toBuilder
- Overrides:
toBuilderin classGoogleCredentials
-
newBuilder
-
getAccount
Returns the email address associated with the GCE default service account.- Specified by:
getAccountin interfaceServiceAccountSigner- Returns:
- The service account associated with the signer.
- Throws:
RuntimeException- if the default service account cannot be read
-
sign
public byte[] sign(byte[] toSign) Signs the provided bytes using the private key associated with the service account.The Compute Engine's project must enable the Identity and Access Management (IAM) API and the instance's service account must have the iam.serviceAccounts.signBlob permission.
- Specified by:
signin interfaceServiceAccountSigner- Parameters:
toSign- bytes to sign- Returns:
- signed bytes
- Throws:
ServiceAccountSigner.SigningException- if the attempt to sign the provided bytes failed- See Also:
-
getDefaultServiceAccount
- Throws:
IOException
-