Class ComputeEngineCredentials
- java.lang.Object
-
- com.google.auth.Credentials
-
- com.google.auth.oauth2.OAuth2Credentials
-
- com.google.auth.oauth2.GoogleCredentials
-
- com.google.auth.oauth2.ComputeEngineCredentials
-
- All Implemented Interfaces:
IdTokenProvider
,QuotaProjectIdProvider
,ServiceAccountSigner
,java.io.Serializable
public class ComputeEngineCredentials extends GoogleCredentials implements ServiceAccountSigner, IdTokenProvider
OAuth2 credentials representing the built-in service account for a Google Compute Engine VM.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:
- Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
ComputeEngineCredentials.Builder
-
Nested classes/interfaces inherited from class com.google.auth.oauth2.OAuth2Credentials
OAuth2Credentials.AsyncRefreshResult, OAuth2Credentials.CacheState, OAuth2Credentials.CredentialsChangedListener, OAuth2Credentials.FutureCallbackToMetadataCallbackAdapter, OAuth2Credentials.OAuthValue, OAuth2Credentials.RefreshTask, OAuth2Credentials.RefreshTaskListener
-
Nested classes/interfaces inherited from interface com.google.auth.oauth2.IdTokenProvider
IdTokenProvider.Option
-
Nested classes/interfaces inherited from interface com.google.auth.ServiceAccountSigner
ServiceAccountSigner.SigningException
-
-
Field Summary
Fields Modifier and Type Field Description (package private) static java.time.Duration
COMPUTE_EXPIRATION_MARGIN
(package private) static int
COMPUTE_PING_CONNECTION_TIMEOUT_MS
(package private) static java.time.Duration
COMPUTE_REFRESH_MARGIN
(package private) static java.lang.String
DEFAULT_METADATA_SERVER_URL
private static java.lang.String
GOOGLE
private static java.lang.String
LINUX
private static java.util.logging.Logger
LOGGER
(package private) static int
MAX_COMPUTE_PING_TRIES
private static java.lang.String
METADATA_FLAVOR
private static java.lang.String
PARSE_ERROR_ACCOUNT
private static java.lang.String
PARSE_ERROR_PREFIX
private java.util.Collection<java.lang.String>
scopes
private static long
serialVersionUID
private java.lang.String
serviceAccountEmail
(package private) static java.lang.String
SIGN_BLOB_URL_FORMAT
private HttpTransportFactory
transportFactory
private java.lang.String
transportFactoryClassName
private java.lang.String
universeDomainFromMetadata
private static java.lang.String
WINDOWS
-
Fields inherited from class com.google.auth.oauth2.GoogleCredentials
GDCH_SERVICE_ACCOUNT_FILE_TYPE, QUOTA_PROJECT_ID_HEADER_KEY, quotaProjectId, SERVICE_ACCOUNT_FILE_TYPE, USER_FILE_TYPE
-
Fields inherited from class com.google.auth.oauth2.OAuth2Credentials
clock, DEFAULT_EXPIRATION_MARGIN, DEFAULT_REFRESH_MARGIN, lock, refreshTask
-
Fields inherited from class com.google.auth.Credentials
GOOGLE_DEFAULT_UNIVERSE
-
-
Constructor Summary
Constructors Modifier Constructor Description private
ComputeEngineCredentials(ComputeEngineCredentials.Builder builder)
An internal constructor
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description (package private) static boolean
checkProductNameOnLinux(java.io.BufferedReader reader)
(package private) static boolean
checkStaticGceDetection(DefaultCredentialsProvider provider)
static ComputeEngineCredentials
create()
Create a new ComputeEngineCredentials instance with default behavior.GoogleCredentials
createScoped(java.util.Collection<java.lang.String> newScopes)
Clones the compute engine account with the specified scopes.GoogleCredentials
createScoped(java.util.Collection<java.lang.String> newScopes, java.util.Collection<java.lang.String> newDefaultScopes)
Clones the compute engine account with the specified scopes and default scopes.(package private) java.lang.String
createTokenUrlWithScopes()
If scopes is specified, add "?scopes=comma-separated-list-of-scopes" to the token url.boolean
equals(java.lang.Object obj)
java.lang.String
getAccount()
Returns the email address associated with the GCE default service account.private java.lang.String
getDefaultServiceAccount()
static java.lang.String
getIdentityDocumentUrl()
private com.google.api.client.http.HttpResponse
getMetadataResponse(java.lang.String url, MetricsUtils.RequestType requestType, boolean shouldSendMetricsHeader)
static java.lang.String
getMetadataServerUrl()
static java.lang.String
getMetadataServerUrl(DefaultCredentialsProvider provider)
CredentialTypeForMetrics
getMetricsCredentialType()
Gets the credential type used for internal metrics header.java.util.Collection<java.lang.String>
getScopes()
static java.lang.String
getServiceAccountsUrl()
static java.lang.String
getTokenServerEncodedUrl()
static java.lang.String
getTokenServerEncodedUrl(DefaultCredentialsProvider provider)
java.lang.String
getUniverseDomain()
Gets the universe domain from the GCE metadata server.private java.lang.String
getUniverseDomainFromMetadata()
static java.lang.String
getUniverseDomainUrl()
int
hashCode()
IdToken
idTokenWithAudience(java.lang.String targetAudience, java.util.List<IdTokenProvider.Option> options)
Returns a Google ID Token from the metadata server on ComputeEngine(package private) static boolean
isOnGce(HttpTransportFactory transportFactory, DefaultCredentialsProvider provider)
Implements an algorithm to detect whether the code is running on Google Compute Environment (GCE) or equivalent runtime.static ComputeEngineCredentials.Builder
newBuilder()
private static boolean
pingComputeEngineMetadata(HttpTransportFactory transportFactory, DefaultCredentialsProvider provider)
private void
readObject(java.io.ObjectInputStream input)
AccessToken
refreshAccessToken()
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.ComputeEngineCredentials.Builder
toBuilder()
protected com.google.common.base.MoreObjects.ToStringHelper
toStringHelper()
A helper for overriding the toString() method.-
Methods inherited from class com.google.auth.oauth2.GoogleCredentials
addQuotaProjectIdToRequestMetadata, create, create, createDelegated, createScoped, createScopedRequired, createWithCustomRetryStrategy, createWithQuotaProject, fromStream, fromStream, getAdditionalHeaders, getApplicationDefault, getApplicationDefault, getQuotaProjectId, isDefaultUniverseDomain, isExplicitUniverseDomain, toString
-
Methods inherited from class com.google.auth.oauth2.OAuth2Credentials
addChangeListener, getAccessToken, getAuthenticationType, getExpirationMargin, getFromServiceLoader, getRefreshMargin, getRequestMetadata, getRequestMetadata, getRequestMetadataInternal, hasRequestMetadata, hasRequestMetadataOnly, newInstance, refresh, refreshIfExpired, removeChangeListener
-
Methods inherited from class com.google.auth.Credentials
blockingGetToCallback, getRequestMetadata
-
-
-
-
Field Detail
-
COMPUTE_EXPIRATION_MARGIN
static final java.time.Duration COMPUTE_EXPIRATION_MARGIN
-
COMPUTE_REFRESH_MARGIN
static final java.time.Duration COMPUTE_REFRESH_MARGIN
-
LOGGER
private static final java.util.logging.Logger LOGGER
-
DEFAULT_METADATA_SERVER_URL
static final java.lang.String DEFAULT_METADATA_SERVER_URL
- See Also:
- Constant Field Values
-
SIGN_BLOB_URL_FORMAT
static final java.lang.String SIGN_BLOB_URL_FORMAT
- See Also:
- Constant Field Values
-
MAX_COMPUTE_PING_TRIES
static final int MAX_COMPUTE_PING_TRIES
- See Also:
- Constant Field Values
-
COMPUTE_PING_CONNECTION_TIMEOUT_MS
static final int COMPUTE_PING_CONNECTION_TIMEOUT_MS
- See Also:
- Constant Field Values
-
METADATA_FLAVOR
private static final java.lang.String METADATA_FLAVOR
- See Also:
- Constant Field Values
-
GOOGLE
private static final java.lang.String GOOGLE
- See Also:
- Constant Field Values
-
WINDOWS
private static final java.lang.String WINDOWS
- See Also:
- Constant Field Values
-
LINUX
private static final java.lang.String LINUX
- See Also:
- Constant Field Values
-
PARSE_ERROR_PREFIX
private static final java.lang.String PARSE_ERROR_PREFIX
- See Also:
- Constant Field Values
-
PARSE_ERROR_ACCOUNT
private static final java.lang.String PARSE_ERROR_ACCOUNT
- See Also:
- Constant Field Values
-
serialVersionUID
private static final long serialVersionUID
- See Also:
- Constant Field Values
-
transportFactoryClassName
private final java.lang.String transportFactoryClassName
-
scopes
private final java.util.Collection<java.lang.String> scopes
-
transportFactory
private transient HttpTransportFactory transportFactory
-
serviceAccountEmail
private transient java.lang.String serviceAccountEmail
-
universeDomainFromMetadata
private java.lang.String universeDomainFromMetadata
-
-
Constructor Detail
-
ComputeEngineCredentials
private ComputeEngineCredentials(ComputeEngineCredentials.Builder builder)
An internal constructor- Parameters:
builder
- A builder forComputeEngineCredentials
SeeComputeEngineCredentials.Builder
-
-
Method Detail
-
getMetricsCredentialType
public CredentialTypeForMetrics getMetricsCredentialType()
Description copied from class:Credentials
Gets 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:
getMetricsCredentialType
in classCredentials
- Returns:
- a enum value for credential type
-
createScoped
public GoogleCredentials createScoped(java.util.Collection<java.lang.String> newScopes)
Clones the compute engine account with the specified scopes.- Overrides:
createScoped
in classGoogleCredentials
- Parameters:
newScopes
- Collection of scopes to request.- Returns:
- GoogleCredentials with requested scopes.
-
createScoped
public GoogleCredentials createScoped(java.util.Collection<java.lang.String> newScopes, java.util.Collection<java.lang.String> newDefaultScopes)
Clones the compute engine account with the specified scopes and default scopes.- Overrides:
createScoped
in classGoogleCredentials
- Parameters:
newScopes
- Collection of scopes to request.newDefaultScopes
- Collection of default scopes to request.- Returns:
- GoogleCredentials with requested scopes.
-
create
public static ComputeEngineCredentials create()
Create a new ComputeEngineCredentials instance with default behavior.- Returns:
- new ComputeEngineCredentials
-
getScopes
public final java.util.Collection<java.lang.String> getScopes()
-
createTokenUrlWithScopes
java.lang.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
public java.lang.String getUniverseDomain() throws java.io.IOException
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_UNIVERSE
if 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:
getUniverseDomain
in classGoogleCredentials
- Returns:
- string representing a universe domain in the format some-domain.xyz
- Throws:
java.io.IOException
- if a call to GCE metadata service was unsuccessful. Check if exception implements theRetryable
andisRetryable()
will return true if the operation may be retried.
-
getUniverseDomainFromMetadata
private java.lang.String getUniverseDomainFromMetadata() throws java.io.IOException
- Throws:
java.io.IOException
-
refreshAccessToken
public AccessToken refreshAccessToken() throws java.io.IOException
Refresh the access token by getting it from the GCE metadata server- Overrides:
refreshAccessToken
in classOAuth2Credentials
- Returns:
- never
- Throws:
java.io.IOException
-
idTokenWithAudience
public IdToken idTokenWithAudience(java.lang.String targetAudience, java.util.List<IdTokenProvider.Option> options) throws java.io.IOException
Returns a Google ID Token from the metadata server on ComputeEngine- Specified by:
idTokenWithAudience
in 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:
java.io.IOException
- if the attempt to get an IdToken failed
-
getMetadataResponse
private com.google.api.client.http.HttpResponse getMetadataResponse(java.lang.String url, MetricsUtils.RequestType requestType, boolean shouldSendMetricsHeader) throws java.io.IOException
- Throws:
java.io.IOException
-
isOnGce
static boolean isOnGce(HttpTransportFactory transportFactory, DefaultCredentialsProvider provider)
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_URL
Passive: 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_VAR
set totrue
. In this case, the algorithm will always returnfalse
Returnstrue
if currently running on Google Compute Environment (GCE) or equivalent runtime. Returnsfalse
if detection fails, platform is not supported or if detection disabled using the environment variable.
-
checkProductNameOnLinux
static boolean checkProductNameOnLinux(java.io.BufferedReader reader) throws java.io.IOException
- Throws:
java.io.IOException
-
checkStaticGceDetection
static boolean checkStaticGceDetection(DefaultCredentialsProvider provider)
-
pingComputeEngineMetadata
private static boolean pingComputeEngineMetadata(HttpTransportFactory transportFactory, DefaultCredentialsProvider provider)
-
getMetadataServerUrl
public static java.lang.String getMetadataServerUrl(DefaultCredentialsProvider provider)
-
getMetadataServerUrl
public static java.lang.String getMetadataServerUrl()
-
getTokenServerEncodedUrl
public static java.lang.String getTokenServerEncodedUrl(DefaultCredentialsProvider provider)
-
getTokenServerEncodedUrl
public static java.lang.String getTokenServerEncodedUrl()
-
getUniverseDomainUrl
public static java.lang.String getUniverseDomainUrl()
-
getServiceAccountsUrl
public static java.lang.String getServiceAccountsUrl()
-
getIdentityDocumentUrl
public static java.lang.String getIdentityDocumentUrl()
-
hashCode
public int hashCode()
- Overrides:
hashCode
in classGoogleCredentials
-
toStringHelper
protected com.google.common.base.MoreObjects.ToStringHelper toStringHelper()
Description copied from class:GoogleCredentials
A 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:
toStringHelper
in classGoogleCredentials
- Returns:
- an instance of the ToStringHelper that has public fields added
-
equals
public boolean equals(java.lang.Object obj)
- Overrides:
equals
in classGoogleCredentials
-
readObject
private void readObject(java.io.ObjectInputStream input) throws java.io.IOException, java.lang.ClassNotFoundException
- Throws:
java.io.IOException
java.lang.ClassNotFoundException
-
toBuilder
public ComputeEngineCredentials.Builder toBuilder()
- Overrides:
toBuilder
in classGoogleCredentials
-
newBuilder
public static ComputeEngineCredentials.Builder newBuilder()
-
getAccount
public java.lang.String getAccount()
Returns the email address associated with the GCE default service account.- Specified by:
getAccount
in interfaceServiceAccountSigner
- Returns:
- The service account associated with the signer.
- Throws:
java.lang.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:
sign
in interfaceServiceAccountSigner
- Parameters:
toSign
- bytes to sign- Returns:
- signed bytes
- Throws:
ServiceAccountSigner.SigningException
- if the attempt to sign the provided bytes failed- See Also:
- Blob Signing
-
getDefaultServiceAccount
private java.lang.String getDefaultServiceAccount() throws java.io.IOException
- Throws:
java.io.IOException
-
-