From c3d396dc1fc6b4e781079de01a74b38bff2dc6ef Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Mon, 7 Nov 2016 10:58:40 +0100 Subject: [PATCH 1/4] Remove AuthCredentials and related classes, use google-auth-library-java instead --- README.md | 55 +- TESTING.md | 4 +- .../cloud/bigquery/BigQueryOptions.java | 2 +- .../testing/RemoteBigQueryHelper.java | 4 +- .../cloud/bigquery/SerializationTest.java | 5 +- .../google/cloud/compute/ComputeOptions.java | 2 +- .../compute/testing/RemoteComputeHelper.java | 4 +- .../cloud/compute/SerializationTest.java | 5 +- google-cloud-core/pom.xml | 4 +- .../com/google/cloud/AuthCredentials.java | 606 ------------------ .../com/google/cloud/GrpcServiceOptions.java | 10 +- .../com/google/cloud/HttpServiceOptions.java | 20 +- .../google/cloud/ServiceAccountSigner.java | 73 --- .../java/com/google/cloud/ServiceOptions.java | 77 +-- .../com/google/cloud/AuthCredentialsTest.java | 168 ----- .../google/cloud/HttpServiceOptionsTest.java | 2 +- .../com/google/cloud/SerializationTest.java | 19 +- .../com/google/cloud/ServiceOptionsTest.java | 31 +- .../cloud/datastore/DatastoreOptions.java | 2 +- .../testing/LocalDatastoreHelper.java | 3 +- .../cloud/datastore/DatastoreOptionsTest.java | 2 +- .../cloud/datastore/SerializationTest.java | 5 +- .../testing/LocalDatastoreHelperTest.java | 5 +- .../java/com/google/cloud/dns/DnsOptions.java | 2 +- .../cloud/dns/testing/LocalDnsHelper.java | 3 +- .../google/cloud/dns/SerializationTest.java | 5 +- .../examples/storage/StorageExample.java | 16 +- .../storage/snippets/BlobSnippets.java | 6 +- .../storage/snippets/StorageSnippets.java | 6 +- .../google/cloud/logging/LoggingOptions.java | 2 +- .../cloud/logging/spi/DefaultLoggingRpc.java | 6 +- .../logging/testing/RemoteLoggingHelper.java | 4 +- .../cloud/logging/SerializationTest.java | 3 +- .../google/cloud/pubsub/PubSubOptions.java | 2 +- .../cloud/pubsub/spi/DefaultPubSubRpc.java | 6 +- .../pubsub/testing/LocalPubsubHelper.java | 3 +- .../cloud/pubsub/SerializationTest.java | 3 +- .../ResourceManagerOptions.java | 2 +- .../testing/LocalResourceManagerHelper.java | 3 +- .../java/com/google/cloud/storage/Blob.java | 31 +- .../com/google/cloud/storage/Storage.java | 31 +- .../com/google/cloud/storage/StorageImpl.java | 14 +- .../google/cloud/storage/StorageOptions.java | 2 +- .../storage/testing/RemoteStorageHelper.java | 4 +- .../cloud/storage/SerializationTest.java | 5 +- .../google/cloud/storage/StorageImplTest.java | 32 +- .../cloud/translate/TranslateOptions.java | 21 +- .../cloud/translate/SerializationTest.java | 5 +- pom.xml | 9 + 49 files changed, 241 insertions(+), 1093 deletions(-) delete mode 100644 google-cloud-core/src/main/java/com/google/cloud/AuthCredentials.java delete mode 100644 google-cloud-core/src/main/java/com/google/cloud/ServiceAccountSigner.java delete mode 100644 google-cloud-core/src/test/java/com/google/cloud/AuthCredentialsTest.java diff --git a/README.md b/README.md index 252f7dc1f833..e83789aa5434 100644 --- a/README.md +++ b/README.md @@ -115,40 +115,63 @@ Most `google-cloud` libraries require a project ID. There are multiple ways to Authentication -------------- -First, ensure that the necessary Google Cloud APIs are enabled for your project. To do this, follow the instructions on the [authentication document](https://github.com/GoogleCloudPlatform/gcloud-common/blob/master/authentication/readme.md#authentication) shared by all the gcloud language libraries. +`google-cloud-java` uses +[https://github.com/google/google-auth-library-java](https://github.com/google/google-auth-library-java) +to authenticate requests. `google-auth-library-java` supports a wide range of authentication types, +see the project's [README](https://github.com/google/google-auth-library-java/blob/master/README.md) +and [javadoc](http://google.github.io/google-auth-library-java/releases/0.6.0/apidocs/) for more +details. + +To access Google Cloud services, you first need to ensure that the necessary Google Cloud APIs are +enabled for your project. To do this, follow the instructions on the +[authentication document](https://github.com/GoogleCloudPlatform/gcloud-common/blob/master/authentication/readme.md#authentication) +shared by all the Google Cloud language libraries. Next, choose a method for authenticating API requests from within your project: -1. When using `google-cloud` libraries from within Compute/App Engine, no additional authentication steps are necessary. -2. When using `google-cloud` libraries elsewhere, there are three options: - * [Generate a JSON service account key](https://cloud.google.com/storage/docs/authentication?hl=en#service_accounts). After downloading that key, you must do one of the following: - * Define the environment variable GOOGLE_APPLICATION_CREDENTIALS to be the location of the key. For example: +1. When using `google-cloud` libraries from within Compute/App Engine, no additional authentication +steps are necessary. For example: +```java +Storage storage = StorageOptions.getDefaultInstance().getService(); +``` +2. When using `google-cloud` libraries elsewhere, there are several options: + * [Generate a JSON service account key](https://cloud.google.com/storage/docs/authentication?hl=en#service_accounts). + After downloading that key, you must do one of the following: + * Define the environment variable GOOGLE_APPLICATION_CREDENTIALS to be the location of the key. + For example: ```bash export GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/key.json ``` - * Supply the JSON credentials file when building the service options. For example, this Storage object has the necessary permissions to interact with your Google Cloud Storage data: + * Supply the JSON credentials file when building the service options. For example, this Storage + object has the necessary permissions to interact with your Google Cloud Storage data: ```java Storage storage = StorageOptions.newBuilder() - .setAuthCredentials(AuthCredentials.createForJson(new FileInputStream("/path/to/my/key.json")) + .setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream("/path/to/my/key.json")) .build() .getService(); ``` - * If running locally for development/testing, you can use Google Cloud SDK. Download the SDK if you haven't already, then login using the SDK (`gcloud auth login` in command line). Be sure to set your project ID as described above. - * If you already have an OAuth2 access token, you can use it to authenticate (notice that in this case the access token will not be automatically refreshed): + * If running locally for development/testing, you can use the + [Google Cloud SDK](https://cloud.google.com/sdk/). Create Application Default Credentials with + `gcloud auth application-default login`, `google-cloud` will automatically detect such + credentials. + * If you already have an OAuth2 access token, you can use it to authenticate (notice that in this + case the access token will not be automatically refreshed): ```java Storage storage = StorageOptions.newBuilder() - .setAuthCredentials(AuthCredentials.createFor("your_access_token")) + .setCredentials(new GoogleCredentials(new AccessToken(accessToken, expirationTime))) .build() .getService(); ``` -`google-cloud` looks for credentials in the following order, stopping once it finds credentials: +If no credentials are provided, `google-cloud` will attempt to detect them from the environment +using `GoogleCredentials.getApplicationDefault()` which will search for Default Application +Credentials in the following locations (in order): -1. Credentials supplied when building the service options -2. App Engine credentials -3. Key file pointed to by the GOOGLE_APPLICATION_CREDENTIALS environment variable -4. Google Cloud SDK credentials -5. Compute Engine credentials +1. Credentials file pointed to by the `GOOGLE_APPLICATION_CREDENTIALS` environment variable +2. Credentials provided by the Google Cloud SDK `gcloud auth application-default login` command +3. Google App Engine built-in credentials +4. Google Cloud Shell built-in credentials +5. Google Compute Engine built-in credentials Google Cloud BigQuery (Alpha) ---------------------- diff --git a/TESTING.md b/TESTING.md index ebb0ee08570b..78908e2b98b0 100644 --- a/TESTING.md +++ b/TESTING.md @@ -102,7 +102,7 @@ You can test against a remote Datastore emulator as well. To do this, set the ` DatastoreOptions options = DatastoreOptions.newBuilder() .setProjectId("my-project-id") // must match project ID specified on remote machine .setHost("http://:") - .setAuthCredentials(AuthCredentials.noAuth()) + .setNoCredentials() .build(); Datastore localDatastore = options.getService(); ``` @@ -209,7 +209,7 @@ endpoint to the hostname of the remote machine, like the example below. PubSubOptions options = PubSubOptions.newBuilder() .setProjectId("my-project-id") // must match project ID specified on remote machine .setHost(":") - .setAuthCredentials(AuthCredentials.noAuth()) + .setNoCredentials() .build(); PubSub localPubsub = options.getService(); ``` diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryOptions.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryOptions.java index 4922a1a8d5d9..2f8c8844b57b 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryOptions.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryOptions.java @@ -28,7 +28,7 @@ public class BigQueryOptions extends HttpServiceOptions SCOPES = ImmutableSet.of(BIGQUERY_SCOPE); - private static final long serialVersionUID = -8592198255032667206L; + private static final long serialVersionUID = -2437598817433266049L; public static class DefaultBigqueryFactory implements BigQueryFactory { diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelper.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelper.java index e2f6b5f74bf1..072c77aec4a9 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelper.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelper.java @@ -16,7 +16,7 @@ package com.google.cloud.bigquery.testing; -import com.google.cloud.AuthCredentials; +import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.RetryParams; import com.google.cloud.bigquery.BigQuery; import com.google.cloud.bigquery.BigQueryException; @@ -96,7 +96,7 @@ public static RemoteBigQueryHelper create(String projectId, InputStream keyStrea throws BigQueryHelperException { try { BigQueryOptions bigqueryOptions = BigQueryOptions.newBuilder() - .setAuthCredentials(AuthCredentials.createForJson(keyStream)) + .setCredentials(ServiceAccountCredentials.fromStream(keyStream)) .setProjectId(projectId) .setRetryParams(retryParams()) .setConnectTimeout(60000) diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java index 6f91a1427f4e..542b72e1c693 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java @@ -16,7 +16,6 @@ package com.google.cloud.bigquery; -import com.google.cloud.AuthCredentials; import com.google.cloud.BaseSerializationTest; import com.google.cloud.Restorable; import com.google.cloud.bigquery.StandardTableDefinition.StreamingBuffer; @@ -229,11 +228,11 @@ public class SerializationTest extends BaseSerializationTest { protected Serializable[] serializableObjects() { BigQueryOptions options = BigQueryOptions.newBuilder() .setProjectId("p1") - .setAuthCredentials(AuthCredentials.createForAppEngine()) + .setNoCredentials() .build(); BigQueryOptions otherOptions = options.toBuilder() .setProjectId("p2") - .setAuthCredentials(null) + .setCredentials(null) .build(); return new Serializable[]{DOMAIN_ACCESS, GROUP_ACCESS, USER_ACCESS, VIEW_ACCESS, DATASET_ID, DATASET_INFO, TABLE_ID, CSV_OPTIONS, STREAMING_BUFFER, TABLE_DEFINITION, diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeOptions.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeOptions.java index b95c64243515..176417ab2d39 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeOptions.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeOptions.java @@ -28,7 +28,7 @@ public class ComputeOptions extends HttpServiceOptions SCOPES = ImmutableSet.of(COMPUTE_SCOPE); - private static final long serialVersionUID = 5074781985597996770L; + private static final long serialVersionUID = 6983703596543425691L; public static class DefaultComputeFactory implements ComputeFactory { diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/RemoteComputeHelper.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/RemoteComputeHelper.java index ac39acd94ad4..dcf4e1b462d1 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/RemoteComputeHelper.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/RemoteComputeHelper.java @@ -16,7 +16,7 @@ package com.google.cloud.compute.testing; -import com.google.cloud.AuthCredentials; +import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.RetryParams; import com.google.cloud.compute.ComputeOptions; @@ -83,7 +83,7 @@ public static String baseResourceName() { public static RemoteComputeHelper create(String projectId, InputStream keyStream) { try { ComputeOptions computeOptions = ComputeOptions.newBuilder() - .setAuthCredentials(AuthCredentials.createForJson(keyStream)) + .setCredentials(ServiceAccountCredentials.fromStream(keyStream)) .setProjectId(projectId) .setRetryParams(retryParams()) .setConnectTimeout(60000) diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java index eb9d52bfea5b..5d98610d98a9 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java @@ -16,7 +16,6 @@ package com.google.cloud.compute; -import com.google.cloud.AuthCredentials; import com.google.cloud.BaseSerializationTest; import com.google.cloud.Restorable; import com.google.cloud.RetryParams; @@ -265,12 +264,12 @@ public class SerializationTest extends BaseSerializationTest { protected Serializable[] serializableObjects() { ComputeOptions options = ComputeOptions.newBuilder() .setProjectId("p1") - .setAuthCredentials(AuthCredentials.createForAppEngine()) + .setNoCredentials() .build(); ComputeOptions otherOptions = options.toBuilder() .setProjectId("p2") .setRetryParams(RetryParams.getDefaultInstance()) - .setAuthCredentials(null) + .setCredentials(null) .build(); return new Serializable[]{DISK_TYPE_ID, DISK_TYPE, MACHINE_TYPE_ID, MACHINE_TYPE, REGION_ID, REGION, ZONE_ID, ZONE, LICENSE_ID, LICENSE, DEPRECATION_STATUS, GLOBAL_OPERATION_ID, diff --git a/google-cloud-core/pom.xml b/google-cloud-core/pom.xml index 116007ee3d1e..cb46970a7933 100644 --- a/google-cloud-core/pom.xml +++ b/google-cloud-core/pom.xml @@ -20,12 +20,12 @@ com.google.auth google-auth-library-credentials - 0.3.1 + ${google.auth.version} com.google.auth google-auth-library-oauth2-http - 0.3.1 + ${google.auth.version} com.google.guava diff --git a/google-cloud-core/src/main/java/com/google/cloud/AuthCredentials.java b/google-cloud-core/src/main/java/com/google/cloud/AuthCredentials.java deleted file mode 100644 index 257e801c6f3b..000000000000 --- a/google-cloud-core/src/main/java/com/google/cloud/AuthCredentials.java +++ /dev/null @@ -1,606 +0,0 @@ -/* - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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. - */ - -package com.google.cloud; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.auth.oauth2.AccessToken; -import com.google.auth.oauth2.GoogleCredentials; -import com.google.auth.oauth2.ServiceAccountCredentials; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Serializable; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.Signature; -import java.security.SignatureException; -import java.util.Collection; -import java.util.Date; -import java.util.Objects; - -/** - * Credentials for accessing Google Cloud services. - */ -public abstract class AuthCredentials implements Restorable { - - /** - * Represents built-in credentials when running in Google App Engine. - */ - public static class AppEngineAuthCredentials extends AuthCredentials - implements ServiceAccountSigner { - - private static final AuthCredentials INSTANCE = new AppEngineAuthCredentials(); - private static final AppEngineAuthCredentialsState STATE = new AppEngineAuthCredentialsState(); - - private AppEngineCredentials credentials; - - private static class AppEngineCredentials extends GoogleCredentials - implements ServiceAccountSigner { - - private final Object appIdentityService; - private final String account; - private final Method getAccessToken; - private final Method getAccessTokenResult; - private final Method getExpirationTime; - private final Method signForApp; - private final Method getSignature; - private final Collection scopes; - - AppEngineCredentials() { - try { - Class factoryClass = - Class.forName("com.google.appengine.api.appidentity.AppIdentityServiceFactory"); - Method method = factoryClass.getMethod("getAppIdentityService"); - this.appIdentityService = method.invoke(null); - Class serviceClass = - Class.forName("com.google.appengine.api.appidentity.AppIdentityService"); - Class tokenResultClass = Class.forName( - "com.google.appengine.api.appidentity.AppIdentityService$GetAccessTokenResult"); - this.getAccessTokenResult = serviceClass.getMethod("getAccessToken", Iterable.class); - this.getAccessToken = tokenResultClass.getMethod("getAccessToken"); - this.getExpirationTime = tokenResultClass.getMethod("getExpirationTime"); - this.account = (String) serviceClass.getMethod("getServiceAccountName") - .invoke(appIdentityService); - this.signForApp = serviceClass.getMethod("signForApp", byte[].class); - Class signingResultClass = Class.forName( - "com.google.appengine.api.appidentity.AppIdentityService$SigningResult"); - this.getSignature = signingResultClass.getMethod("getSignature"); - this.scopes = null; - } catch (Exception e) { - throw new RuntimeException("Could not create AppEngineCredentials.", e); - } - } - - AppEngineCredentials(Collection scopes, AppEngineCredentials unscoped) { - this.appIdentityService = unscoped.appIdentityService; - this.getAccessToken = unscoped.getAccessToken; - this.getAccessTokenResult = unscoped.getAccessTokenResult; - this.getExpirationTime = unscoped.getExpirationTime; - this.account = unscoped.account; - this.signForApp = unscoped.signForApp; - this.getSignature = unscoped.getSignature; - this.scopes = scopes; - } - - /** - * Refresh the access token by getting it from the App Identity service. - */ - @Override - public AccessToken refreshAccessToken() throws IOException { - if (createScopedRequired()) { - throw new IOException("AppEngineCredentials requires createScoped call before use."); - } - try { - Object accessTokenResult = getAccessTokenResult.invoke(appIdentityService, scopes); - String accessToken = (String) getAccessToken.invoke(accessTokenResult); - Date expirationTime = (Date) getExpirationTime.invoke(accessTokenResult); - return new AccessToken(accessToken, expirationTime); - } catch (Exception e) { - throw new IOException("Could not get the access token.", e); - } - } - - @Override - public boolean createScopedRequired() { - return scopes == null || scopes.isEmpty(); - } - - @Override - public GoogleCredentials createScoped(Collection scopes) { - return new AppEngineCredentials(scopes, this); - } - - @Override - public String account() { - return getAccount(); - } - - @Override - public String getAccount() { - return account; - } - - @Override - public byte[] sign(byte[] toSign) { - try { - Object signingResult = signForApp.invoke(appIdentityService, toSign); - return (byte[]) getSignature.invoke(signingResult); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { - throw new SigningException("Failed to sign the provided bytes", ex); - } - } - } - - private static class AppEngineAuthCredentialsState - implements RestorableState, Serializable { - - private static final long serialVersionUID = 3558563960848658928L; - - @Override - public AuthCredentials restore() { - return INSTANCE; - } - - @Override - public int hashCode() { - return getClass().getName().hashCode(); - } - - @Override - public boolean equals(Object obj) { - return obj instanceof AppEngineAuthCredentialsState; - } - } - - @Override - @Deprecated - public AppEngineCredentials credentials() { - return getCredentials(); - } - - @Override - public AppEngineCredentials getCredentials() { - if (credentials == null) { - credentials = new AppEngineCredentials(); - } - return credentials; - } - - @Override - public RestorableState capture() { - return STATE; - } - - @Override - @Deprecated - public String account() { - return getAccount(); - } - - @Override - public String getAccount() { - return getCredentials().getAccount(); - } - - @Override - public byte[] sign(byte[] toSign) { - return getCredentials().sign(toSign); - } - } - - /** - * Represents service account credentials. - * - * @see - * User accounts and service accounts - */ - public static class ServiceAccountAuthCredentials extends AuthCredentials - implements ServiceAccountSigner { - - private final ServiceAccountCredentials credentials; - private final String account; - private final PrivateKey privateKey; - - private static class ServiceAccountAuthCredentialsState - implements RestorableState, Serializable { - - private static final long serialVersionUID = -7302180782414633639L; - - private final String account; - private final PrivateKey privateKey; - - private ServiceAccountAuthCredentialsState(String account, PrivateKey privateKey) { - this.account = account; - this.privateKey = privateKey; - } - - @Override - public AuthCredentials restore() { - return new ServiceAccountAuthCredentials(account, privateKey); - } - - @Override - public int hashCode() { - return Objects.hash(account, privateKey); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof ServiceAccountAuthCredentialsState)) { - return false; - } - ServiceAccountAuthCredentialsState other = (ServiceAccountAuthCredentialsState) obj; - return Objects.equals(account, other.account) - && Objects.equals(privateKey, other.privateKey); - } - } - - ServiceAccountAuthCredentials(String account, PrivateKey privateKey) { - this(new ServiceAccountCredentials(null, account, privateKey, null, null)); - } - - ServiceAccountAuthCredentials(ServiceAccountCredentials credentials) { - this.credentials = checkNotNull(credentials); - this.account = checkNotNull(credentials.getClientEmail()); - this.privateKey = checkNotNull(credentials.getPrivateKey()); - } - - @Override - @Deprecated - public ServiceAccountCredentials credentials() { - return getCredentials(); - } - - @Override - public ServiceAccountCredentials getCredentials() { - return credentials; - } - - @Override - @Deprecated - public String account() { - return account; - } - - @Override - public String getAccount() { - return account; - } - - /** - * Returns the private key associated with the service account credentials. - */ - @Deprecated - public PrivateKey privateKey() { - return getPrivateKey(); - } - - /** - * Returns the private key associated with the service account credentials. - */ - public PrivateKey getPrivateKey() { - return privateKey; - } - - @Override - public byte[] sign(byte[] toSign) { - try { - Signature signer = Signature.getInstance("SHA256withRSA"); - signer.initSign(getPrivateKey()); - signer.update(toSign); - return signer.sign(); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException ex) { - throw new SigningException("Failed to sign the provided bytes", ex); - } - } - - @Override - public RestorableState capture() { - return new ServiceAccountAuthCredentialsState(account, privateKey); - } - } - - /** - * Represents Application Default Credentials, which are credentials that are inferred from the - * runtime environment. - * - * @see - * Google Application Default Credentials - */ - public static class ApplicationDefaultAuthCredentials extends AuthCredentials { - - private GoogleCredentials googleCredentials; - - private static final ApplicationDefaultAuthCredentialsState STATE = - new ApplicationDefaultAuthCredentialsState(); - - private static class ApplicationDefaultAuthCredentialsState - implements RestorableState, Serializable { - - private static final long serialVersionUID = -8839085552021212257L; - - @Override - public AuthCredentials restore() { - try { - return new ApplicationDefaultAuthCredentials(); - } catch (IOException e) { - throw new IllegalStateException( - "Could not restore " + ApplicationDefaultAuthCredentials.class.getSimpleName(), e); - } - } - - @Override - public int hashCode() { - return getClass().getName().hashCode(); - } - - @Override - public boolean equals(Object obj) { - return obj instanceof ApplicationDefaultAuthCredentialsState; - } - } - - ApplicationDefaultAuthCredentials(GoogleCredentials credentials) { - googleCredentials = credentials; - } - - ApplicationDefaultAuthCredentials() throws IOException { - googleCredentials = GoogleCredentials.getApplicationDefault(); - } - - @Override - @Deprecated - public GoogleCredentials credentials() { - return getCredentials(); - } - - @Override - public GoogleCredentials getCredentials() { - return googleCredentials; - } - - @Override - public RestorableState capture() { - return STATE; - } - } - - /** - * Represents OAuth2 credentials. These credentials can be created given an OAuth2 access token. - * The access token will not be automatically refreshed. - */ - public static class OAuth2AuthCredentials extends AuthCredentials { - - private final GoogleCredentials credentials; - private final String accessToken; - private final Date expirationTime; - - private static class OAuth2AuthCredentialsState - implements RestorableState, Serializable { - - private static final long serialVersionUID = -7760693952274496205L; - - private final String accessToken; - private final Date expirationTime; - - private OAuth2AuthCredentialsState(String accessToken, Date expirationTime) { - this.accessToken = accessToken; - this.expirationTime = expirationTime; - } - - @Override - public AuthCredentials restore() { - return new OAuth2AuthCredentials(accessToken, expirationTime); - } - - @Override - public int hashCode() { - return Objects.hash(accessToken, expirationTime); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof OAuth2AuthCredentialsState)) { - return false; - } - OAuth2AuthCredentialsState other = (OAuth2AuthCredentialsState) obj; - return Objects.equals(accessToken, other.accessToken) - && Objects.equals(expirationTime, other.expirationTime); - } - } - - OAuth2AuthCredentials(String accessToken, Date expirationTime) { - this.accessToken = checkNotNull(accessToken); - this.expirationTime = expirationTime; - this.credentials = new GoogleCredentials(new AccessToken(accessToken, expirationTime)); - } - - @Override - @Deprecated - public GoogleCredentials credentials() { - return getCredentials(); - } - - @Override - public GoogleCredentials getCredentials() { - return credentials; - } - - @Override - public RestorableState capture() { - return new OAuth2AuthCredentialsState(accessToken, expirationTime); - } - } - - /** - * A placeholder for credentials to signify that requests sent to the server should not be - * authenticated. This is typically useful when using the local service emulators, such as - * {@code LocalDatastoreHelper} and {@code LocalResourceManagerHelper}. - */ - public static class NoAuthCredentials extends AuthCredentials { - - private static final AuthCredentials INSTANCE = new NoAuthCredentials(); - private static final NoAuthCredentialsState STATE = new NoAuthCredentialsState(); - - private static class NoAuthCredentialsState - implements RestorableState, Serializable { - - private static final long serialVersionUID = -4022100563954640465L; - - @Override - public AuthCredentials restore() { - return INSTANCE; - } - - @Override - public int hashCode() { - return getClass().getName().hashCode(); - } - - @Override - public boolean equals(Object obj) { - return obj instanceof NoAuthCredentialsState; - } - } - - private NoAuthCredentials() {} - - @Override - @Deprecated - public GoogleCredentials credentials() { - return getCredentials(); - } - - @Override - public GoogleCredentials getCredentials() { - return null; - } - - @Override - public RestorableState capture() { - return STATE; - } - } - - @Deprecated - public abstract GoogleCredentials credentials(); - - public abstract GoogleCredentials getCredentials(); - - public static AuthCredentials createForAppEngine() { - return AppEngineAuthCredentials.INSTANCE; - } - - /** - * Returns the Application Default Credentials. - * - *

Returns the Application Default Credentials which are credentials that identify and - * authorize the whole application. This is the built-in service account if running on - * Google Compute Engine or the credentials file can be read from the path in the environment - * variable GOOGLE_APPLICATION_CREDENTIALS. - *

- * - * @return the credentials instance - * @throws IOException if the credentials cannot be created in the current environment - */ - public static AuthCredentials createApplicationDefaults() throws IOException { - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); - if (credentials instanceof ServiceAccountCredentials) { - ServiceAccountCredentials serviceAccountCredentials = (ServiceAccountCredentials) credentials; - return new ServiceAccountAuthCredentials(serviceAccountCredentials); - } - return new ApplicationDefaultAuthCredentials(credentials); - } - - /** - * Creates Service Account Credentials given an account id and a private key. - * - *

For details on how to obtain Service Account Credentials see - * Service - * Account Authentication. - *

- * - * @param account id of the Service Account - * @param privateKey private key associated to the account - * @return the credentials instance - */ - public static ServiceAccountAuthCredentials createFor(String account, PrivateKey privateKey) { - return new ServiceAccountAuthCredentials(account, privateKey); - } - - /** - * Creates OAuth2 Credentials given the string representation of an access token. The access token - * will not be automatically refreshed. - * - * @param accessToken string representation of an access token - * @return the credentials instance - */ - public static OAuth2AuthCredentials createFor(String accessToken) { - return createFor(accessToken, (Date) null); - } - - /** - * Creates OAuth2 Credentials given the string representation of an access token and its - * expiration time. The access token will not be automatically refreshed. - * - * @param accessToken string representation of an access token - * @return the credentials instance - */ - public static OAuth2AuthCredentials createFor(String accessToken, Date expirationTime) { - return new OAuth2AuthCredentials(accessToken, expirationTime); - } - - /** - * Creates a placeholder denoting that no credentials should be used. This is typically useful - * when using the local service emulators, such as {@code LocalDatastoreHelper} and - * {@code LocalResourceManagerHelper}. - */ - public static AuthCredentials noAuth() { - return NoAuthCredentials.INSTANCE; - } - - /** - * Creates Service Account Credentials given a stream for credentials in JSON format. - * - *

For details on how to obtain Service Account Credentials in JSON format see - * Service - * Account Authentication. - *

- * - * @param jsonCredentialStream stream for Service Account Credentials in JSON format - * @return the credentials instance - * @throws IOException if the credentials cannot be created from the stream - */ - public static ServiceAccountAuthCredentials createForJson(InputStream jsonCredentialStream) - throws IOException { - GoogleCredentials tempCredentials = GoogleCredentials.fromStream(jsonCredentialStream); - if (tempCredentials instanceof ServiceAccountCredentials) { - ServiceAccountCredentials tempServiceAccountCredentials = - (ServiceAccountCredentials) tempCredentials; - return new ServiceAccountAuthCredentials( - tempServiceAccountCredentials.getClientEmail(), - tempServiceAccountCredentials.getPrivateKey()); - } - throw new IOException( - "The given JSON Credentials Stream is not for a service account credential."); - } -} diff --git a/google-cloud-core/src/main/java/com/google/cloud/GrpcServiceOptions.java b/google-cloud-core/src/main/java/com/google/cloud/GrpcServiceOptions.java index e0017e09191c..03d180d736fd 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/GrpcServiceOptions.java +++ b/google-cloud-core/src/main/java/com/google/cloud/GrpcServiceOptions.java @@ -21,7 +21,7 @@ import com.google.api.gax.core.ConnectionSettings; import com.google.api.gax.core.RetrySettings; import com.google.api.gax.grpc.UnaryCallSettings; -import com.google.auth.oauth2.GoogleCredentials; +import com.google.auth.Credentials; import com.google.cloud.spi.ServiceRpcFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; @@ -52,7 +52,7 @@ public abstract class GrpcServiceOptions, Ser OptionsT extends GrpcServiceOptions> extends ServiceOptions { - private static final long serialVersionUID = 6415982522610509549L; + private static final long serialVersionUID = -3093986242928037007L; private final String executorFactoryClassName; private final int initialTimeout; private final double timeoutMultiplier; @@ -319,9 +319,9 @@ protected ConnectionSettings.Builder getConnectionSettings() { ConnectionSettings.Builder builder = ConnectionSettings.newBuilder() .setServiceAddress(hostAndPort.getHostText()) .setPort(hostAndPort.getPort()); - GoogleCredentials credentials = getAuthCredentials().getCredentials(); - if (credentials != null) { - builder.provideCredentialsWith(credentials.createScoped(getScopes())); + Credentials scopedCredentials = getScopedCredentials(); + if (scopedCredentials != null) { + builder.provideCredentialsWith(scopedCredentials); } return builder; } diff --git a/google-cloud-core/src/main/java/com/google/cloud/HttpServiceOptions.java b/google-cloud-core/src/main/java/com/google/cloud/HttpServiceOptions.java index 9e49d537f375..515877e0b961 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/HttpServiceOptions.java +++ b/google-cloud-core/src/main/java/com/google/cloud/HttpServiceOptions.java @@ -23,7 +23,9 @@ import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.auth.Credentials; import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.http.HttpTransportFactory; import com.google.cloud.spi.ServiceRpcFactory; import java.io.IOException; @@ -42,23 +44,13 @@ public abstract class HttpServiceOptions, Ser OptionsT extends HttpServiceOptions> extends ServiceOptions { - private static final long serialVersionUID = 3652819407083815771L; + private static final long serialVersionUID = 4765436436821178975L; private final int connectTimeout; private final int readTimeout; private final String httpTransportFactoryClassName; private transient HttpTransportFactory httpTransportFactory; - /** - * A base interface for all {@link HttpTransport} factories. - * - *

Implementation must provide a public no-arg constructor. Loading of a factory implementation - * is done via {@link java.util.ServiceLoader}. - */ - public interface HttpTransportFactory { - HttpTransport create(); - } - public static class DefaultHttpTransportFactory implements HttpTransportFactory { private static final HttpTransportFactory INSTANCE = new DefaultHttpTransportFactory(); @@ -221,11 +213,9 @@ public HttpRequestInitializer httpRequestInitializer() { * options. */ public HttpRequestInitializer getHttpRequestInitializer() { + Credentials scopedCredentials = getScopedCredentials(); final HttpRequestInitializer delegate = - getAuthCredentials() != null && getAuthCredentials().getCredentials() != null - ? new HttpCredentialsAdapter( - getAuthCredentials().getCredentials().createScoped(getScopes())) - : null; + scopedCredentials != null ? new HttpCredentialsAdapter(scopedCredentials) : null; return new HttpRequestInitializer() { @Override public void initialize(HttpRequest httpRequest) throws IOException { diff --git a/google-cloud-core/src/main/java/com/google/cloud/ServiceAccountSigner.java b/google-cloud-core/src/main/java/com/google/cloud/ServiceAccountSigner.java deleted file mode 100644 index 29202c69d0ae..000000000000 --- a/google-cloud-core/src/main/java/com/google/cloud/ServiceAccountSigner.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * 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. - */ - -package com.google.cloud; - -import java.util.Objects; - -/** - * Interface for a service account signer. A signer for a service account is capable of signing - * bytes using the private key associated with its service account. - */ -public interface ServiceAccountSigner { - - class SigningException extends RuntimeException { - - private static final long serialVersionUID = 8962780757822799255L; - - SigningException(String message, Exception cause) { - super(message, cause); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof SigningException)) { - return false; - } - SigningException other = (SigningException) obj; - return Objects.equals(getCause(), other.getCause()) - && Objects.equals(getMessage(), other.getMessage()); - } - - @Override - public int hashCode() { - return Objects.hash(getMessage(), getCause()); - } - } - - /** - * Returns the service account associated with the signer. - */ - @Deprecated - String account(); - - /** - * Returns the service account associated with the signer. - */ - String getAccount(); - - /** - * Signs the provided bytes using the private key associated with the service account. - * - * @param toSign bytes to sign - * @return signed bytes - * @throws SigningException if the attempt to sign the provided bytes failed - */ - byte[] sign(byte[] toSign); -} diff --git a/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java b/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java index f918cd2188c4..33ecac6eee1a 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java +++ b/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java @@ -20,6 +20,8 @@ import static com.google.common.base.Preconditions.checkArgument; import static java.nio.charset.StandardCharsets.UTF_8; +import com.google.auth.Credentials; +import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.spi.ServiceRpcFactory; import com.google.common.collect.Iterables; import com.google.common.io.Files; @@ -73,17 +75,17 @@ public abstract class ServiceOptions, Service private static final String LIBRARY_VERSION = defaultLibraryVersion(); private static final String APPLICATION_NAME = LIBRARY_VERSION == null ? LIBRARY_NAME : LIBRARY_NAME + "/" + LIBRARY_VERSION; - private static final long serialVersionUID = 3049375916337507361L; + private static final long serialVersionUID = -5714029257168617973L; private final String projectId; private final String host; - private final RestorableState authCredentialsState; private final RetryParams retryParams; private final String serviceRpcFactoryClassName; private final String serviceFactoryClassName; private final Clock clock; + private final boolean noCredentials; + private final Credentials credentials; - private transient AuthCredentials authCredentials; private transient ServiceRpcFactory serviceRpcFactory; private transient ServiceFactory serviceFactory; private transient ServiceT service; @@ -103,7 +105,8 @@ protected abstract static class Builder, Serv private String projectId; private String host; - private AuthCredentials authCredentials; + private boolean noCredentials; + private Credentials credentials; private RetryParams retryParams; private ServiceFactory serviceFactory; private ServiceRpcFactory serviceRpcFactory; @@ -114,7 +117,8 @@ protected Builder() {} protected Builder(ServiceOptions options) { projectId = options.projectId; host = options.host; - authCredentials = options.authCredentials; + noCredentials = options.noCredentials; + credentials = options.credentials; retryParams = options.retryParams; serviceFactory = options.serviceFactory; serviceRpcFactory = options.serviceRpcFactory; @@ -213,18 +217,20 @@ public B setHost(String host) { * * @return the builder */ - @Deprecated - public B authCredentials(AuthCredentials authCredentials) { - return setAuthCredentials(authCredentials); + public B setCredentials(Credentials credentials) { + this.noCredentials = false; + this.credentials = credentials; + return self(); } /** - * Sets the service authentication credentials. - * - * @return the builder + * Sets that no credentials should be used. This is typically useful when using the local + * service emulators, such as {@code LocalDatastoreHelper}, {@code LocalPubsubHelper} and + * {@code LocalResourceManagerHelper}. */ - public B setAuthCredentials(AuthCredentials authCredentials) { - this.authCredentials = authCredentials; + public B setNoCredentials() { + this.noCredentials = true; + this.credentials = null; return self(); } @@ -284,9 +290,9 @@ protected ServiceOptions(Class> ser + "or the environment. Please set a project ID using the builder."); } host = firstNonNull(builder.host, getDefaultHost()); - authCredentials = - builder.authCredentials != null ? builder.authCredentials : defaultAuthCredentials(); - authCredentialsState = authCredentials != null ? authCredentials.capture() : null; + noCredentials = builder.noCredentials; + credentials = builder.credentials != null || noCredentials + ? builder.credentials : defaultCredentials(); retryParams = firstNonNull(builder.retryParams, defaultRetryParams()); serviceFactory = firstNonNull(builder.serviceFactory, getFromServiceLoader(serviceFactoryClass, getDefaultServiceFactory())); @@ -307,18 +313,9 @@ protected boolean projectIdRequired() { return true; } - private static AuthCredentials defaultAuthCredentials() { - // Consider App Engine. - if (appEngineAppId() != null) { - try { - return AuthCredentials.createForAppEngine(); - } catch (Exception ignore) { - // Maybe not on App Engine - } - } - + private static GoogleCredentials defaultCredentials() { try { - return AuthCredentials.createApplicationDefaults(); + return GoogleCredentials.getApplicationDefault(); } catch (Exception ex) { return null; } @@ -528,16 +525,20 @@ public String getHost() { /** * Returns the authentication credentials. */ - @Deprecated - public AuthCredentials authCredentials() { - return getAuthCredentials(); + public Credentials getCredentials() { + return credentials; } /** - * Returns the authentication credentials. + * Returns the authentication credentials. If required, credentials are scoped. */ - public AuthCredentials getAuthCredentials() { - return authCredentials; + public Credentials getScopedCredentials() { + Credentials credentialsToReturn = credentials; + if (credentials instanceof GoogleCredentials && + ((GoogleCredentials) credentials).createScopedRequired()) { + credentialsToReturn = ((GoogleCredentials) credentials).createScoped(getScopes()); + } + return credentialsToReturn; } /** @@ -619,14 +620,15 @@ public String getLibraryVersion() { } protected int baseHashCode() { - return Objects.hash(projectId, host, authCredentialsState, retryParams, serviceFactoryClassName, - serviceRpcFactoryClassName, clock); + return Objects.hash(projectId, host, noCredentials, credentials, retryParams, + serviceFactoryClassName, serviceRpcFactoryClassName, clock); } protected boolean baseEquals(ServiceOptions other) { - return Objects.equals(projectId, other.projectId) + return noCredentials == other.noCredentials + && Objects.equals(projectId, other.projectId) && Objects.equals(host, other.host) - && Objects.equals(authCredentialsState, other.authCredentialsState) + && Objects.equals(credentials, other.credentials) && Objects.equals(retryParams, other.retryParams) && Objects.equals(serviceFactoryClassName, other.serviceFactoryClassName) && Objects.equals(serviceRpcFactoryClassName, other.serviceRpcFactoryClassName) @@ -637,7 +639,6 @@ private void readObject(ObjectInputStream input) throws IOException, ClassNotFou input.defaultReadObject(); serviceFactory = newInstance(serviceFactoryClassName); serviceRpcFactory = newInstance(serviceRpcFactoryClassName); - authCredentials = authCredentialsState != null ? authCredentialsState.restore() : null; } @SuppressWarnings("unchecked") diff --git a/google-cloud-core/src/test/java/com/google/cloud/AuthCredentialsTest.java b/google-cloud-core/src/test/java/com/google/cloud/AuthCredentialsTest.java deleted file mode 100644 index 3ae34e6ca934..000000000000 --- a/google-cloud-core/src/test/java/com/google/cloud/AuthCredentialsTest.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * 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. - */ - -package com.google.cloud; - -import static com.google.common.base.Charsets.UTF_8; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; - -import com.google.auth.oauth2.AccessToken; -import com.google.auth.oauth2.ServiceAccountCredentials; -import com.google.cloud.AuthCredentials.OAuth2AuthCredentials; -import com.google.cloud.AuthCredentials.ServiceAccountAuthCredentials; -import com.google.common.io.BaseEncoding; - -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.InvalidKeyException; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.Signature; -import java.security.SignatureException; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.util.Date; - -public class AuthCredentialsTest { - - private static final String ACCESS_TOKEN = "accessToken"; - private static final Date EXPIRATION_DATE = new Date(); - private static final String SERVICE_ACCOUNT = "someclientid@developer.gserviceaccount.com"; - private static final String PRIVATE_KEY_STRING = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoG" - + "BAL2xolH1zrISQ8+GzOV29BNjjzq4/HIP8Psd1+cZb81vDklSF+95wB250MSE0BDc81pvIMwj5OmIfLg1NY6uB1xav" - + "OPpVdx1z664AGc/BEJ1zInXGXaQ6s+SxGenVq40Yws57gikQGMZjttpf1Qbz4DjkxsbRoeaRHn06n9pH1ejAgMBAAE" - + "CgYEAkWcm0AJF5LMhbWKbjkxm/LG06UNApkHX6vTOOOODkonM/qDBnhvKCj8Tan+PaU2j7679Cd19qxCm4SBQJET7e" - + "BhqLD9L2j9y0h2YUQnLbISaqUS1/EXcr2C1Lf9VCEn1y/GYuDYqs85rGoQ4ZYfM9ClROSq86fH+cbIIssqJqukCQQD" - + "18LjfJz/ichFeli5/l1jaFid2XoCH3T6TVuuysszVx68fh60gSIxEF/0X2xB+wuPxTP4IQ+t8tD/ktd232oWXAkEAx" - + "XPych2QBHePk9/lek4tOkKBgfnDzex7S/pI0G1vpB3VmzBbCsokn9lpOv7JV8071GDlW/7R6jlLfpQy3hN31QJAE10" - + "osSk99m5Uv8XDU3hvHnywDrnSFOBulNs7I47AYfSe7TSZhPkxUgsxejddTR27JLyTI8N1PxRSE4feNSOXcQJAMMKJR" - + "JT4U6IS2rmXubREhvaVdLtxFxEnAYQ1JwNfZm/XqBMw6GEy2iaeTetNXVlZRQEIoscyn1y2v/No/F5iYQJBAKBOGAS" - + "oQcBjGTOg/H/SfcE8QVNsKEpthRrs6CkpT80aZ/AV+ksfoIf2zw2M3mAHfrO+TBLdz4sicuFQvlN9SEc="; - private static final String JSON_KEY = "{\n" - + " \"private_key_id\": \"somekeyid\",\n" - + " \"private_key\": \"-----BEGIN PRIVATE KEY-----\\n" + PRIVATE_KEY_STRING - + "\\n-----END PRIVATE KEY-----\\n\",\n" - + " \"client_email\": \"someclientid@developer.gserviceaccount.com\",\n" - + " \"client_id\": \"someclientid.apps.googleusercontent.com\",\n" - + " \"type\": \"service_account\"\n" - + "}"; - private static final AuthCredentials NO_AUTH_CREDENTIALS = AuthCredentials.noAuth(); - private static final OAuth2AuthCredentials OAUTH2_AUTH_CREDENTIALS = - AuthCredentials.createFor(ACCESS_TOKEN, EXPIRATION_DATE); - private static final byte[] BYTES_TO_SIGN = PRIVATE_KEY_STRING.getBytes(UTF_8); - - private static PrivateKey privateKey; - private static byte[] signedBytes; - - @BeforeClass - public static void beforeClass() throws NoSuchAlgorithmException, InvalidKeySpecException, - InvalidKeyException, SignatureException { - KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - privateKey = keyFactory.generatePrivate( - new PKCS8EncodedKeySpec(BaseEncoding.base64().decode(PRIVATE_KEY_STRING))); - Signature signature = Signature.getInstance("SHA256withRSA"); - signature.initSign(privateKey); - signature.update(BYTES_TO_SIGN); - signedBytes = signature.sign(); - } - - @Test - public void testNoAuthCredentials() { - assertSame(NO_AUTH_CREDENTIALS, AuthCredentials.noAuth()); - assertNull(NO_AUTH_CREDENTIALS.getCredentials()); - } - - @Test - public void testNoAuthCredentialsDeprecated() { - assertSame(NO_AUTH_CREDENTIALS, AuthCredentials.noAuth()); - assertNull(NO_AUTH_CREDENTIALS.credentials()); - } - - @Test - public void testOAuth2AuthCredentials() { - AccessToken accessToken = OAUTH2_AUTH_CREDENTIALS.getCredentials().getAccessToken(); - assertEquals(ACCESS_TOKEN, accessToken.getTokenValue()); - assertEquals(EXPIRATION_DATE, accessToken.getExpirationTime()); - OAuth2AuthCredentials oAuth2AuthCredentials = - AuthCredentials.createFor(ACCESS_TOKEN); - accessToken = oAuth2AuthCredentials.getCredentials().getAccessToken(); - assertEquals(ACCESS_TOKEN, accessToken.getTokenValue()); - assertNull(accessToken.getExpirationTime()); - } - - @Test - public void testOAuth2AuthCredentialsDeprecated() { - AccessToken accessToken = OAUTH2_AUTH_CREDENTIALS.credentials().getAccessToken(); - assertEquals(ACCESS_TOKEN, accessToken.getTokenValue()); - assertEquals(EXPIRATION_DATE, accessToken.getExpirationTime()); - OAuth2AuthCredentials oAuth2AuthCredentials = - AuthCredentials.createFor(ACCESS_TOKEN); - accessToken = oAuth2AuthCredentials.credentials().getAccessToken(); - assertEquals(ACCESS_TOKEN, accessToken.getTokenValue()); - assertNull(accessToken.getExpirationTime()); - } - - @Test - public void testServiceAccountFromJson() throws IOException, SignatureException { - ServiceAccountAuthCredentials serviceAccountAuthCredentials = - AuthCredentials.createForJson(new ByteArrayInputStream(JSON_KEY.getBytes())); - ServiceAccountCredentials credentials = serviceAccountAuthCredentials.getCredentials(); - assertEquals(SERVICE_ACCOUNT, serviceAccountAuthCredentials.getAccount()); - assertEquals(SERVICE_ACCOUNT, credentials.getClientEmail()); - assertEquals(privateKey, credentials.getPrivateKey()); - assertArrayEquals(signedBytes, serviceAccountAuthCredentials.sign(BYTES_TO_SIGN)); - } - - @Test - public void testServiceAccountFromJsonDeprecated() throws IOException, SignatureException { - ServiceAccountAuthCredentials serviceAccountAuthCredentials = - AuthCredentials.createForJson(new ByteArrayInputStream(JSON_KEY.getBytes())); - ServiceAccountCredentials credentials = serviceAccountAuthCredentials.credentials(); - assertEquals(SERVICE_ACCOUNT, serviceAccountAuthCredentials.account()); - assertEquals(SERVICE_ACCOUNT, credentials.getClientEmail()); - assertEquals(privateKey, credentials.getPrivateKey()); - assertArrayEquals(signedBytes, serviceAccountAuthCredentials.sign(BYTES_TO_SIGN)); - } - - @Test - public void testServiceAccountFromKey() throws IOException, SignatureException { - ServiceAccountAuthCredentials serviceAccountAuthCredentials = - AuthCredentials.createFor(SERVICE_ACCOUNT, privateKey); - ServiceAccountCredentials credentials = serviceAccountAuthCredentials.getCredentials(); - assertEquals(SERVICE_ACCOUNT, serviceAccountAuthCredentials.getAccount()); - assertEquals(SERVICE_ACCOUNT, credentials.getClientEmail()); - assertEquals(privateKey, credentials.getPrivateKey()); - assertArrayEquals(signedBytes, serviceAccountAuthCredentials.sign(BYTES_TO_SIGN)); - } - - @Test - public void testServiceAccountFromKeyDeprecated() throws IOException, SignatureException { - ServiceAccountAuthCredentials serviceAccountAuthCredentials = - AuthCredentials.createFor(SERVICE_ACCOUNT, privateKey); - ServiceAccountCredentials credentials = serviceAccountAuthCredentials.credentials(); - assertEquals(SERVICE_ACCOUNT, serviceAccountAuthCredentials.account()); - assertEquals(SERVICE_ACCOUNT, credentials.getClientEmail()); - assertEquals(privateKey, credentials.getPrivateKey()); - assertArrayEquals(signedBytes, serviceAccountAuthCredentials.sign(BYTES_TO_SIGN)); - } -} diff --git a/google-cloud-core/src/test/java/com/google/cloud/HttpServiceOptionsTest.java b/google-cloud-core/src/test/java/com/google/cloud/HttpServiceOptionsTest.java index a372498c2173..9ac2891c6cbf 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/HttpServiceOptionsTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/HttpServiceOptionsTest.java @@ -21,8 +21,8 @@ import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; +import com.google.auth.http.HttpTransportFactory; import com.google.cloud.HttpServiceOptions.DefaultHttpTransportFactory; -import com.google.cloud.HttpServiceOptions.HttpTransportFactory; import com.google.cloud.spi.ServiceRpcFactory; import org.easymock.EasyMock; diff --git a/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java b/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java index 746f2b406b13..d2e2de4f4afd 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java @@ -18,14 +18,10 @@ import com.google.cloud.MonitoredResourceDescriptor.LabelDescriptor; import com.google.cloud.MonitoredResourceDescriptor.LabelDescriptor.ValueType; -import com.google.cloud.ServiceAccountSigner.SigningException; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import java.io.ByteArrayInputStream; -import java.io.IOException; import java.io.Serializable; -import java.util.Date; import java.util.concurrent.TimeUnit; public class SerializationTest extends BaseSerializationTest { @@ -36,8 +32,6 @@ public class SerializationTest extends BaseSerializationTest { private static final Identity IDENTITY = Identity.allAuthenticatedUsers(); private static final PageImpl PAGE = new PageImpl<>(null, "cursor", ImmutableList.of("string1", "string2")); - private static final SigningException SIGNING_EXCEPTION = - new SigningException("message", BASE_SERVICE_EXCEPTION); private static final RetryParams RETRY_PARAMS = RetryParams.getDefaultInstance(); private static final Role SOME_ROLE = Role.viewer(); private static final Policy SOME_IAM_POLICY = Policy.newBuilder().build(); @@ -82,19 +76,12 @@ public class SerializationTest extends BaseSerializationTest { @Override protected Serializable[] serializableObjects() { return new Serializable[]{BASE_SERVICE_EXCEPTION, EXCEPTION_HANDLER, IDENTITY, PAGE, - RETRY_PARAMS, SOME_ROLE, SOME_IAM_POLICY, SIGNING_EXCEPTION, CHECKING_PERIOD, - LABEL_DESCRIPTOR, MONITORED_RESOURCE_DESCRIPTOR, MONITORED_RESOURCE}; + RETRY_PARAMS, SOME_ROLE, SOME_IAM_POLICY, CHECKING_PERIOD, LABEL_DESCRIPTOR, + MONITORED_RESOURCE_DESCRIPTOR, MONITORED_RESOURCE}; } @Override protected Restorable[] restorableObjects() { - try { - return new Restorable[]{AuthCredentials.createForAppEngine(), AuthCredentials.noAuth(), - AuthCredentials.createForJson(new ByteArrayInputStream(JSON_KEY.getBytes())), - AuthCredentials.createFor("accessToken", new Date())}; - } catch (IOException ex) { - // never reached - throw new RuntimeException(ex); - } + return null; } } diff --git a/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java b/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java index e7e74459d18c..f21c37ad55d8 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java @@ -18,10 +18,12 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.spi.ServiceRpcFactory; import org.junit.Test; @@ -61,10 +63,10 @@ public class ServiceOptionsTest { + " \"type\": \"service_account\"\n" + "}"; private static final InputStream JSON_KEY_STREAM = new ByteArrayInputStream(JSON_KEY.getBytes()); - private static AuthCredentials authCredentials; + private static GoogleCredentials credentials; static { try { - authCredentials = AuthCredentials.createForJson(JSON_KEY_STREAM); + credentials = GoogleCredentials.fromStream(JSON_KEY_STREAM); } catch (IOException e) { fail("Couldn't create fake JSON credentials."); } @@ -72,7 +74,15 @@ public class ServiceOptionsTest { private static final Clock TEST_CLOCK = new TestClock(); private static final TestServiceOptions OPTIONS = TestServiceOptions.newBuilder() - .setAuthCredentials(authCredentials) + .setCredentials(credentials) + .setClock(TEST_CLOCK) + .setHost("host") + .setProjectId("project-id") + .setRetryParams(RetryParams.noRetries()) + .build(); + private static final TestServiceOptions OPTIONS_NO_CREDENTIALS = + TestServiceOptions.newBuilder() + .setNoCredentials() .setClock(TEST_CLOCK) .setHost("host") .setProjectId("project-id") @@ -80,7 +90,7 @@ public class ServiceOptionsTest { .build(); private static final TestServiceOptions DEPRECATED_OPTIONS = TestServiceOptions.newBuilder() - .authCredentials(authCredentials) + .setCredentials(credentials) .clock(TEST_CLOCK) .host("host") .projectId("project-id") @@ -197,7 +207,7 @@ public int hashCode() { @Test public void testBuilder() { - assertSame(authCredentials, OPTIONS.getAuthCredentials()); + assertSame(credentials, OPTIONS.getCredentials()); assertSame(TEST_CLOCK, OPTIONS.getClock()); assertEquals("host", OPTIONS.getHost()); assertEquals("project-id", OPTIONS.getProjectId()); @@ -207,9 +217,18 @@ public void testBuilder() { assertSame(RetryParams.getDefaultInstance(), DEFAULT_OPTIONS.getRetryParams()); } + @Test + public void testBuilderNoCredentials() { + assertNull(OPTIONS_NO_CREDENTIALS.getCredentials()); + assertSame(TEST_CLOCK, OPTIONS_NO_CREDENTIALS.getClock()); + assertEquals("host", OPTIONS_NO_CREDENTIALS.getHost()); + assertEquals("project-id", OPTIONS_NO_CREDENTIALS.getProjectId()); + assertSame(RetryParams.noRetries(), OPTIONS_NO_CREDENTIALS.getRetryParams()); + } + @Test public void testBuilderDeprecated() { - assertSame(authCredentials, DEPRECATED_OPTIONS.authCredentials()); + assertSame(credentials, DEPRECATED_OPTIONS.getCredentials()); assertSame(TEST_CLOCK, DEPRECATED_OPTIONS.clock()); assertEquals("host", DEPRECATED_OPTIONS.host()); assertEquals("project-id", DEPRECATED_OPTIONS.projectId()); diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreOptions.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreOptions.java index 69132adcaf36..db65213f268b 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreOptions.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreOptions.java @@ -35,7 +35,7 @@ public class DatastoreOptions extends HttpServiceOptions { - private static final long serialVersionUID = -7859275434360052450L; + private static final long serialVersionUID = -1018382430058137336L; private static final String DATASTORE_SCOPE = "https://www.googleapis.com/auth/datastore"; private static final Set SCOPES = ImmutableSet.of(DATASTORE_SCOPE); diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java index 461fc0b9a975..c484153a27e1 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java @@ -19,7 +19,6 @@ import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; -import com.google.cloud.AuthCredentials; import com.google.cloud.RetryParams; import com.google.cloud.datastore.DatastoreOptions; import com.google.common.base.Strings; @@ -640,7 +639,7 @@ private DatastoreOptions.Builder optionsBuilder() { return DatastoreOptions.newBuilder() .setProjectId(projectId) .setHost("localhost:" + Integer.toString(port)) - .setAuthCredentials(AuthCredentials.noAuth()) + .setNoCredentials() .setRetryParams(RetryParams.noRetries()); } diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreOptionsTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreOptionsTest.java index 109a28c2078b..2bda0f3dc8dd 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreOptionsTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreOptionsTest.java @@ -78,6 +78,6 @@ public void testToBuilder() throws Exception { assertEquals(original.getNamespace(), copy.getNamespace()); assertEquals(original.getHost(), copy.getHost()); assertEquals(original.getRetryParams(), copy.getRetryParams()); - assertEquals(original.getAuthCredentials(), copy.getAuthCredentials()); + assertEquals(original.getCredentials(), copy.getCredentials()); } } diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java index b591ebac09f5..40be3a3321ac 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java @@ -18,7 +18,6 @@ import static java.nio.charset.StandardCharsets.UTF_8; -import com.google.cloud.AuthCredentials; import com.google.cloud.BaseSerializationTest; import com.google.cloud.Restorable; import com.google.cloud.datastore.StructuredQuery.CompositeFilter; @@ -111,12 +110,12 @@ public class SerializationTest extends BaseSerializationTest { @Override protected java.io.Serializable[] serializableObjects() { DatastoreOptions options = DatastoreOptions.newBuilder() - .setAuthCredentials(AuthCredentials.createForAppEngine()) + .setNoCredentials() .setProjectId("ds1") .build(); DatastoreOptions otherOptions = options.toBuilder() .setNamespace("ns1") - .setAuthCredentials(null) + .setCredentials(null) .build(); return new java.io.Serializable[]{KEY1, KEY2, INCOMPLETE_KEY1, INCOMPLETE_KEY2, ENTITY1, ENTITY2, ENTITY3, EMBEDDED_ENTITY, PROJECTION_ENTITY, DATE_TIME1, BLOB1, CURSOR1, GQL1, diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java index ee649c878ca0..98da680a129e 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java @@ -22,7 +22,6 @@ import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import com.google.cloud.AuthCredentials; import com.google.cloud.datastore.Datastore; import com.google.cloud.datastore.DatastoreException; import com.google.cloud.datastore.DatastoreOptions; @@ -73,11 +72,11 @@ public void testOptions() { DatastoreOptions options = helper.getOptions(); assertTrue(options.getProjectId().startsWith(PROJECT_ID_PREFIX)); assertTrue(options.getHost().startsWith("localhost:")); - assertSame(AuthCredentials.noAuth(), options.getAuthCredentials()); + assertNull(options.getCredentials()); options = helper.getOptions(NAMESPACE); assertTrue(options.getProjectId().startsWith(PROJECT_ID_PREFIX)); assertTrue(options.getHost().startsWith("localhost:")); - assertSame(AuthCredentials.noAuth(), options.getAuthCredentials()); + assertNull(options.getCredentials()); assertEquals(NAMESPACE, options.getNamespace()); } diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsOptions.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsOptions.java index d76d8e22525a..50d735209a54 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsOptions.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsOptions.java @@ -26,7 +26,7 @@ public class DnsOptions extends HttpServiceOptions { - private static final long serialVersionUID = -8639966476950724880L; + private static final long serialVersionUID = -2501790264435912627L; private static final String GC_DNS_RW = "https://www.googleapis.com/auth/ndev.clouddns.readwrite"; private static final Set SCOPES = ImmutableSet.of(GC_DNS_RW); diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/LocalDnsHelper.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/LocalDnsHelper.java index b9abf3aeb43b..cb6b1ffecb25 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/LocalDnsHelper.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/LocalDnsHelper.java @@ -28,7 +28,6 @@ import com.google.api.services.dns.model.Project; import com.google.api.services.dns.model.Quota; import com.google.api.services.dns.model.ResourceRecordSet; -import com.google.cloud.AuthCredentials; import com.google.cloud.dns.DnsOptions; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; @@ -507,7 +506,7 @@ public DnsOptions getOptions() { return DnsOptions.newBuilder() .setProjectId(PROJECT_ID) .setHost("http://localhost:" + port) - .setAuthCredentials(AuthCredentials.noAuth()) + .setNoCredentials() .build(); } diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java index 3434a5cf8280..344d7dabb808 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java @@ -16,7 +16,6 @@ package com.google.cloud.dns; -import com.google.cloud.AuthCredentials; import com.google.cloud.BaseSerializationTest; import com.google.cloud.Restorable; import com.google.cloud.RetryParams; @@ -89,11 +88,11 @@ public class SerializationTest extends BaseSerializationTest { @Override protected Serializable[] serializableObjects() { DnsOptions options = DnsOptions.newBuilder() - .setAuthCredentials(AuthCredentials.createForAppEngine()) + .setNoCredentials() .setProjectId("id1") .build(); DnsOptions otherOptions = options.toBuilder() - .setAuthCredentials(null) + .setCredentials(null) .build(); return new Serializable[]{FULL_ZONE_INFO, PARTIAL_ZONE_INFO, ZONE_LIST_OPTION, RECORD_SET_LIST_OPTION, CHANGE_REQUEST_LIST_OPTION, ZONE_OPTION, CHANGE_REQUEST_OPTION, diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/StorageExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/StorageExample.java index 69ccbf51d880..2da42bdeac07 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/StorageExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/StorageExample.java @@ -16,8 +16,7 @@ package com.google.cloud.examples.storage; -import com.google.cloud.AuthCredentials; -import com.google.cloud.AuthCredentials.ServiceAccountAuthCredentials; +import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.ReadChannel; import com.google.cloud.WriteChannel; import com.google.cloud.storage.Acl; @@ -531,24 +530,24 @@ public String params() { * @see Signed URLs */ private static class SignUrlAction extends - StorageAction> { + StorageAction> { private static final char[] PASSWORD = "notasecret".toCharArray(); @Override - public void run(Storage storage, Tuple tuple) + public void run(Storage storage, Tuple tuple) throws Exception { run(storage, tuple.x(), tuple.y()); } - private void run(Storage storage, ServiceAccountAuthCredentials cred, BlobInfo blobInfo) { + private void run(Storage storage, ServiceAccountCredentials cred, BlobInfo blobInfo) { Blob blob = storage.get(blobInfo.getBlobId()); System.out.printf("Signed URL: %s%n", blob.signUrl(1, TimeUnit.DAYS, SignUrlOption.signWith(cred))); } @Override - Tuple parse(String... args) throws IOException, + Tuple parse(String... args) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException { if (args.length != 4) { @@ -557,8 +556,9 @@ Tuple parse(String... args) throws IOEx KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(Files.newInputStream(Paths.get(args[0])), PASSWORD); PrivateKey privateKey = (PrivateKey) keystore.getKey("privatekey", PASSWORD); - ServiceAccountAuthCredentials cred = AuthCredentials.createFor(args[1], privateKey); - return Tuple.of(cred, BlobInfo.newBuilder(BlobId.of(args[2], args[3])).build()); + ServiceAccountCredentials credentials = + new ServiceAccountCredentials(null, args[1], privateKey, null, null); + return Tuple.of(credentials, BlobInfo.newBuilder(BlobId.of(args[2], args[3])).build()); } @Override diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/BlobSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/BlobSnippets.java index 18c2519e38a2..b761e3c35de9 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/BlobSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/BlobSnippets.java @@ -24,9 +24,9 @@ import static java.nio.charset.StandardCharsets.UTF_8; -import com.google.cloud.AuthCredentials; +import com.google.auth.ServiceAccountSigner; +import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.ReadChannel; -import com.google.cloud.ServiceAccountSigner; import com.google.cloud.WriteChannel; import com.google.cloud.storage.Acl; import com.google.cloud.storage.Acl.User; @@ -227,7 +227,7 @@ public URL signUrl() { public URL signUrlWithSigner(String keyPath) throws IOException { // [START signUrlWithSigner] URL signedUrl = blob.signUrl(14, TimeUnit.DAYS, SignUrlOption.signWith( - AuthCredentials.createForJson(new FileInputStream(keyPath)))); + ServiceAccountCredentials.fromStream(new FileInputStream(keyPath)))); // [END signUrlWithSigner] return signedUrl; } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/StorageSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/StorageSnippets.java index fb6d8567a004..5424d1b650b9 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/StorageSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/StorageSnippets.java @@ -24,11 +24,11 @@ import static java.nio.charset.StandardCharsets.UTF_8; -import com.google.cloud.AuthCredentials; +import com.google.auth.ServiceAccountSigner; +import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.BatchResult; import com.google.cloud.Page; import com.google.cloud.ReadChannel; -import com.google.cloud.ServiceAccountSigner; import com.google.cloud.WriteChannel; import com.google.cloud.storage.Acl; import com.google.cloud.storage.Acl.Role; @@ -580,7 +580,7 @@ public URL signUrlWithSigner(String bucketName, String blobName, String keyPath) // [START signUrlWithSigner] URL signedUrl = storage.signUrl(BlobInfo.newBuilder(bucketName, blobName).build(), 14, TimeUnit.DAYS, SignUrlOption.signWith( - AuthCredentials.createForJson(new FileInputStream(keyPath)))); + ServiceAccountCredentials.fromStream(new FileInputStream(keyPath)))); // [END signUrlWithSigner] return signedUrl; } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingOptions.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingOptions.java index 230482e73c27..3bf7b8b3f9dc 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingOptions.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingOptions.java @@ -29,7 +29,7 @@ public class LoggingOptions extends GrpcServiceOptions { - private static final long serialVersionUID = -2996451684945061075L; + private static final long serialVersionUID = -5117984564582881668L; private static final String LOGGING_SCOPE = "https://www.googleapis.com/auth/logging.admin"; private static final Set SCOPES = ImmutableSet.of(LOGGING_SCOPE); private static final String DEFAULT_HOST = LoggingServiceV2Settings.getDefaultServiceAddress() diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/DefaultLoggingRpc.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/DefaultLoggingRpc.java index e47aeb56766a..60ded3d308be 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/DefaultLoggingRpc.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/DefaultLoggingRpc.java @@ -19,9 +19,8 @@ import static com.google.common.base.MoreObjects.firstNonNull; import com.google.api.gax.core.ConnectionSettings; -import com.google.api.gax.grpc.UnaryCallSettings; import com.google.api.gax.grpc.ApiException; -import com.google.cloud.AuthCredentials; +import com.google.api.gax.grpc.UnaryCallSettings; import com.google.cloud.GrpcServiceOptions.ExecutorFactory; import com.google.cloud.logging.LoggingException; import com.google.cloud.logging.LoggingOptions; @@ -119,8 +118,7 @@ public DefaultLoggingRpc(LoggingOptions options) throws IOException { .provideExecutorWith(executor, false) .setClientLibHeader(libraryName, libraryVersion); // todo(mziccard): PublisherSettings should support null/absent credentials for testing - if (options.getHost().contains("localhost") - || options.getAuthCredentials().equals(AuthCredentials.noAuth())) { + if (options.getHost().contains("localhost") || options.getCredentials() == null) { ManagedChannel channel = NettyChannelBuilder.forTarget(options.getHost()) .negotiationType(NegotiationType.PLAINTEXT) .build(); diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/RemoteLoggingHelper.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/RemoteLoggingHelper.java index d1935618a5c3..79ff035e4f38 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/RemoteLoggingHelper.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/RemoteLoggingHelper.java @@ -16,7 +16,7 @@ package com.google.cloud.logging.testing; -import com.google.cloud.AuthCredentials; +import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.RetryParams; import com.google.cloud.logging.LoggingOptions; @@ -74,7 +74,7 @@ public static RemoteLoggingHelper create(String projectId, InputStream keyStream throws LoggingHelperException { try { LoggingOptions storageOptions = LoggingOptions.newBuilder() - .setAuthCredentials(AuthCredentials.createForJson(keyStream)) + .setCredentials(ServiceAccountCredentials.fromStream(keyStream)) .setProjectId(projectId) .setRetryParams(retryParams()) .setInitialTimeout(60000) diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java index bdb7d0e908b0..14db61d80db9 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java @@ -16,7 +16,6 @@ package com.google.cloud.logging; -import com.google.cloud.AuthCredentials; import com.google.cloud.BaseSerializationTest; import com.google.cloud.MonitoredResource; import com.google.cloud.Restorable; @@ -41,7 +40,7 @@ public class SerializationTest extends BaseSerializationTest { private static final Logging LOGGING = LoggingOptions.newBuilder() .setProjectId("p") - .setAuthCredentials(AuthCredentials.noAuth()) + .setNoCredentials() .setHost("localhost") .build().getService(); private static final HttpRequest HTTP_REQUEST = HttpRequest.newBuilder() diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubOptions.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubOptions.java index 760bd6b6b8b0..ac8262d1af97 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubOptions.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubOptions.java @@ -29,7 +29,7 @@ public class PubSubOptions extends GrpcServiceOptions { - private static final long serialVersionUID = 5640180400046623305L; + private static final long serialVersionUID = 5598666986447361352L; private static final String PUBSUB_SCOPE = "https://www.googleapis.com/auth/pubsub"; private static final Set SCOPES = ImmutableSet.of(PUBSUB_SCOPE); private static final String EMULATOR_HOST_ENV_VAR = "PUBSUB_EMULATOR_HOST"; diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/DefaultPubSubRpc.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/DefaultPubSubRpc.java index 255171d1c47f..3cf1165c146a 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/DefaultPubSubRpc.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/DefaultPubSubRpc.java @@ -19,9 +19,8 @@ import static com.google.common.base.MoreObjects.firstNonNull; import com.google.api.gax.core.ConnectionSettings; -import com.google.api.gax.grpc.UnaryCallSettings; import com.google.api.gax.grpc.ApiException; -import com.google.cloud.AuthCredentials; +import com.google.api.gax.grpc.UnaryCallSettings; import com.google.cloud.GrpcServiceOptions.ExecutorFactory; import com.google.cloud.pubsub.PubSubException; import com.google.cloud.pubsub.PubSubOptions; @@ -142,8 +141,7 @@ public DefaultPubSubRpc(PubSubOptions options) throws IOException { .provideExecutorWith(executor, false) .setClientLibHeader(libraryName, libraryVersion); // todo(mziccard): PublisherSettings should support null/absent credentials for testing - if (options.getHost().contains("localhost") - || options.getAuthCredentials().equals(AuthCredentials.noAuth())) { + if (options.getHost().contains("localhost") || options.getCredentials() == null) { ManagedChannel channel = NettyChannelBuilder.forTarget(options.getHost()) .negotiationType(NegotiationType.PLAINTEXT) .build(); diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/LocalPubsubHelper.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/LocalPubsubHelper.java index 5715879291c2..db01f60fa882 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/LocalPubsubHelper.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/LocalPubsubHelper.java @@ -19,7 +19,6 @@ import com.google.api.gax.testing.DownloadableEmulatorRunner; import com.google.api.gax.testing.GCloudEmulatorRunner; import com.google.api.gax.testing.LocalServiceHelper; -import com.google.cloud.AuthCredentials; import com.google.cloud.RetryParams; import com.google.cloud.pubsub.PubSubOptions; @@ -158,7 +157,7 @@ public PubSubOptions getOptions() { return PubSubOptions.newBuilder() .setProjectId(projectId) .setHost("localhost:" + port) - .setAuthCredentials(AuthCredentials.noAuth()) + .setNoCredentials() .setRetryParams(RetryParams.noRetries()) .build(); } diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SerializationTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SerializationTest.java index 74f38fcebc9b..ca4e8bf3b62e 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SerializationTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SerializationTest.java @@ -16,7 +16,6 @@ package com.google.cloud.pubsub; -import com.google.cloud.AuthCredentials; import com.google.cloud.BaseSerializationTest; import com.google.cloud.GrpcServiceOptions.ExecutorFactory; import com.google.cloud.Restorable; @@ -30,7 +29,7 @@ public class SerializationTest extends BaseSerializationTest { private static final PubSub PUB_SUB = PubSubOptions.newBuilder() .setProjectId("p") - .setAuthCredentials(AuthCredentials.noAuth()) + .setNoCredentials() .setHost("localhost") .build().getService(); private static final Message MESSAGE = Message.of("payload"); diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerOptions.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerOptions.java index 649dc5306f20..7b893fe4d98e 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerOptions.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerOptions.java @@ -27,7 +27,7 @@ public class ResourceManagerOptions extends HttpServiceOptions { - private static final long serialVersionUID = -109855112863688882L; + private static final long serialVersionUID = 624147474447836183L; private static final String GCRM_SCOPE = "https://www.googleapis.com/auth/cloud-platform"; private static final Set SCOPES = ImmutableSet.of(GCRM_SCOPE); private static final String DEFAULT_HOST = "https://cloudresourcemanager.googleapis.com"; diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelper.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelper.java index d5200f954b6b..e20c44f8f7f7 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelper.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelper.java @@ -27,7 +27,6 @@ import com.google.api.services.cloudresourcemanager.model.SetIamPolicyRequest; import com.google.api.services.cloudresourcemanager.model.TestIamPermissionsRequest; import com.google.api.services.cloudresourcemanager.model.TestIamPermissionsResponse; -import com.google.cloud.AuthCredentials; import com.google.cloud.resourcemanager.ResourceManagerOptions; import com.google.common.base.Joiner; import com.google.common.base.Objects; @@ -686,7 +685,7 @@ public ResourceManagerOptions options() { public ResourceManagerOptions getOptions() { return ResourceManagerOptions.newBuilder() .setHost("http://localhost:" + port) - .setAuthCredentials(AuthCredentials.noAuth()) + .setNoCredentials() .build(); } diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/Blob.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/Blob.java index 6eac48c23093..2f6667a5a062 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/Blob.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/Blob.java @@ -21,12 +21,9 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.api.services.storage.model.StorageObject; -import com.google.cloud.AuthCredentials; -import com.google.cloud.AuthCredentials.AppEngineAuthCredentials; -import com.google.cloud.AuthCredentials.ServiceAccountAuthCredentials; +import com.google.auth.ServiceAccountSigner; +import com.google.auth.ServiceAccountSigner.SigningException; import com.google.cloud.ReadChannel; -import com.google.cloud.ServiceAccountSigner; -import com.google.cloud.ServiceAccountSigner.SigningException; import com.google.cloud.WriteChannel; import com.google.cloud.storage.Acl.Entity; import com.google.cloud.storage.Storage.BlobTargetOption; @@ -656,21 +653,21 @@ public WriteChannel writer(BlobWriteOption... options) { * this blob, you can use this method to generate a URL that is only valid within a certain time * period. This is particularly useful if you don't want publicly accessible blobs, but also don't * want to require users to explicitly log in. Signing a URL requires - * a service account signer. If a {@link ServiceAccountAuthCredentials} or an - * {@link AppEngineAuthCredentials} was passed to - * {@link StorageOptions.Builder#setAuthCredentials(AuthCredentials)} or the default credentials - * are being used and the environment variable {@code GOOGLE_APPLICATION_CREDENTIALS} is set, then - * {@code signUrl} will use that credentials to sign the URL. If the credentials passed to - * {@link StorageOptions} do not implement {@link ServiceAccountSigner} (this is the case for - * Compute Engine credentials and Google Cloud SDK credentials) then {@code signUrl} will throw an - * {@link IllegalStateException} unless an implementation of {@link ServiceAccountSigner} is - * passed using the {@link SignUrlOption#signWith(ServiceAccountSigner)} option. + * a service account signer. If an instance of {@link com.google.auth.ServiceAccountSigner} was + * passed to {@link StorageOptions}' builder via {@code setCredentials(Credentials)} or the + * default credentials are being used and the environment variable + * {@code GOOGLE_APPLICATION_CREDENTIALS} is set or your application is running in App Engine, + * then {@code signUrl} will use that credentials to sign the URL. If the credentials passed to + * {@link StorageOptions} do not implement {@link ServiceAccountSigner} (this is the case, for + * instance, for Compute Engine credentials and Google Cloud SDK credentials) then {@code signUrl} + * will throw an {@link IllegalStateException} unless an implementation of + * {@link ServiceAccountSigner} is passed using the + * {@link SignUrlOption#signWith(ServiceAccountSigner)} option. * *

A service account signer is looked for in the following order: *

    *
  1. The signer passed with the option {@link SignUrlOption#signWith(ServiceAccountSigner)} - *
  2. The credentials passed to - * {@link StorageOptions.Builder#setAuthCredentials(AuthCredentials)} + *
  3. The credentials passed to {@link StorageOptions} *
  4. The default credentials, if no credentials were passed to {@link StorageOptions} *
* @@ -685,7 +682,7 @@ public WriteChannel writer(BlobWriteOption... options) { *
 {@code
    * String keyPath = "/path/to/key.json";
    * URL signedUrl = blob.signUrl(14, TimeUnit.DAYS, SignUrlOption.signWith(
-   *     AuthCredentials.createForJson(new FileInputStream(keyPath))));
+   *     ServiceAccountCredentials.fromStream(new FileInputStream(keyPath))));
    * }
* * @param duration time until the signed URL expires, expressed in {@code unit}. The finer diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/Storage.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/Storage.java index d08de6114920..f2e779a18f15 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/Storage.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/Storage.java @@ -19,16 +19,13 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import com.google.cloud.AuthCredentials; -import com.google.cloud.AuthCredentials.AppEngineAuthCredentials; -import com.google.cloud.AuthCredentials.ServiceAccountAuthCredentials; +import com.google.auth.ServiceAccountSigner; +import com.google.auth.ServiceAccountSigner.SigningException; import com.google.cloud.FieldSelector; import com.google.cloud.FieldSelector.Helper; import com.google.cloud.Page; import com.google.cloud.ReadChannel; import com.google.cloud.Service; -import com.google.cloud.ServiceAccountSigner; -import com.google.cloud.ServiceAccountSigner.SigningException; import com.google.cloud.WriteChannel; import com.google.cloud.storage.Acl.Entity; import com.google.cloud.storage.spi.StorageRpc; @@ -2036,21 +2033,21 @@ public static Builder newBuilder() { * fixed amount of time, you can use this method to generate a URL that is only valid within a * certain time period. This is particularly useful if you don't want publicly accessible blobs, * but also don't want to require users to explicitly log in. Signing a URL requires - * a service account signer. If a {@link ServiceAccountAuthCredentials} or an - * {@link AppEngineAuthCredentials} was passed to - * {@link StorageOptions.Builder#setAuthCredentials(AuthCredentials)} or the default credentials - * are being used and the environment variable {@code GOOGLE_APPLICATION_CREDENTIALS} is set, then - * {@code signUrl} will use that credentials to sign the URL. If the credentials passed to - * {@link StorageOptions} do not implement {@link ServiceAccountSigner} (this is the case for - * Compute Engine credentials and Google Cloud SDK credentials) then {@code signUrl} will throw an - * {@link IllegalStateException} unless an implementation of {@link ServiceAccountSigner} is - * passed using the {@link SignUrlOption#signWith(ServiceAccountSigner)} option. + * a service account signer. If an instance of {@link com.google.auth.ServiceAccountSigner} was + * passed to {@link StorageOptions}' builder via {@code setCredentials(Credentials)} or the + * default credentials are being used and the environment variable + * {@code GOOGLE_APPLICATION_CREDENTIALS} is set or your application is running in App Engine, + * then {@code signUrl} will use that credentials to sign the URL. If the credentials passed to + * {@link StorageOptions} do not implement {@link ServiceAccountSigner} (this is the case, for + * instance, for Compute Engine credentials and Google Cloud SDK credentials) then {@code signUrl} + * will throw an {@link IllegalStateException} unless an implementation of + * {@link ServiceAccountSigner} is passed using the + * {@link SignUrlOption#signWith(ServiceAccountSigner)} option. * *

A service account signer is looked for in the following order: *

    *
  1. The signer passed with the option {@link SignUrlOption#signWith(ServiceAccountSigner)} - *
  2. The credentials passed to - * {@link StorageOptions.Builder#setAuthCredentials(AuthCredentials)} + *
  3. The credentials passed to {@link StorageOptions} *
  4. The default credentials, if no credentials were passed to {@link StorageOptions} *
* @@ -2072,7 +2069,7 @@ public static Builder newBuilder() { * String keyPath = "/path/to/key.json"; * URL signedUrl = storage.signUrl(BlobInfo.newBuilder(bucketName, blobName).build(), * 14, TimeUnit.DAYS, SignUrlOption.signWith( - * AuthCredentials.createForJson(new FileInputStream(keyPath)))); + * ServiceAccountCredentials.fromStream(new FileInputStream(keyPath)))); * } * * @param blobInfo the blob associated with the signed URL diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageImpl.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageImpl.java index a96cde57d09d..5e0db04fd274 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageImpl.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageImpl.java @@ -34,6 +34,7 @@ import com.google.api.services.storage.model.BucketAccessControl; import com.google.api.services.storage.model.ObjectAccessControl; import com.google.api.services.storage.model.StorageObject; +import com.google.auth.ServiceAccountSigner; import com.google.cloud.BaseService; import com.google.cloud.BatchResult; import com.google.cloud.Page; @@ -41,7 +42,6 @@ import com.google.cloud.PageImpl.NextPageFetcher; import com.google.cloud.ReadChannel; import com.google.cloud.RetryHelper.RetryHelperException; -import com.google.cloud.ServiceAccountSigner; import com.google.cloud.storage.Acl.Entity; import com.google.cloud.storage.spi.StorageRpc; import com.google.cloud.storage.spi.StorageRpc.RewriteResponse; @@ -501,12 +501,12 @@ public URL signUrl(BlobInfo blobInfo, long duration, TimeUnit unit, SignUrlOptio for (SignUrlOption option : options) { optionMap.put(option.getOption(), option.getValue()); } - ServiceAccountSigner authCredentials = + ServiceAccountSigner credentials = (ServiceAccountSigner) optionMap.get(SignUrlOption.Option.SERVICE_ACCOUNT_CRED); - if (authCredentials == null) { - checkState(this.getOptions().getAuthCredentials() instanceof ServiceAccountSigner, + if (credentials == null) { + checkState(this.getOptions().getCredentials() instanceof ServiceAccountSigner, "Signing key was not provided and could not be derived"); - authCredentials = (ServiceAccountSigner) this.getOptions().getAuthCredentials(); + credentials = (ServiceAccountSigner) this.getOptions().getCredentials(); } // construct signature - see https://cloud.google.com/storage/docs/access-control#Signed-URLs StringBuilder stBuilder = new StringBuilder(); @@ -544,11 +544,11 @@ public URL signUrl(BlobInfo blobInfo, long duration, TimeUnit unit, SignUrlOptio path.append(escapedName.replace("?", "%3F")); stBuilder.append(path); try { - byte[] signatureBytes = authCredentials.sign(stBuilder.toString().getBytes(UTF_8)); + byte[] signatureBytes = credentials.sign(stBuilder.toString().getBytes(UTF_8)); stBuilder = new StringBuilder("https://storage.googleapis.com").append(path); String signature = URLEncoder.encode(BaseEncoding.base64().encode(signatureBytes), UTF_8.name()); - stBuilder.append("?GoogleAccessId=").append(authCredentials.getAccount()); + stBuilder.append("?GoogleAccessId=").append(credentials.getAccount()); stBuilder.append("&Expires=").append(expiration); stBuilder.append("&Signature=").append(signature); return new URL(stBuilder.toString()); diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageOptions.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageOptions.java index 37630e2ace42..d0adf15f7ad7 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageOptions.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageOptions.java @@ -26,7 +26,7 @@ public class StorageOptions extends HttpServiceOptions { - private static final long serialVersionUID = -7456495262640805964L; + private static final long serialVersionUID = -2907268477247502947L; private static final String GCS_SCOPE = "https://www.googleapis.com/auth/devstorage.full_control"; private static final Set SCOPES = ImmutableSet.of(GCS_SCOPE); diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/RemoteStorageHelper.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/RemoteStorageHelper.java index 19df39e2c0a9..d5379178a808 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/RemoteStorageHelper.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/RemoteStorageHelper.java @@ -16,7 +16,7 @@ package com.google.cloud.storage.testing; -import com.google.cloud.AuthCredentials; +import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.RetryParams; import com.google.cloud.storage.BlobInfo; import com.google.cloud.storage.Storage; @@ -133,7 +133,7 @@ public static RemoteStorageHelper create(String projectId, InputStream keyStream throws StorageHelperException { try { StorageOptions storageOptions = StorageOptions.newBuilder() - .setAuthCredentials(AuthCredentials.createForJson(keyStream)) + .setCredentials(GoogleCredentials.fromStream(keyStream)) .setProjectId(projectId) .setRetryParams(retryParams()) .setConnectTimeout(60000) diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java index 3b1e5284aeee..a12c1602d18d 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java @@ -16,7 +16,6 @@ package com.google.cloud.storage; -import com.google.cloud.AuthCredentials; import com.google.cloud.BaseSerializationTest; import com.google.cloud.PageImpl; import com.google.cloud.ReadChannel; @@ -66,11 +65,11 @@ public class SerializationTest extends BaseSerializationTest { protected Serializable[] serializableObjects() { StorageOptions options = StorageOptions.newBuilder() .setProjectId("p1") - .setAuthCredentials(AuthCredentials.createForAppEngine()) + .setNoCredentials() .build(); StorageOptions otherOptions = options.toBuilder() .setProjectId("p2") - .setAuthCredentials(null) + .setCredentials(null) .build(); return new Serializable[]{ACL_DOMAIN, ACL_GROUP, ACL_PROJECT_, ACL_USER, ACL_RAW, ACL, BLOB_INFO, BLOB, BUCKET_INFO, BUCKET, ORIGIN, CORS, PAGE_RESULT, BLOB_LIST_OPTIONS, diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageImplTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageImplTest.java index d44dfe2402e6..bc6fded437f1 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageImplTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageImplTest.java @@ -27,7 +27,7 @@ import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.services.storage.model.StorageObject; -import com.google.cloud.AuthCredentials.ServiceAccountAuthCredentials; +import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.Clock; import com.google.cloud.Page; import com.google.cloud.ReadChannel; @@ -1231,9 +1231,9 @@ public void testWriterWithEncryptionKey() { public void testSignUrl() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException { EasyMock.replay(storageRpcMock); - ServiceAccountAuthCredentials authCredentials = - ServiceAccountAuthCredentials.createFor(ACCOUNT, privateKey); - storage = options.toBuilder().setAuthCredentials(authCredentials).build().getService(); + ServiceAccountCredentials credentials = + new ServiceAccountCredentials(null, ACCOUNT, privateKey, null, null); + storage = options.toBuilder().setCredentials(credentials).build().getService(); URL url = storage.signUrl(BLOB_INFO1, 14, TimeUnit.DAYS); String stringUrl = url.toString(); String expectedUrl = new StringBuilder("https://storage.googleapis.com/").append(BUCKET_NAME1) @@ -1258,9 +1258,9 @@ public void testSignUrlLeadingSlash() throws NoSuchAlgorithmException, InvalidKe SignatureException, UnsupportedEncodingException { String blobName = "/b1"; EasyMock.replay(storageRpcMock); - ServiceAccountAuthCredentials authCredentials = - ServiceAccountAuthCredentials.createFor(ACCOUNT, privateKey); - storage = options.toBuilder().setAuthCredentials(authCredentials).build().getService(); + ServiceAccountCredentials credentials = + new ServiceAccountCredentials(null, ACCOUNT, privateKey, null, null); + storage = options.toBuilder().setCredentials(credentials).build().getService(); URL url = storage.signUrl(BlobInfo.newBuilder(BUCKET_NAME1, blobName).build(), 14, TimeUnit.DAYS); String escapedBlobName = UrlEscapers.urlFragmentEscaper().escape(blobName); @@ -1286,9 +1286,9 @@ public void testSignUrlLeadingSlash() throws NoSuchAlgorithmException, InvalidKe public void testSignUrlWithOptions() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException { EasyMock.replay(storageRpcMock); - ServiceAccountAuthCredentials authCredentials = - ServiceAccountAuthCredentials.createFor(ACCOUNT, privateKey); - storage = options.toBuilder().setAuthCredentials(authCredentials).build().getService(); + ServiceAccountCredentials credentials = + new ServiceAccountCredentials(null, ACCOUNT, privateKey, null, null); + storage = options.toBuilder().setCredentials(credentials).build().getService(); URL url = storage.signUrl(BLOB_INFO1, 14, TimeUnit.DAYS, Storage.SignUrlOption.httpMethod(HttpMethod.POST), Storage.SignUrlOption.withContentType(), Storage.SignUrlOption.withMd5()); @@ -1319,9 +1319,9 @@ public void testSignUrlForBlobWithSpecialChars() throws NoSuchAlgorithmException char[] specialChars = new char[]{'!','#','$','&','\'','(',')','*','+',',',':',';','=','?','@','[',']'}; EasyMock.replay(storageRpcMock); - ServiceAccountAuthCredentials authCredentials = - ServiceAccountAuthCredentials.createFor(ACCOUNT, privateKey); - storage = options.toBuilder().setAuthCredentials(authCredentials).build().getService(); + ServiceAccountCredentials credentials = + new ServiceAccountCredentials(null, ACCOUNT, privateKey, null, null); + storage = options.toBuilder().setCredentials(credentials).build().getService(); for (char specialChar : specialChars) { String blobName = "/a" + specialChar + "b"; @@ -1352,9 +1352,9 @@ public void testSignUrlForBlobWithSpecialChars() throws NoSuchAlgorithmException public void testSignUrlForBlobWithSlashes() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException { EasyMock.replay(storageRpcMock); - ServiceAccountAuthCredentials authCredentials = - ServiceAccountAuthCredentials.createFor(ACCOUNT, privateKey); - storage = options.toBuilder().authCredentials(authCredentials).build().service(); + ServiceAccountCredentials credentials = + new ServiceAccountCredentials(null, ACCOUNT, privateKey, null, null); + storage = options.toBuilder().setCredentials(credentials).build().getService(); String blobName = "/foo/bar/baz #%20other cool stuff.txt"; URL url = diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java index 508dde26d0c6..c06548d2b79f 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java @@ -19,7 +19,7 @@ import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; -import com.google.cloud.AuthCredentials; +import com.google.auth.Credentials; import com.google.cloud.HttpServiceOptions; import com.google.cloud.translate.Translate.TranslateOption; import com.google.cloud.translate.spi.DefaultTranslateRpc; @@ -34,7 +34,7 @@ public class TranslateOptions extends HttpServiceOptions { - private static final long serialVersionUID = 5997441123713672886L; + private static final long serialVersionUID = -572597134540398216L; private static final String API_KEY_ENV_NAME = "GOOGLE_API_KEY"; private static final Set SCOPES = ImmutableSet.of(); @@ -102,19 +102,8 @@ public Builder setProjectId(String projectId) { * * @return the builder */ - @Deprecated - public Builder authCredentials(AuthCredentials authCredentials) { - return setAuthCredentials(authCredentials); - } - - /** - * Sets the service authentication credentials. Setting credentials has no impact on the - * {@link Translate} service. - * - * @return the builder - */ - public Builder setAuthCredentials(AuthCredentials authCredentials) { - super.setAuthCredentials(authCredentials); + public Builder setCredentials(Credentials credentials) { + super.setCredentials(credentials); return self(); } @@ -169,7 +158,7 @@ public Builder setTargetLanguage(String targetLanguage) { @Override public TranslateOptions build() { // Auth credentials are not used by Translate - setAuthCredentials(AuthCredentials.noAuth()); + setNoCredentials(); return new TranslateOptions(this); } } diff --git a/google-cloud-translate/src/test/java/com/google/cloud/translate/SerializationTest.java b/google-cloud-translate/src/test/java/com/google/cloud/translate/SerializationTest.java index b9b7a36d0201..03a4e9af8c2a 100644 --- a/google-cloud-translate/src/test/java/com/google/cloud/translate/SerializationTest.java +++ b/google-cloud-translate/src/test/java/com/google/cloud/translate/SerializationTest.java @@ -18,7 +18,6 @@ import com.google.api.services.translate.model.DetectionsResourceItems; import com.google.api.services.translate.model.TranslationsResource; -import com.google.cloud.AuthCredentials; import com.google.cloud.BaseSerializationTest; import com.google.cloud.Restorable; @@ -48,10 +47,10 @@ public class SerializationTest extends BaseSerializationTest { protected Serializable[] serializableObjects() { TranslateOptions options = TranslateOptions.newBuilder() .setApiKey(API_KEY) - .setAuthCredentials(AuthCredentials.createForAppEngine()) + .setNoCredentials() .build(); TranslateOptions otherOptions = options.toBuilder() - .setAuthCredentials(null) + .setCredentials(null) .build(); return new Serializable[]{DETECTION, TRANSLATION, TRANSLATE_EXCEPTION, LANGUAGE_LIST_OPTION, TRANSLATE_OPTION, options, otherOptions}; diff --git a/pom.xml b/pom.xml index c739587d54d8..5a3b10a828c7 100644 --- a/pom.xml +++ b/pom.xml @@ -90,6 +90,7 @@ UTF-8 UTF-8 github + 0.6.0 1.0.1 google-cloud @@ -420,6 +421,9 @@ com.google.cloud.spi:com.google.cloud.bigquery.spi:com.google.cloud.compute.spi:com.google.cloud.datastore.spi:com.google.cloud.dns.spi:com.google.cloud.errorreporting.spi:com.google.cloud.errorreporting.spi.*:com.google.cloud.language.spi:com.google.cloud.language.spi.*:com.google.cloud.logging.spi:com.google.cloud.monitoring.spi:com.google.cloud.monitoring.spi.*:com.google.cloud.logging.spi.*:com.google.cloud.pubsub.spi:com.google.cloud.pubsub.spi.*:com.google.cloud.resourcemanager.spi:com.google.cloud.speech.spi:com.google.cloud.speech.spi.*:com.google.cloud.storage.spi:com.google.cloud.trace.spi:com.google.cloud.trace.spi.*:com.google.cloud.translate.spi:com.google.cloud.vision.spi:com.google.cloud.vision.spi.* + + http://google.github.io/google-auth-library-java/releases/${google.auth.version}/apidocs/ + @@ -484,6 +488,11 @@ + + + http://google.github.io/google-auth-library-java/releases/${google.auth.version}/apidocs/ + + From faa44765c4a837d5eb4b631dd18cddbf105fc9c3 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Mon, 7 Nov 2016 21:28:30 +0100 Subject: [PATCH 2/4] Throw NPE when setCredentials is called with null --- .../com/google/cloud/bigquery/SerializationTest.java | 5 +---- .../com/google/cloud/compute/SerializationTest.java | 1 - .../main/java/com/google/cloud/ServiceOptions.java | 10 ++++++++-- .../java/com/google/cloud/ServiceOptionsTest.java | 11 +++++++++++ .../com/google/cloud/datastore/SerializationTest.java | 5 +---- .../java/com/google/cloud/dns/SerializationTest.java | 4 +--- .../com/google/cloud/storage/SerializationTest.java | 5 +---- .../com/google/cloud/translate/SerializationTest.java | 4 +--- 8 files changed, 24 insertions(+), 21 deletions(-) diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java index 542b72e1c693..5e7a47781ca3 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java @@ -230,10 +230,7 @@ protected Serializable[] serializableObjects() { .setProjectId("p1") .setNoCredentials() .build(); - BigQueryOptions otherOptions = options.toBuilder() - .setProjectId("p2") - .setCredentials(null) - .build(); + BigQueryOptions otherOptions = options.toBuilder().setProjectId("p2").build(); return new Serializable[]{DOMAIN_ACCESS, GROUP_ACCESS, USER_ACCESS, VIEW_ACCESS, DATASET_ID, DATASET_INFO, TABLE_ID, CSV_OPTIONS, STREAMING_BUFFER, TABLE_DEFINITION, EXTERNAL_TABLE_DEFINITION, VIEW_DEFINITION, TABLE_SCHEMA, TABLE_INFO, VIEW_INFO, diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java index 5d98610d98a9..779bfa37b6ff 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java @@ -269,7 +269,6 @@ protected Serializable[] serializableObjects() { ComputeOptions otherOptions = options.toBuilder() .setProjectId("p2") .setRetryParams(RetryParams.getDefaultInstance()) - .setCredentials(null) .build(); return new Serializable[]{DISK_TYPE_ID, DISK_TYPE, MACHINE_TYPE_ID, MACHINE_TYPE, REGION_ID, REGION, ZONE_ID, ZONE, LICENSE_ID, LICENSE, DEPRECATION_STATUS, GLOBAL_OPERATION_ID, diff --git a/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java b/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java index 33ecac6eee1a..c938c0eb411d 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java +++ b/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java @@ -18,6 +18,7 @@ import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.auth.Credentials; @@ -213,13 +214,18 @@ public B setHost(String host) { } /** - * Sets the service authentication credentials. + * Sets the service authentication credentials. If this method or {@link #setNoCredentials() are + * not used on the builder, {@link GoogleCredentials#getApplicationDefault()} will be used to + * attempt getting credentials from the environment. * + * @param credentials authentication credentials, should not be {@code null} * @return the builder + * @throws NullPointerException if {@code credentials} is {@code null}. To disable + * authentication use {@link Builder#setNoCredentials()} */ public B setCredentials(Credentials credentials) { + this.credentials = checkNotNull(credentials); this.noCredentials = false; - this.credentials = credentials; return self(); } diff --git a/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java b/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java index f21c37ad55d8..1565aa4aecd8 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java @@ -26,7 +26,9 @@ import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.spi.ServiceRpcFactory; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -105,6 +107,9 @@ public class ServiceOptionsTest { private static final Pattern APPLICATION_NAME_PATTERN = Pattern.compile(LIBRARY_NAME + "(/[0-9]+.[0-9]+.[0-9]+)?"); + @Rule + public ExpectedException thrown = ExpectedException.none(); + private static class TestClock extends Clock { @Override public long millis() { @@ -226,6 +231,12 @@ public void testBuilderNoCredentials() { assertSame(RetryParams.noRetries(), OPTIONS_NO_CREDENTIALS.getRetryParams()); } + @Test + public void testBuilderNullCredentials() { + thrown.expect(NullPointerException.class); + TestServiceOptions.newBuilder().setCredentials(null).build(); + } + @Test public void testBuilderDeprecated() { assertSame(credentials, DEPRECATED_OPTIONS.getCredentials()); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java index 40be3a3321ac..b3135c247e9e 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java @@ -113,10 +113,7 @@ protected java.io.Serializable[] serializableObjects() { .setNoCredentials() .setProjectId("ds1") .build(); - DatastoreOptions otherOptions = options.toBuilder() - .setNamespace("ns1") - .setCredentials(null) - .build(); + DatastoreOptions otherOptions = options.toBuilder().setNamespace("ns1").build(); return new java.io.Serializable[]{KEY1, KEY2, INCOMPLETE_KEY1, INCOMPLETE_KEY2, ENTITY1, ENTITY2, ENTITY3, EMBEDDED_ENTITY, PROJECTION_ENTITY, DATE_TIME1, BLOB1, CURSOR1, GQL1, GQL2, QUERY1, QUERY2, QUERY3, NULL_VALUE, KEY_VALUE, STRING_VALUE, EMBEDDED_ENTITY_VALUE1, diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java index 344d7dabb808..37ac272d010c 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java @@ -91,9 +91,7 @@ protected Serializable[] serializableObjects() { .setNoCredentials() .setProjectId("id1") .build(); - DnsOptions otherOptions = options.toBuilder() - .setCredentials(null) - .build(); + DnsOptions otherOptions = options.toBuilder().build(); return new Serializable[]{FULL_ZONE_INFO, PARTIAL_ZONE_INFO, ZONE_LIST_OPTION, RECORD_SET_LIST_OPTION, CHANGE_REQUEST_LIST_OPTION, ZONE_OPTION, CHANGE_REQUEST_OPTION, PROJECT_OPTION, PARTIAL_PROJECT_INFO, FULL_PROJECT_INFO, OPTIONS, FULL_ZONE, PARTIAL_ZONE, diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java index a12c1602d18d..354a49dded60 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java @@ -67,10 +67,7 @@ protected Serializable[] serializableObjects() { .setProjectId("p1") .setNoCredentials() .build(); - StorageOptions otherOptions = options.toBuilder() - .setProjectId("p2") - .setCredentials(null) - .build(); + StorageOptions otherOptions = options.toBuilder().setProjectId("p2").build(); return new Serializable[]{ACL_DOMAIN, ACL_GROUP, ACL_PROJECT_, ACL_USER, ACL_RAW, ACL, BLOB_INFO, BLOB, BUCKET_INFO, BUCKET, ORIGIN, CORS, PAGE_RESULT, BLOB_LIST_OPTIONS, BLOB_SOURCE_OPTIONS, BLOB_TARGET_OPTIONS, BUCKET_LIST_OPTIONS, BUCKET_SOURCE_OPTIONS, diff --git a/google-cloud-translate/src/test/java/com/google/cloud/translate/SerializationTest.java b/google-cloud-translate/src/test/java/com/google/cloud/translate/SerializationTest.java index 03a4e9af8c2a..d6cfdc40e93e 100644 --- a/google-cloud-translate/src/test/java/com/google/cloud/translate/SerializationTest.java +++ b/google-cloud-translate/src/test/java/com/google/cloud/translate/SerializationTest.java @@ -49,9 +49,7 @@ protected Serializable[] serializableObjects() { .setApiKey(API_KEY) .setNoCredentials() .build(); - TranslateOptions otherOptions = options.toBuilder() - .setCredentials(null) - .build(); + TranslateOptions otherOptions = options.toBuilder().build(); return new Serializable[]{DETECTION, TRANSLATION, TRANSLATE_EXCEPTION, LANGUAGE_LIST_OPTION, TRANSLATE_OPTION, options, otherOptions}; } From 96c2b606fd1f8b1d395f9b10c173f698d1acca44 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Mon, 7 Nov 2016 21:30:43 +0100 Subject: [PATCH 3/4] Fix wording in main README's Authentication section --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e83789aa5434..b9101a8cbf4f 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ Authentication `google-cloud-java` uses [https://github.com/google/google-auth-library-java](https://github.com/google/google-auth-library-java) -to authenticate requests. `google-auth-library-java` supports a wide range of authentication types, +to authenticate requests. `google-auth-library-java` supports a wide range of authentication types; see the project's [README](https://github.com/google/google-auth-library-java/blob/master/README.md) and [javadoc](http://google.github.io/google-auth-library-java/releases/0.6.0/apidocs/) for more details. @@ -152,10 +152,10 @@ Storage storage = StorageOptions.getDefaultInstance().getService(); ``` * If running locally for development/testing, you can use the [Google Cloud SDK](https://cloud.google.com/sdk/). Create Application Default Credentials with - `gcloud auth application-default login`, `google-cloud` will automatically detect such + `gcloud auth application-default login`, and then `google-cloud` will automatically detect such credentials. * If you already have an OAuth2 access token, you can use it to authenticate (notice that in this - case the access token will not be automatically refreshed): + case, the access token will not be automatically refreshed): ```java Storage storage = StorageOptions.newBuilder() .setCredentials(new GoogleCredentials(new AccessToken(accessToken, expirationTime))) @@ -167,7 +167,7 @@ If no credentials are provided, `google-cloud` will attempt to detect them from using `GoogleCredentials.getApplicationDefault()` which will search for Default Application Credentials in the following locations (in order): -1. Credentials file pointed to by the `GOOGLE_APPLICATION_CREDENTIALS` environment variable +1. The credentials file pointed to by the `GOOGLE_APPLICATION_CREDENTIALS` environment variable 2. Credentials provided by the Google Cloud SDK `gcloud auth application-default login` command 3. Google App Engine built-in credentials 4. Google Cloud Shell built-in credentials From e8f9f6e3fd7f4c31359f54584924ba7916958d45 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Tue, 8 Nov 2016 00:38:05 +0100 Subject: [PATCH 4/4] Add NoCredentials class and remove setNoCredentials method --- TESTING.md | 4 +- .../cloud/bigquery/SerializationTest.java | 3 +- .../cloud/compute/SerializationTest.java | 3 +- .../com/google/cloud/GrpcServiceOptions.java | 2 +- .../com/google/cloud/HttpServiceOptions.java | 3 +- .../java/com/google/cloud/NoCredentials.java | 41 +++++++++++++++++++ .../java/com/google/cloud/ServiceOptions.java | 39 +++++------------- .../com/google/cloud/ServiceOptionsTest.java | 5 +-- .../testing/LocalDatastoreHelper.java | 3 +- .../cloud/datastore/SerializationTest.java | 3 +- .../testing/LocalDatastoreHelperTest.java | 5 ++- .../cloud/dns/testing/LocalDnsHelper.java | 3 +- .../google/cloud/dns/SerializationTest.java | 3 +- .../cloud/logging/SerializationTest.java | 3 +- .../pubsub/testing/LocalPubsubHelper.java | 3 +- .../cloud/pubsub/SerializationTest.java | 3 +- .../testing/LocalResourceManagerHelper.java | 3 +- .../cloud/storage/SerializationTest.java | 3 +- .../cloud/translate/TranslateOptions.java | 3 +- .../cloud/translate/SerializationTest.java | 3 +- 20 files changed, 88 insertions(+), 50 deletions(-) create mode 100644 google-cloud-core/src/main/java/com/google/cloud/NoCredentials.java diff --git a/TESTING.md b/TESTING.md index 78908e2b98b0..67d8c6650cd9 100644 --- a/TESTING.md +++ b/TESTING.md @@ -102,7 +102,7 @@ You can test against a remote Datastore emulator as well. To do this, set the ` DatastoreOptions options = DatastoreOptions.newBuilder() .setProjectId("my-project-id") // must match project ID specified on remote machine .setHost("http://:") - .setNoCredentials() + .setCredentials(NoCredentials.getInstance()) .build(); Datastore localDatastore = options.getService(); ``` @@ -209,7 +209,7 @@ endpoint to the hostname of the remote machine, like the example below. PubSubOptions options = PubSubOptions.newBuilder() .setProjectId("my-project-id") // must match project ID specified on remote machine .setHost(":") - .setNoCredentials() + .setCredentials(NoCredentials.getInstance()) .build(); PubSub localPubsub = options.getService(); ``` diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java index 5e7a47781ca3..65f7c33715b2 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java @@ -17,6 +17,7 @@ package com.google.cloud.bigquery; import com.google.cloud.BaseSerializationTest; +import com.google.cloud.NoCredentials; import com.google.cloud.Restorable; import com.google.cloud.bigquery.StandardTableDefinition.StreamingBuffer; import com.google.common.collect.ImmutableList; @@ -228,7 +229,7 @@ public class SerializationTest extends BaseSerializationTest { protected Serializable[] serializableObjects() { BigQueryOptions options = BigQueryOptions.newBuilder() .setProjectId("p1") - .setNoCredentials() + .setCredentials(NoCredentials.getInstance()) .build(); BigQueryOptions otherOptions = options.toBuilder().setProjectId("p2").build(); return new Serializable[]{DOMAIN_ACCESS, GROUP_ACCESS, USER_ACCESS, VIEW_ACCESS, DATASET_ID, diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java index 779bfa37b6ff..93fe6d16f4a1 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java @@ -17,6 +17,7 @@ package com.google.cloud.compute; import com.google.cloud.BaseSerializationTest; +import com.google.cloud.NoCredentials; import com.google.cloud.Restorable; import com.google.cloud.RetryParams; import com.google.cloud.compute.AttachedDisk.CreateDiskConfiguration; @@ -264,7 +265,7 @@ public class SerializationTest extends BaseSerializationTest { protected Serializable[] serializableObjects() { ComputeOptions options = ComputeOptions.newBuilder() .setProjectId("p1") - .setNoCredentials() + .setCredentials(NoCredentials.getInstance()) .build(); ComputeOptions otherOptions = options.toBuilder() .setProjectId("p2") diff --git a/google-cloud-core/src/main/java/com/google/cloud/GrpcServiceOptions.java b/google-cloud-core/src/main/java/com/google/cloud/GrpcServiceOptions.java index 03d180d736fd..25cd8a29cc56 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/GrpcServiceOptions.java +++ b/google-cloud-core/src/main/java/com/google/cloud/GrpcServiceOptions.java @@ -320,7 +320,7 @@ protected ConnectionSettings.Builder getConnectionSettings() { .setServiceAddress(hostAndPort.getHostText()) .setPort(hostAndPort.getPort()); Credentials scopedCredentials = getScopedCredentials(); - if (scopedCredentials != null) { + if (scopedCredentials != null && scopedCredentials != NoCredentials.getInstance()) { builder.provideCredentialsWith(scopedCredentials); } return builder; diff --git a/google-cloud-core/src/main/java/com/google/cloud/HttpServiceOptions.java b/google-cloud-core/src/main/java/com/google/cloud/HttpServiceOptions.java index 515877e0b961..d816ed1a7bd3 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/HttpServiceOptions.java +++ b/google-cloud-core/src/main/java/com/google/cloud/HttpServiceOptions.java @@ -215,7 +215,8 @@ public HttpRequestInitializer httpRequestInitializer() { public HttpRequestInitializer getHttpRequestInitializer() { Credentials scopedCredentials = getScopedCredentials(); final HttpRequestInitializer delegate = - scopedCredentials != null ? new HttpCredentialsAdapter(scopedCredentials) : null; + scopedCredentials != null && scopedCredentials != NoCredentials.getInstance() + ? new HttpCredentialsAdapter(scopedCredentials) : null; return new HttpRequestInitializer() { @Override public void initialize(HttpRequest httpRequest) throws IOException { diff --git a/google-cloud-core/src/main/java/com/google/cloud/NoCredentials.java b/google-cloud-core/src/main/java/com/google/cloud/NoCredentials.java new file mode 100644 index 000000000000..3f5cfbdbfc02 --- /dev/null +++ b/google-cloud-core/src/main/java/com/google/cloud/NoCredentials.java @@ -0,0 +1,41 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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. + */ + +package com.google.cloud; + +import com.google.auth.oauth2.OAuth2Credentials; + +import java.io.ObjectStreamException; + +/** + * A placeholder for credentials to signify that requests sent to the server should not be + * authenticated. This is typically useful when using local service emulators. + */ +public class NoCredentials extends OAuth2Credentials { + + private static final long serialVersionUID = -6263971603971044288L; + private static final NoCredentials INSTANCE = new NoCredentials(); + + private NoCredentials() {} + + private Object readResolve() throws ObjectStreamException { + return INSTANCE; + } + + public static NoCredentials getInstance() { + return INSTANCE; + } +} diff --git a/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java b/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java index c938c0eb411d..c14c770e3bc8 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java +++ b/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java @@ -84,7 +84,6 @@ public abstract class ServiceOptions, Service private final String serviceRpcFactoryClassName; private final String serviceFactoryClassName; private final Clock clock; - private final boolean noCredentials; private final Credentials credentials; private transient ServiceRpcFactory serviceRpcFactory; @@ -106,7 +105,6 @@ protected abstract static class Builder, Serv private String projectId; private String host; - private boolean noCredentials; private Credentials credentials; private RetryParams retryParams; private ServiceFactory serviceFactory; @@ -118,7 +116,6 @@ protected Builder() {} protected Builder(ServiceOptions options) { projectId = options.projectId; host = options.host; - noCredentials = options.noCredentials; credentials = options.credentials; retryParams = options.retryParams; serviceFactory = options.serviceFactory; @@ -214,29 +211,18 @@ public B setHost(String host) { } /** - * Sets the service authentication credentials. If this method or {@link #setNoCredentials() are - * not used on the builder, {@link GoogleCredentials#getApplicationDefault()} will be used to - * attempt getting credentials from the environment. + * Sets the service authentication credentials. If no credentials are set, + * {@link GoogleCredentials#getApplicationDefault()} will be used to attempt getting credentials + * from the environment. Use {@link NoCredentials#getInstance()} to skip authentication, this is + * typically useful when using local service emulators. * * @param credentials authentication credentials, should not be {@code null} * @return the builder * @throws NullPointerException if {@code credentials} is {@code null}. To disable - * authentication use {@link Builder#setNoCredentials()} + * authentication use {@link NoCredentials#getInstance()} */ public B setCredentials(Credentials credentials) { this.credentials = checkNotNull(credentials); - this.noCredentials = false; - return self(); - } - - /** - * Sets that no credentials should be used. This is typically useful when using the local - * service emulators, such as {@code LocalDatastoreHelper}, {@code LocalPubsubHelper} and - * {@code LocalResourceManagerHelper}. - */ - public B setNoCredentials() { - this.noCredentials = true; - this.credentials = null; return self(); } @@ -296,9 +282,7 @@ protected ServiceOptions(Class> ser + "or the environment. Please set a project ID using the builder."); } host = firstNonNull(builder.host, getDefaultHost()); - noCredentials = builder.noCredentials; - credentials = builder.credentials != null || noCredentials - ? builder.credentials : defaultCredentials(); + credentials = builder.credentials != null ? builder.credentials : defaultCredentials(); retryParams = firstNonNull(builder.retryParams, defaultRetryParams()); serviceFactory = firstNonNull(builder.serviceFactory, getFromServiceLoader(serviceFactoryClass, getDefaultServiceFactory())); @@ -540,8 +524,8 @@ public Credentials getCredentials() { */ public Credentials getScopedCredentials() { Credentials credentialsToReturn = credentials; - if (credentials instanceof GoogleCredentials && - ((GoogleCredentials) credentials).createScopedRequired()) { + if (credentials instanceof GoogleCredentials + && ((GoogleCredentials) credentials).createScopedRequired()) { credentialsToReturn = ((GoogleCredentials) credentials).createScoped(getScopes()); } return credentialsToReturn; @@ -626,13 +610,12 @@ public String getLibraryVersion() { } protected int baseHashCode() { - return Objects.hash(projectId, host, noCredentials, credentials, retryParams, - serviceFactoryClassName, serviceRpcFactoryClassName, clock); + return Objects.hash(projectId, host, credentials, retryParams, serviceFactoryClassName, + serviceRpcFactoryClassName, clock); } protected boolean baseEquals(ServiceOptions other) { - return noCredentials == other.noCredentials - && Objects.equals(projectId, other.projectId) + return Objects.equals(projectId, other.projectId) && Objects.equals(host, other.host) && Objects.equals(credentials, other.credentials) && Objects.equals(retryParams, other.retryParams) diff --git a/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java b/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java index 1565aa4aecd8..cf364db57ec1 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java @@ -18,7 +18,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -84,7 +83,7 @@ public class ServiceOptionsTest { .build(); private static final TestServiceOptions OPTIONS_NO_CREDENTIALS = TestServiceOptions.newBuilder() - .setNoCredentials() + .setCredentials(NoCredentials.getInstance()) .setClock(TEST_CLOCK) .setHost("host") .setProjectId("project-id") @@ -224,7 +223,7 @@ public void testBuilder() { @Test public void testBuilderNoCredentials() { - assertNull(OPTIONS_NO_CREDENTIALS.getCredentials()); + assertEquals(NoCredentials.getInstance(), OPTIONS_NO_CREDENTIALS.getCredentials()); assertSame(TEST_CLOCK, OPTIONS_NO_CREDENTIALS.getClock()); assertEquals("host", OPTIONS_NO_CREDENTIALS.getHost()); assertEquals("project-id", OPTIONS_NO_CREDENTIALS.getProjectId()); diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java index c484153a27e1..99a5067a7827 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java @@ -19,6 +19,7 @@ import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; +import com.google.cloud.NoCredentials; import com.google.cloud.RetryParams; import com.google.cloud.datastore.DatastoreOptions; import com.google.common.base.Strings; @@ -639,7 +640,7 @@ private DatastoreOptions.Builder optionsBuilder() { return DatastoreOptions.newBuilder() .setProjectId(projectId) .setHost("localhost:" + Integer.toString(port)) - .setNoCredentials() + .setCredentials(NoCredentials.getInstance()) .setRetryParams(RetryParams.noRetries()); } diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java index b3135c247e9e..d92c8cd695b0 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java @@ -19,6 +19,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; import com.google.cloud.BaseSerializationTest; +import com.google.cloud.NoCredentials; import com.google.cloud.Restorable; import com.google.cloud.datastore.StructuredQuery.CompositeFilter; import com.google.cloud.datastore.StructuredQuery.OrderBy; @@ -110,7 +111,7 @@ public class SerializationTest extends BaseSerializationTest { @Override protected java.io.Serializable[] serializableObjects() { DatastoreOptions options = DatastoreOptions.newBuilder() - .setNoCredentials() + .setCredentials(NoCredentials.getInstance()) .setProjectId("ds1") .build(); DatastoreOptions otherOptions = options.toBuilder().setNamespace("ns1").build(); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java index 98da680a129e..589fa33d4a8e 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java @@ -22,6 +22,7 @@ import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; +import com.google.cloud.NoCredentials; import com.google.cloud.datastore.Datastore; import com.google.cloud.datastore.DatastoreException; import com.google.cloud.datastore.DatastoreOptions; @@ -72,11 +73,11 @@ public void testOptions() { DatastoreOptions options = helper.getOptions(); assertTrue(options.getProjectId().startsWith(PROJECT_ID_PREFIX)); assertTrue(options.getHost().startsWith("localhost:")); - assertNull(options.getCredentials()); + assertSame(NoCredentials.getInstance(), options.getCredentials()); options = helper.getOptions(NAMESPACE); assertTrue(options.getProjectId().startsWith(PROJECT_ID_PREFIX)); assertTrue(options.getHost().startsWith("localhost:")); - assertNull(options.getCredentials()); + assertSame(NoCredentials.getInstance(), options.getCredentials()); assertEquals(NAMESPACE, options.getNamespace()); } diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/LocalDnsHelper.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/LocalDnsHelper.java index cb6b1ffecb25..4d7fb277c388 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/LocalDnsHelper.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/LocalDnsHelper.java @@ -28,6 +28,7 @@ import com.google.api.services.dns.model.Project; import com.google.api.services.dns.model.Quota; import com.google.api.services.dns.model.ResourceRecordSet; +import com.google.cloud.NoCredentials; import com.google.cloud.dns.DnsOptions; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; @@ -506,7 +507,7 @@ public DnsOptions getOptions() { return DnsOptions.newBuilder() .setProjectId(PROJECT_ID) .setHost("http://localhost:" + port) - .setNoCredentials() + .setCredentials(NoCredentials.getInstance()) .build(); } diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java index 37ac272d010c..8364f56960bf 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java @@ -17,6 +17,7 @@ package com.google.cloud.dns; import com.google.cloud.BaseSerializationTest; +import com.google.cloud.NoCredentials; import com.google.cloud.Restorable; import com.google.cloud.RetryParams; import com.google.common.collect.ImmutableList; @@ -88,7 +89,7 @@ public class SerializationTest extends BaseSerializationTest { @Override protected Serializable[] serializableObjects() { DnsOptions options = DnsOptions.newBuilder() - .setNoCredentials() + .setCredentials(NoCredentials.getInstance()) .setProjectId("id1") .build(); DnsOptions otherOptions = options.toBuilder().build(); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java index 14db61d80db9..eca34b4187bc 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java @@ -18,6 +18,7 @@ import com.google.cloud.BaseSerializationTest; import com.google.cloud.MonitoredResource; +import com.google.cloud.NoCredentials; import com.google.cloud.Restorable; import com.google.cloud.logging.Logging.EntryListOption; import com.google.cloud.logging.Logging.ListOption; @@ -40,7 +41,7 @@ public class SerializationTest extends BaseSerializationTest { private static final Logging LOGGING = LoggingOptions.newBuilder() .setProjectId("p") - .setNoCredentials() + .setCredentials(NoCredentials.getInstance()) .setHost("localhost") .build().getService(); private static final HttpRequest HTTP_REQUEST = HttpRequest.newBuilder() diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/LocalPubsubHelper.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/LocalPubsubHelper.java index db01f60fa882..93cc35e57b87 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/LocalPubsubHelper.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/LocalPubsubHelper.java @@ -19,6 +19,7 @@ import com.google.api.gax.testing.DownloadableEmulatorRunner; import com.google.api.gax.testing.GCloudEmulatorRunner; import com.google.api.gax.testing.LocalServiceHelper; +import com.google.cloud.NoCredentials; import com.google.cloud.RetryParams; import com.google.cloud.pubsub.PubSubOptions; @@ -157,7 +158,7 @@ public PubSubOptions getOptions() { return PubSubOptions.newBuilder() .setProjectId(projectId) .setHost("localhost:" + port) - .setNoCredentials() + .setCredentials(NoCredentials.getInstance()) .setRetryParams(RetryParams.noRetries()) .build(); } diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SerializationTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SerializationTest.java index ca4e8bf3b62e..b200b42989b1 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SerializationTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SerializationTest.java @@ -18,6 +18,7 @@ import com.google.cloud.BaseSerializationTest; import com.google.cloud.GrpcServiceOptions.ExecutorFactory; +import com.google.cloud.NoCredentials; import com.google.cloud.Restorable; import com.google.cloud.pubsub.PubSub.ListOption; import com.google.cloud.pubsub.PubSub.PullOption; @@ -29,7 +30,7 @@ public class SerializationTest extends BaseSerializationTest { private static final PubSub PUB_SUB = PubSubOptions.newBuilder() .setProjectId("p") - .setNoCredentials() + .setCredentials(NoCredentials.getInstance()) .setHost("localhost") .build().getService(); private static final Message MESSAGE = Message.of("payload"); diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelper.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelper.java index e20c44f8f7f7..45c3af96df0d 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelper.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelper.java @@ -27,6 +27,7 @@ import com.google.api.services.cloudresourcemanager.model.SetIamPolicyRequest; import com.google.api.services.cloudresourcemanager.model.TestIamPermissionsRequest; import com.google.api.services.cloudresourcemanager.model.TestIamPermissionsResponse; +import com.google.cloud.NoCredentials; import com.google.cloud.resourcemanager.ResourceManagerOptions; import com.google.common.base.Joiner; import com.google.common.base.Objects; @@ -685,7 +686,7 @@ public ResourceManagerOptions options() { public ResourceManagerOptions getOptions() { return ResourceManagerOptions.newBuilder() .setHost("http://localhost:" + port) - .setNoCredentials() + .setCredentials(NoCredentials.getInstance()) .build(); } diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java index 354a49dded60..ed43092f2461 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java @@ -17,6 +17,7 @@ package com.google.cloud.storage; import com.google.cloud.BaseSerializationTest; +import com.google.cloud.NoCredentials; import com.google.cloud.PageImpl; import com.google.cloud.ReadChannel; import com.google.cloud.Restorable; @@ -65,7 +66,7 @@ public class SerializationTest extends BaseSerializationTest { protected Serializable[] serializableObjects() { StorageOptions options = StorageOptions.newBuilder() .setProjectId("p1") - .setNoCredentials() + .setCredentials(NoCredentials.getInstance()) .build(); StorageOptions otherOptions = options.toBuilder().setProjectId("p2").build(); return new Serializable[]{ACL_DOMAIN, ACL_GROUP, ACL_PROJECT_, ACL_USER, ACL_RAW, ACL, diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java index c06548d2b79f..acdb192b00c6 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java @@ -21,6 +21,7 @@ import com.google.auth.Credentials; import com.google.cloud.HttpServiceOptions; +import com.google.cloud.NoCredentials; import com.google.cloud.translate.Translate.TranslateOption; import com.google.cloud.translate.spi.DefaultTranslateRpc; import com.google.cloud.translate.spi.TranslateRpc; @@ -158,7 +159,7 @@ public Builder setTargetLanguage(String targetLanguage) { @Override public TranslateOptions build() { // Auth credentials are not used by Translate - setNoCredentials(); + setCredentials(NoCredentials.getInstance()); return new TranslateOptions(this); } } diff --git a/google-cloud-translate/src/test/java/com/google/cloud/translate/SerializationTest.java b/google-cloud-translate/src/test/java/com/google/cloud/translate/SerializationTest.java index d6cfdc40e93e..d463270e31c6 100644 --- a/google-cloud-translate/src/test/java/com/google/cloud/translate/SerializationTest.java +++ b/google-cloud-translate/src/test/java/com/google/cloud/translate/SerializationTest.java @@ -19,6 +19,7 @@ import com.google.api.services.translate.model.DetectionsResourceItems; import com.google.api.services.translate.model.TranslationsResource; import com.google.cloud.BaseSerializationTest; +import com.google.cloud.NoCredentials; import com.google.cloud.Restorable; import java.io.Serializable; @@ -47,7 +48,7 @@ public class SerializationTest extends BaseSerializationTest { protected Serializable[] serializableObjects() { TranslateOptions options = TranslateOptions.newBuilder() .setApiKey(API_KEY) - .setNoCredentials() + .setCredentials(NoCredentials.getInstance()) .build(); TranslateOptions otherOptions = options.toBuilder().build(); return new Serializable[]{DETECTION, TRANSLATION, TRANSLATE_EXCEPTION, LANGUAGE_LIST_OPTION,