From 9cb508169d6d2c02b44dce02a15e142e5a6092c4 Mon Sep 17 00:00:00 2001 From: hiranya911 Date: Mon, 26 Feb 2018 14:09:00 -0800 Subject: [PATCH] Removed the deprecated FirebaseCredential API --- .../com/google/firebase/FirebaseOptions.java | 44 ++- .../firebase/auth/FirebaseCredential.java | 39 --- .../firebase/auth/FirebaseCredentials.java | 223 ------------- .../firebase/auth/GoogleOAuthAccessToken.java | 62 ---- .../auth/internal/BaseCredential.java | 77 ----- .../internal/FirebaseCredentialsAdapter.java | 51 --- .../google/firebase/FirebaseOptionsTest.java | 35 +-- .../firebase/auth/FirebaseAuthTest.java | 42 +-- .../auth/FirebaseCredentialsTest.java | 292 ------------------ 9 files changed, 30 insertions(+), 835 deletions(-) delete mode 100644 src/main/java/com/google/firebase/auth/FirebaseCredential.java delete mode 100644 src/main/java/com/google/firebase/auth/FirebaseCredentials.java delete mode 100644 src/main/java/com/google/firebase/auth/GoogleOAuthAccessToken.java delete mode 100644 src/main/java/com/google/firebase/auth/internal/BaseCredential.java delete mode 100644 src/main/java/com/google/firebase/auth/internal/FirebaseCredentialsAdapter.java delete mode 100644 src/test/java/com/google/firebase/auth/FirebaseCredentialsTest.java diff --git a/src/main/java/com/google/firebase/FirebaseOptions.java b/src/main/java/com/google/firebase/FirebaseOptions.java index fc4df2658..948d6a0a6 100644 --- a/src/main/java/com/google/firebase/FirebaseOptions.java +++ b/src/main/java/com/google/firebase/FirebaseOptions.java @@ -25,21 +25,35 @@ import com.google.api.client.util.Key; import com.google.auth.oauth2.GoogleCredentials; import com.google.common.base.Strings; -import com.google.firebase.auth.FirebaseCredential; -import com.google.firebase.auth.FirebaseCredentials; -import com.google.firebase.auth.internal.BaseCredential; -import com.google.firebase.auth.internal.FirebaseCredentialsAdapter; +import com.google.common.collect.ImmutableList; import com.google.firebase.internal.FirebaseThreadManagers; import com.google.firebase.internal.NonNull; import com.google.firebase.internal.Nullable; import java.util.HashMap; +import java.util.List; import java.util.Map; /** Configurable Firebase options. */ public final class FirebaseOptions { - // TODO: deprecate and remove it once we can fetch these from Remote Config. + private static final List FIREBASE_SCOPES = + ImmutableList.of( + // Enables access to Firebase Realtime Database. + "https://www.googleapis.com/auth/firebase.database", + + // Enables access to the email address associated with a project. + "https://www.googleapis.com/auth/userinfo.email", + + // Enables access to Google Identity Toolkit (for user management APIs). + "https://www.googleapis.com/auth/identitytoolkit", + + // Enables access to Google Cloud Storage. + "https://www.googleapis.com/auth/devstorage.full_control", + + // Enables access to Google Cloud Firestore + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/datastore"); private final String databaseUrl; private final String storageBucket; @@ -53,7 +67,7 @@ public final class FirebaseOptions { private FirebaseOptions(@NonNull FirebaseOptions.Builder builder) { this.credentials = checkNotNull(builder.credentials, "FirebaseOptions must be initialized with setCredentials().") - .createScoped(BaseCredential.FIREBASE_SCOPES); + .createScoped(FIREBASE_SCOPES); this.databaseUrl = builder.databaseUrl; this.databaseAuthVariableOverride = builder.databaseAuthVariableOverride; this.projectId = builder.projectId; @@ -230,24 +244,6 @@ public Builder setCredentials(GoogleCredentials credentials) { return this; } - /** - * Sets the FirebaseCredential to use to authenticate the SDK. - * - * @param credential A FirebaseCredential used to authenticate the SDK. See {@link - * FirebaseCredentials} for default implementations. - * @return This Builder instance is returned so subsequent calls can be chained. - * @deprecated Use {@link FirebaseOptions.Builder#setCredentials(GoogleCredentials)}. - */ - public Builder setCredential(@NonNull FirebaseCredential credential) { - checkNotNull(credential); - if (credential instanceof BaseCredential) { - this.credentials = ((BaseCredential) credential).getGoogleCredentials(); - } else { - this.credentials = new FirebaseCredentialsAdapter(credential); - } - return this; - } - /** * Sets the auth variable to be used by the Realtime Database rules. * diff --git a/src/main/java/com/google/firebase/auth/FirebaseCredential.java b/src/main/java/com/google/firebase/auth/FirebaseCredential.java deleted file mode 100644 index b238d299c..000000000 --- a/src/main/java/com/google/firebase/auth/FirebaseCredential.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.firebase.auth; - -import com.google.firebase.tasks.Task; - -/** - * Provides Google OAuth2 access tokens used to authenticate with Firebase services. In most cases, - * you will not need to implement this yourself and can instead use the default implementations - * provided by {@link FirebaseCredentials}. - * - * @deprecated Use {@code GoogleCredentials}. - */ -public interface FirebaseCredential { - - /** - * Returns a Google OAuth2 access token which can be used to authenticate with Firebase services. - * This method does not cache tokens, and therefore each invocation will fetch a fresh token. - * The caller is expected to implement caching by referencing the token expiry details - * available in the returned GoogleOAuthAccessToken instance. - * - * @return A {@link Task} providing a Google OAuth access token. - */ - Task getAccessToken(); -} diff --git a/src/main/java/com/google/firebase/auth/FirebaseCredentials.java b/src/main/java/com/google/firebase/auth/FirebaseCredentials.java deleted file mode 100644 index 4ae1d62da..000000000 --- a/src/main/java/com/google/firebase/auth/FirebaseCredentials.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.firebase.auth; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.api.client.googleapis.util.Utils; -import com.google.api.client.http.HttpTransport; -import com.google.api.client.json.JsonFactory; -import com.google.auth.http.HttpTransportFactory; -import com.google.auth.oauth2.GoogleCredentials; -import com.google.auth.oauth2.ServiceAccountCredentials; -import com.google.auth.oauth2.UserCredentials; -import com.google.common.base.Strings; -import com.google.firebase.auth.internal.BaseCredential; -import com.google.firebase.internal.NonNull; - -import java.io.IOException; -import java.io.InputStream; - -/** - * Standard {@link FirebaseCredential} implementations for use with {@link - * com.google.firebase.FirebaseOptions}. - * - * @deprecated Use {@code GoogleCredentials}. - */ -public class FirebaseCredentials { - - private FirebaseCredentials() { - } - - /** - * Returns a {@link FirebaseCredential} based on Google Application Default Credentials which can - * be used to authenticate the SDK. - * - *

See Google - * Application Default Credentials for details on Google Application Deafult Credentials. - * - *

See Initialize the SDK for code samples - * and detailed documentation. - * - * @return A {@link FirebaseCredential} based on Google Application Default Credentials which can - * be used to authenticate the SDK. - */ - @NonNull - public static FirebaseCredential applicationDefault() { - return DefaultCredentialsHolder.INSTANCE; - } - - /** - * Returns a {@link FirebaseCredential} based on Google Application Default Credentials which can - * be used to authenticate the SDK. Allows specifying the HttpTransport and the - * JsonFactory to be used when communicating with the remote authentication server. - * - *

See Google - * Application Default Credentials for details on Google Application Deafult Credentials. - * - *

See Initialize the SDK for code samples - * and detailed documentation. - * - * @param transport HttpTransport used to communicate with the remote - * authentication server. - * @param jsonFactory JsonFactory used to parse JSON responses from the remote - * authentication server. - * @return A {@link FirebaseCredential} based on Google Application Default Credentials which can - * be used to authenticate the SDK. - */ - @NonNull - public static FirebaseCredential applicationDefault( - HttpTransport transport, JsonFactory jsonFactory) { - try { - return new ApplicationDefaultCredential(transport); - } catch (IOException e) { - // To prevent a breaking API change, we throw an unchecked exception. - throw new RuntimeException(e); - } - } - - /** - * Returns a {@link FirebaseCredential} generated from the provided service account certificate - * which can be used to authenticate the SDK. - * - *

See Initialize the SDK for code samples - * and detailed documentation. - * - * @param serviceAccount An InputStream containing the JSON representation of a - * service account certificate. - * @return A {@link FirebaseCredential} generated from the provided service account certificate - * which can be used to authenticate the SDK. - * @throws IOException If an error occurs while parsing the service account certificate. - */ - @NonNull - public static FirebaseCredential fromCertificate(InputStream serviceAccount) throws IOException { - return fromCertificate(serviceAccount, Utils.getDefaultTransport(), - Utils.getDefaultJsonFactory()); - } - - /** - * Returns a {@link FirebaseCredential} generated from the provided service account certificate - * which can be used to authenticate the SDK. Allows specifying the HttpTransport - * and the JsonFactory to be used when communicating with the remote authentication - * server. - * - *

See Initialize the SDK for code samples - * and detailed documentation. - * - * @param serviceAccount An InputStream containing the JSON representation of a - * service account certificate. - * @param transport HttpTransport used to communicate with the remote - * authentication server. - * @param jsonFactory JsonFactory used to parse JSON responses from the remote - * authentication server. - * @return A {@link FirebaseCredential} generated from the provided service account certificate - * which can be used to authenticate the SDK. - * @throws IOException If an error occurs while parsing the service account certificate. - */ - @NonNull - public static FirebaseCredential fromCertificate(InputStream serviceAccount, - HttpTransport transport, JsonFactory jsonFactory) throws IOException { - ServiceAccountCredentials credentials = ServiceAccountCredentials.fromStream( - serviceAccount, wrap(transport)); - checkArgument(!Strings.isNullOrEmpty(credentials.getProjectId()), - "Failed to parse service account: 'project_id' must be set"); - return new CertCredential(credentials); - } - - /** - * Returns a {@link FirebaseCredential} generated from the provided refresh token which can be - * used to authenticate the SDK. - * - *

See Initialize the SDK for code samples - * and detailed documentation. - * - * @param refreshToken An InputStream containing the JSON representation of a refresh - * token. - * @return A {@link FirebaseCredential} generated from the provided service account credential - * which can be used to authenticate the SDK. - * @throws IOException If an error occurs while parsing the refresh token. - */ - @NonNull - public static FirebaseCredential fromRefreshToken(InputStream refreshToken) throws IOException { - return fromRefreshToken( - refreshToken, Utils.getDefaultTransport(), Utils.getDefaultJsonFactory()); - } - - /** - * Returns a {@link FirebaseCredential} generated from the provided refresh token which can be - * used to authenticate the SDK. Allows specifying the HttpTransport and the - * JsonFactory to be used when communicating with the remote authentication server. - * - *

See Initialize the SDK for code samples - * and detailed documentation. - * - * @param refreshToken An InputStream containing the JSON representation of a refresh - * token. - * @param transport HttpTransport used to communicate with the remote - * authentication server. - * @param jsonFactory JsonFactory used to parse JSON responses from the remote - * authentication server. - * @return A {@link FirebaseCredential} generated from the provided service account credential - * which can be used to authenticate the SDK. - * @throws IOException If an error occurs while parsing the refresh token. - */ - @NonNull - public static FirebaseCredential fromRefreshToken(final InputStream refreshToken, - HttpTransport transport, JsonFactory jsonFactory) throws IOException { - return new RefreshTokenCredential(refreshToken, transport); - } - - static class CertCredential extends BaseCredential { - - CertCredential(ServiceAccountCredentials credentials) throws IOException { - super(credentials); - } - } - - static class ApplicationDefaultCredential extends BaseCredential { - - ApplicationDefaultCredential(HttpTransport transport) throws IOException { - super(GoogleCredentials.getApplicationDefault(wrap(transport))); - } - } - - static class RefreshTokenCredential extends BaseCredential { - - RefreshTokenCredential(InputStream inputStream, HttpTransport transport) throws IOException { - super(UserCredentials.fromStream(inputStream, wrap(transport))); - } - } - - private static class DefaultCredentialsHolder { - - static final FirebaseCredential INSTANCE = - applicationDefault(Utils.getDefaultTransport(), Utils.getDefaultJsonFactory()); - } - - private static HttpTransportFactory wrap(final HttpTransport transport) { - checkNotNull(transport, "HttpTransport must not be null"); - return new HttpTransportFactory() { - @Override - public HttpTransport create() { - return transport; - } - }; - } -} diff --git a/src/main/java/com/google/firebase/auth/GoogleOAuthAccessToken.java b/src/main/java/com/google/firebase/auth/GoogleOAuthAccessToken.java deleted file mode 100644 index 85e6021e3..000000000 --- a/src/main/java/com/google/firebase/auth/GoogleOAuthAccessToken.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.firebase.auth; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.common.base.Strings; - -/** - * Represents an OAuth access token, which can be used to access Firebase and other qualified - * Google APIs. Encapsulates both the token string, and its expiration time. - * - * @deprecated Use GoogleCredentials and associated classes. - */ -public class GoogleOAuthAccessToken { - - - private final String accessToken; - private final long expiryTime; - - /** - * Create a new GoogleOAuthAccessToken instance - * - * @param accessToken JWT access token string - * @param expiryTime Time at which the token will expire (milliseconds since epoch) - * @throws IllegalArgumentException If the token is null or empty - */ - public GoogleOAuthAccessToken(String accessToken, long expiryTime) { - checkArgument(!Strings.isNullOrEmpty(accessToken), "Access token must not be null"); - this.accessToken = accessToken; - this.expiryTime = expiryTime; - } - - /** - * Returns the JWT access token. - */ - public String getAccessToken() { - return accessToken; - } - - /** - * Returns the expiration time as a milliseconds since epoch timestamp. - */ - public long getExpiryTime() { - return expiryTime; - } - -} diff --git a/src/main/java/com/google/firebase/auth/internal/BaseCredential.java b/src/main/java/com/google/firebase/auth/internal/BaseCredential.java deleted file mode 100644 index d15832a55..000000000 --- a/src/main/java/com/google/firebase/auth/internal/BaseCredential.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.firebase.auth.internal; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.auth.oauth2.AccessToken; -import com.google.auth.oauth2.GoogleCredentials; -import com.google.common.collect.ImmutableList; -import com.google.firebase.auth.FirebaseCredential; -import com.google.firebase.auth.GoogleOAuthAccessToken; -import com.google.firebase.tasks.Task; -import com.google.firebase.tasks.Tasks; - -import java.io.IOException; -import java.util.List; - -/** - * Internal base class for built-in FirebaseCredential implementations. - */ -public abstract class BaseCredential implements FirebaseCredential { - - public static final List FIREBASE_SCOPES = - ImmutableList.of( - // Enables access to Firebase Realtime Database. - "https://www.googleapis.com/auth/firebase.database", - - // Enables access to the email address associated with a project. - "https://www.googleapis.com/auth/userinfo.email", - - // Enables access to Google Identity Toolkit (for user management APIs). - "https://www.googleapis.com/auth/identitytoolkit", - - // Enables access to Google Cloud Storage. - "https://www.googleapis.com/auth/devstorage.full_control", - - // Enables access to Google Cloud Firestore - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/datastore"); - - private final GoogleCredentials googleCredentials; - - public BaseCredential(GoogleCredentials googleCredentials) { - this.googleCredentials = checkNotNull(googleCredentials).createScoped(FIREBASE_SCOPES); - } - - public final GoogleCredentials getGoogleCredentials() { - return googleCredentials; - } - - @Override - public Task getAccessToken() { - try { - AccessToken accessToken = googleCredentials.refreshAccessToken(); - GoogleOAuthAccessToken googleToken = new GoogleOAuthAccessToken(accessToken.getTokenValue(), - accessToken.getExpirationTime().getTime()); - return Tasks.forResult(googleToken); - } catch (Exception e) { - return Tasks.forException(e); - } - } - -} diff --git a/src/main/java/com/google/firebase/auth/internal/FirebaseCredentialsAdapter.java b/src/main/java/com/google/firebase/auth/internal/FirebaseCredentialsAdapter.java deleted file mode 100644 index e1b069eda..000000000 --- a/src/main/java/com/google/firebase/auth/internal/FirebaseCredentialsAdapter.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.firebase.auth.internal; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.auth.oauth2.AccessToken; -import com.google.auth.oauth2.GoogleCredentials; -import com.google.firebase.auth.FirebaseCredential; -import com.google.firebase.auth.GoogleOAuthAccessToken; -import com.google.firebase.tasks.Tasks; -import java.io.IOException; -import java.util.Date; -import java.util.concurrent.ExecutionException; - -/** - * An adapter for converting custom {@link FirebaseCredential} implementations into - * GoogleCredentials. - */ -public final class FirebaseCredentialsAdapter extends GoogleCredentials { - - private final FirebaseCredential credential; - - public FirebaseCredentialsAdapter(FirebaseCredential credential) { - this.credential = checkNotNull(credential); - } - - @Override - public AccessToken refreshAccessToken() throws IOException { - try { - GoogleOAuthAccessToken token = Tasks.await(credential.getAccessToken()); - return new AccessToken(token.getAccessToken(), new Date(token.getExpiryTime())); - } catch (ExecutionException | InterruptedException e) { - throw new IOException("Error while obtaining OAuth2 token", e); - } - } -} diff --git a/src/test/java/com/google/firebase/FirebaseOptionsTest.java b/src/test/java/com/google/firebase/FirebaseOptionsTest.java index b02fbbdc9..8c81df7b5 100644 --- a/src/test/java/com/google/firebase/FirebaseOptionsTest.java +++ b/src/test/java/com/google/firebase/FirebaseOptionsTest.java @@ -27,12 +27,9 @@ import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; +import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; -import com.google.firebase.auth.FirebaseCredential; -import com.google.firebase.auth.FirebaseCredentials; -import com.google.firebase.auth.GoogleOAuthAccessToken; -import com.google.firebase.tasks.Task; import com.google.firebase.testing.ServiceAccount; import com.google.firebase.testing.TestUtils; import java.io.IOException; @@ -75,7 +72,7 @@ protected ThreadFactory getThreadFactory() { }; @Test - public void createOptionsWithAllValuesSet() throws IOException, InterruptedException { + public void createOptionsWithAllValuesSet() throws IOException { GsonFactory jsonFactory = new GsonFactory(); NetHttpTransport httpTransport = new NetHttpTransport(); FirebaseOptions firebaseOptions = @@ -104,7 +101,7 @@ public void createOptionsWithAllValuesSet() throws IOException, InterruptedExcep } @Test - public void createOptionsWithOnlyMandatoryValuesSet() throws IOException, InterruptedException { + public void createOptionsWithOnlyMandatoryValuesSet() throws IOException { FirebaseOptions firebaseOptions = new FirebaseOptions.Builder() .setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream())) @@ -124,32 +121,12 @@ public void createOptionsWithOnlyMandatoryValuesSet() throws IOException, Interr } @Test - public void createOptionsWithFirebaseCredential() throws IOException { + public void createOptionsWithCustomFirebaseCredential() { FirebaseOptions firebaseOptions = new FirebaseOptions.Builder() - .setCredential(FirebaseCredentials.fromCertificate(ServiceAccount.EDITOR.asStream())) - .build(); - - assertNotNull(firebaseOptions.getJsonFactory()); - assertNotNull(firebaseOptions.getHttpTransport()); - assertNull(firebaseOptions.getDatabaseUrl()); - assertNull(firebaseOptions.getStorageBucket()); - - GoogleCredentials credentials = firebaseOptions.getCredentials(); - assertNotNull(credentials); - assertTrue(credentials instanceof ServiceAccountCredentials); - assertEquals( - GoogleCredential.fromStream(ServiceAccount.EDITOR.asStream()).getServiceAccountId(), - ((ServiceAccountCredentials) credentials).getClientEmail()); - } - - @Test - public void createOptionsWithCustomFirebaseCredential() throws IOException { - FirebaseOptions firebaseOptions = - new FirebaseOptions.Builder() - .setCredential(new FirebaseCredential() { + .setCredentials(new GoogleCredentials() { @Override - public Task getAccessToken() { + public AccessToken refreshAccessToken() { return null; } }) diff --git a/src/test/java/com/google/firebase/auth/FirebaseAuthTest.java b/src/test/java/com/google/firebase/auth/FirebaseAuthTest.java index eb19bafd5..bb430d285 100644 --- a/src/test/java/com/google/firebase/auth/FirebaseAuthTest.java +++ b/src/test/java/com/google/firebase/auth/FirebaseAuthTest.java @@ -106,16 +106,6 @@ public static Collection data() throws Exception { .build(), /* isCertCredential */ false }, - { - new FirebaseOptions.Builder().setCredential( - createFirebaseCertificateCredential()).build(), - /* isCertCredential */ true - }, - { - new FirebaseOptions.Builder().setCredential( - createFirebaseRefreshTokenCredential()).build(), - /* isCertCredential */ false - }, }); } @@ -141,23 +131,6 @@ public HttpTransport create() { }); } - private static FirebaseCredential createFirebaseRefreshTokenCredential() - throws IOException { - - final MockTokenServerTransport transport = new MockTokenServerTransport(); - transport.addClient(CLIENT_ID, CLIENT_SECRET); - transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); - - Map secretJson = new HashMap<>(); - secretJson.put("client_id", CLIENT_ID); - secretJson.put("client_secret", CLIENT_SECRET); - secretJson.put("refresh_token", REFRESH_TOKEN); - secretJson.put("type", "authorized_user"); - InputStream refreshTokenStream = - new ByteArrayInputStream(JSON_FACTORY.toByteArray(secretJson)); - return FirebaseCredentials.fromRefreshToken(refreshTokenStream, transport, JSON_FACTORY); - } - private static GoogleCredentials createCertificateCredential() throws IOException { final MockTokenServerTransport transport = new MockTokenServerTransport(); transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN); @@ -170,13 +143,6 @@ public HttpTransport create() { }); } - private static FirebaseCredential createFirebaseCertificateCredential() throws IOException { - final MockTokenServerTransport transport = new MockTokenServerTransport(); - transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN); - return FirebaseCredentials.fromCertificate(ServiceAccount.EDITOR.asStream(), - transport, JSON_FACTORY); - } - @Before public void setup() { TestOnlyImplFirebaseTrampolines.clearInstancesForTest(); @@ -189,7 +155,7 @@ public void cleanup() { } @Test - public void testGetInstance() throws ExecutionException, InterruptedException { + public void testGetInstance() { FirebaseAuth defaultAuth = FirebaseAuth.getInstance(); assertNotNull(defaultAuth); assertSame(defaultAuth, FirebaseAuth.getInstance()); @@ -198,7 +164,7 @@ public void testGetInstance() throws ExecutionException, InterruptedException { } @Test - public void testGetInstanceForApp() throws ExecutionException, InterruptedException { + public void testGetInstanceForApp() { FirebaseApp app = FirebaseApp.initializeApp(firebaseOptions, "testGetInstanceForApp"); FirebaseAuth auth = FirebaseAuth.getInstance(app); assertNotNull(auth); @@ -208,7 +174,7 @@ public void testGetInstanceForApp() throws ExecutionException, InterruptedExcept } @Test - public void testAppDelete() throws ExecutionException, InterruptedException { + public void testAppDelete() { FirebaseApp app = FirebaseApp.initializeApp(firebaseOptions, "testAppDelete"); FirebaseAuth auth = FirebaseAuth.getInstance(app); assertNotNull(auth); @@ -272,7 +238,7 @@ public void testInitAfterAppDelete() throws ExecutionException, InterruptedExcep } @Test - public void testAppWithAuthVariableOverrides() throws ExecutionException, InterruptedException { + public void testAppWithAuthVariableOverrides() { Map authVariableOverrides = Collections.singletonMap("uid", (Object) "uid1"); FirebaseOptions options = new FirebaseOptions.Builder(firebaseOptions) diff --git a/src/test/java/com/google/firebase/auth/FirebaseCredentialsTest.java b/src/test/java/com/google/firebase/auth/FirebaseCredentialsTest.java deleted file mode 100644 index dd52e941a..000000000 --- a/src/test/java/com/google/firebase/auth/FirebaseCredentialsTest.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.firebase.auth; - -import com.google.api.client.googleapis.testing.auth.oauth2.MockTokenServerTransport; -import com.google.api.client.googleapis.util.Utils; -import com.google.api.client.json.JsonFactory; -import com.google.auth.oauth2.AccessToken; -import com.google.auth.oauth2.GoogleCredentials; -import com.google.firebase.auth.internal.BaseCredential; -import com.google.firebase.auth.internal.FirebaseCredentialsAdapter; -import com.google.firebase.tasks.Task; -import com.google.firebase.tasks.Tasks; -import com.google.firebase.testing.ServiceAccount; -import com.google.firebase.testing.TestUtils; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -/** - * Tests for {@link FirebaseCredentials}. - */ -public class FirebaseCredentialsTest { - - private static final String ACCESS_TOKEN = "mockaccesstoken"; - private static final String CLIENT_SECRET = "mockclientsecret"; - private static final String CLIENT_ID = "mockclientid"; - private static final String REFRESH_TOKEN = "mockrefreshtoken"; - private static final JsonFactory JSON_FACTORY = Utils.getDefaultJsonFactory(); - - @Rule public final ExpectedException thrown = ExpectedException.none(); - - @BeforeClass - public static void setupClass() throws IOException { - TestUtils.getApplicationDefaultCredentials(); - } - - @Test(expected = NullPointerException.class) - public void testNullCertificate() throws IOException { - FirebaseCredentials.fromCertificate(null); - } - - @Test(expected = NullPointerException.class) - public void testNullRefreshToken() throws IOException { - FirebaseCredentials.fromRefreshToken(null); - } - - @Test - public void defaultCredentialDoesntRefetch() throws Exception { - FirebaseCredential credential = FirebaseCredentials.applicationDefault( - Utils.getDefaultTransport(), Utils.getDefaultJsonFactory()); - GoogleOAuthAccessToken token = Tasks.await(credential.getAccessToken()); - Assert.assertEquals(TestUtils.TEST_ADC_ACCESS_TOKEN, token.getAccessToken()); - Assert.assertNotNull(((BaseCredential) credential).getGoogleCredentials()); - - // We should still be able to fetch the token since the certificate is cached - credential = FirebaseCredentials.applicationDefault(); - token = Tasks.await(credential.getAccessToken()); - Assert.assertNotNull(token); - Assert.assertEquals(TestUtils.TEST_ADC_ACCESS_TOKEN, token.getAccessToken()); - Assert.assertNotNull(((BaseCredential) credential).getGoogleCredentials()); - } - - @Test - public void canResolveTokenMoreThanOnce() - throws ExecutionException, InterruptedException, IOException { - MockTokenServerTransport transport = new MockTokenServerTransport(); - transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN); - - FirebaseCredential credential = - FirebaseCredentials.fromCertificate( - ServiceAccount.EDITOR.asStream(), transport, Utils.getDefaultJsonFactory()); - - Tasks.await(credential.getAccessToken()); - Tasks.await(credential.getAccessToken()); - } - - @Test - public void certificateReadIsDoneSynchronously() - throws ExecutionException, InterruptedException, IOException { - MockTokenServerTransport transport = new MockTokenServerTransport(); - transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN); - - ByteArrayInputStream inputStream = - new ByteArrayInputStream( - ServiceAccount.EDITOR.asString().getBytes(Charset.defaultCharset())); - - FirebaseCredential credential = - FirebaseCredentials.fromCertificate(inputStream, transport, Utils.getDefaultJsonFactory()); - - Assert.assertEquals(0, inputStream.available()); - inputStream.close(); - - Assert.assertNotNull(((BaseCredential) credential).getGoogleCredentials()); - Assert.assertEquals(ACCESS_TOKEN, Tasks.await(credential.getAccessToken()).getAccessToken()); - } - - @Test - public void certificateReadChecksForProjectId() - throws ExecutionException, InterruptedException, IOException { - MockTokenServerTransport transport = new MockTokenServerTransport(); - transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN); - - String accountWithoutProjectId = - ServiceAccount.EDITOR.asString().replace("project_id", "missing"); - ByteArrayInputStream inputStream = - new ByteArrayInputStream(accountWithoutProjectId.getBytes(Charset.defaultCharset())); - - try { - FirebaseCredentials.fromCertificate(inputStream, transport, Utils.getDefaultJsonFactory()); - Assert.fail(); - } catch (IllegalArgumentException e) { - Assert.assertEquals( - "Failed to parse service account: 'project_id' must be set", e.getMessage()); - } - } - - @Test - public void certificateReadThrowsIOException() - throws ExecutionException, InterruptedException { - MockTokenServerTransport transport = new MockTokenServerTransport(); - transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN); - - InputStream inputStream = - new InputStream() { - @Override - public int read() throws IOException { - throw new IOException("Expected"); - } - }; - - - try { - FirebaseCredentials.fromCertificate(inputStream, transport, Utils.getDefaultJsonFactory()); - Assert.fail(); - } catch (IOException e) { - Assert.assertEquals("Expected", e.getMessage()); - } - } - - @Test - public void nullThrowsRuntimeExceptionFromCertificate() - throws ExecutionException, InterruptedException, IOException { - final MockTokenServerTransport transport = new MockTokenServerTransport(); - transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN); - thrown.expect(NullPointerException.class); - FirebaseCredentials.fromCertificate(null, transport, Utils.getDefaultJsonFactory()); - } - - @Test - public void nullThrowsRuntimeExceptionFromRefreshToken() - throws ExecutionException, InterruptedException, IOException { - final MockTokenServerTransport transport = new MockTokenServerTransport(); - transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN); - thrown.expect(NullPointerException.class); - FirebaseCredentials.fromRefreshToken(null, transport, Utils.getDefaultJsonFactory()); - } - - @Test - public void refreshTokenReadIsDoneSynchronously() - throws ExecutionException, InterruptedException, IOException { - MockTokenServerTransport transport = new MockTokenServerTransport(); - transport.addClient(CLIENT_ID, CLIENT_SECRET); - transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); - - Map secretJson = new HashMap<>(); - secretJson.put("client_id", CLIENT_ID); - secretJson.put("client_secret", CLIENT_SECRET); - secretJson.put("refresh_token", REFRESH_TOKEN); - secretJson.put("type", "authorized_user"); - InputStream inputStream = new ByteArrayInputStream(JSON_FACTORY.toByteArray(secretJson)); - - FirebaseCredential credential = - FirebaseCredentials.fromRefreshToken(inputStream, transport, Utils.getDefaultJsonFactory()); - - Assert.assertEquals(0, inputStream.available()); - inputStream.close(); - - Assert.assertNotNull(((BaseCredential) credential).getGoogleCredentials()); - Assert.assertEquals(ACCESS_TOKEN, Tasks.await(credential.getAccessToken()).getAccessToken()); - } - - @Test - public void refreshTokenReadThrowsIOException() - throws ExecutionException, InterruptedException { - MockTokenServerTransport transport = new MockTokenServerTransport(); - transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN); - - InputStream inputStream = - new InputStream() { - @Override - public int read() throws IOException { - throw new IOException("Expected"); - } - }; - - try { - FirebaseCredentials.fromRefreshToken(inputStream, transport, Utils.getDefaultJsonFactory()); - Assert.fail(); - } catch (IOException e) { - Assert.assertEquals("Expected", e.getMessage()); - } - } - - @Test(expected = Exception.class) - public void serviceAccountUsedAsRefreshToken() throws Exception { - FirebaseCredentials.fromRefreshToken(ServiceAccount.EDITOR.asStream()); - } - - @Test - public void tokenNotCached() throws Exception { - TestCredential credential = new TestCredential(new MockGoogleCredentials(ACCESS_TOKEN, 10L)); - - for (long i = 0; i < 10; i++) { - Assert.assertEquals(ACCESS_TOKEN, Tasks.await(credential.getAccessToken()).getAccessToken()); - Assert.assertEquals(i + 1, credential.getFetchCount()); - } - } - - @Test - public void testTokenExpiration() throws Exception { - final MockGoogleCredentials googleCredentials = new MockGoogleCredentials(ACCESS_TOKEN); - TestCredential credential = new TestCredential(googleCredentials); - - for (long i = 0; i < 10; i++) { - long expiryTime = (i + 1) * 10L; - googleCredentials.setExpiryTime(expiryTime); - GoogleOAuthAccessToken googleToken = Tasks.await(credential.getAccessToken()); - Assert.assertEquals(ACCESS_TOKEN, googleToken.getAccessToken()); - Assert.assertEquals(expiryTime, googleToken.getExpiryTime()); - } - } - - @Test - public void testCustomFirebaseCredential() throws IOException { - final Date date = new Date(); - FirebaseCredential credential = new FirebaseCredential() { - @Override - public Task getAccessToken() { - return Tasks.forResult(new GoogleOAuthAccessToken("token", date.getTime())); - } - }; - GoogleCredentials googleCredentials = new FirebaseCredentialsAdapter(credential); - AccessToken accessToken = googleCredentials.refreshAccessToken(); - Assert.assertEquals("token", accessToken.getTokenValue()); - Assert.assertEquals(date, accessToken.getExpirationTime()); - } - - private static class TestCredential extends BaseCredential { - - private final AtomicInteger fetchCount = new AtomicInteger(0); - - TestCredential(GoogleCredentials googleCredentials) { - super(googleCredentials); - } - - @Override - public Task getAccessToken() { - fetchCount.incrementAndGet(); - return super.getAccessToken(); - } - - int getFetchCount() { - return fetchCount.get(); - } - } -}