Skip to content

fix(auth): Set emulator credentials when using the Auth emulator #734

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import com.google.api.core.ApiFutures;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.firestore.FirestoreOptions;
import com.google.firebase.auth.internal.Utils;
import com.google.firebase.internal.EmulatorCredentials;
import com.google.firebase.internal.FirebaseService;
import com.google.firebase.internal.NonNull;

Expand All @@ -41,6 +43,9 @@ public final class ImplFirebaseTrampolines {
private ImplFirebaseTrampolines() {}

public static GoogleCredentials getCredentials(@NonNull FirebaseApp app) {
if (Utils.isEmulatorMode()) {
return new EmulatorCredentials();
}
return app.getOptions().getCredentials();
}

Expand Down
23 changes: 1 addition & 22 deletions src/main/java/com/google/firebase/database/FirebaseDatabase.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import com.google.firebase.database.utilities.ParsedUrl;
import com.google.firebase.database.utilities.Utilities;
import com.google.firebase.database.utilities.Validation;
import com.google.firebase.internal.EmulatorCredentials;
import com.google.firebase.internal.FirebaseService;

import com.google.firebase.internal.SdkUtils;
Expand Down Expand Up @@ -406,26 +407,4 @@ public void destroy() {
instance.destroy();
}
}

private static class EmulatorCredentials extends GoogleCredentials {

EmulatorCredentials() {
super(newToken());
}

private static AccessToken newToken() {
return new AccessToken("owner",
new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)));
}

@Override
public AccessToken refreshAccessToken() {
return newToken();
}

@Override
public Map<String, List<String>> getRequestMetadata() throws IOException {
return ImmutableMap.of();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Copyright 2022 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.internal;

import com.google.auth.oauth2.AccessToken;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.common.collect.ImmutableMap;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* A Mock Credentials implementation that can be used with the Emulator Suite
*/
public final class EmulatorCredentials extends GoogleCredentials {

public EmulatorCredentials() {
super(newToken());
}

private static AccessToken newToken() {
return new AccessToken("owner",
new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)));
}

@Override
public AccessToken refreshAccessToken() {
return newToken();
}

@Override
public Map<String, List<String>> getRequestMetadata() throws IOException {
return ImmutableMap.of();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,13 @@ public class FirebaseUserManagerTest {

private static final String TEST_TOKEN = "token";

private static final String TEST_EMULATOR_TOKEN = "owner";

private static final GoogleCredentials credentials = new MockGoogleCredentials(TEST_TOKEN);

private static final GoogleCredentials emulator_credentials =
new MockGoogleCredentials(TEST_EMULATOR_TOKEN);

private static final ActionCodeSettings ACTION_CODE_SETTINGS = ActionCodeSettings.builder()
.setUrl("https://example.dynamic.link")
.setHandleCodeInApp(true)
Expand Down Expand Up @@ -2916,7 +2921,7 @@ private static void initializeAppWithResponses(String... responses) {
}
MockHttpTransport transport = new MultiRequestMockHttpTransport(mocks);
FirebaseApp.initializeApp(FirebaseOptions.builder()
.setCredentials(credentials)
.setCredentials(isEmulatorMode() ? emulator_credentials : credentials)
.setHttpTransport(transport)
.setProjectId("test-project-id")
.build());
Expand Down Expand Up @@ -3014,7 +3019,7 @@ private static void checkSamlProviderConfig(SamlProviderConfig config, String pr

private static void checkRequestHeaders(TestResponseInterceptor interceptor) {
HttpHeaders headers = interceptor.getResponse().getRequest().getHeaders();
String auth = "Bearer " + TEST_TOKEN;
String auth = "Bearer " + (isEmulatorMode() ? TEST_EMULATOR_TOKEN : TEST_TOKEN);
assertEquals(auth, headers.getFirstHeaderStringValue("Authorization"));

String clientVersion = "Java/Admin/" + SdkUtils.getVersion();
Expand All @@ -3027,6 +3032,12 @@ private static void checkUrl(TestResponseInterceptor interceptor, String method,
assertEquals(url, request.getUrl().toString().split("\\?")[0]);
}

private static boolean isEmulatorMode() {
return !Strings.isNullOrEmpty(
FirebaseProcessEnvironment.getenv("FIREBASE_AUTH_EMULATOR_HOST")
);
}

private interface UserManagerOp {
void call(FirebaseAuth auth) throws Exception;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import com.google.api.client.testing.http.MockHttpTransport;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.firebase.ErrorCode;
Expand Down Expand Up @@ -63,8 +64,13 @@ public class FirebaseTenantClientTest {

private static final String TEST_TOKEN = "token";

private static final String TEST_EMULATOR_TOKEN = "owner";

private static final GoogleCredentials credentials = new MockGoogleCredentials(TEST_TOKEN);

private static final GoogleCredentials emulator_credentials =
new MockGoogleCredentials(TEST_EMULATOR_TOKEN);

private static final String PROJECT_BASE_URL =
"https://identitytoolkit.googleapis.com/v2/projects/test-project-id";

Expand Down Expand Up @@ -342,7 +348,7 @@ private static void checkTenant(Tenant tenant, String tenantId) {

private static void checkRequestHeaders(TestResponseInterceptor interceptor) {
HttpHeaders headers = interceptor.getResponse().getRequest().getHeaders();
String auth = "Bearer " + TEST_TOKEN;
String auth = "Bearer " + (isEmulatorMode() ? TEST_EMULATOR_TOKEN : TEST_TOKEN);
assertEquals(auth, headers.getFirstHeaderStringValue("Authorization"));

String clientVersion = "Java/Admin/" + SdkUtils.getVersion();
Expand All @@ -362,7 +368,7 @@ private static TestResponseInterceptor initializeAppForTenantManagement(String..
}
MockHttpTransport transport = new MultiRequestMockHttpTransport(mocks);
FirebaseApp.initializeApp(FirebaseOptions.builder()
.setCredentials(credentials)
.setCredentials(isEmulatorMode() ? emulator_credentials : credentials)
.setHttpTransport(transport)
.setProjectId("test-project-id")
.build());
Expand Down Expand Up @@ -408,4 +414,10 @@ private static GenericJson parseRequestContent(TestResponseInterceptor intercept
interceptor.getResponse().getRequest().getContent().writeTo(out);
return JSON_FACTORY.fromString(new String(out.toByteArray()), GenericJson.class);
}

private static boolean isEmulatorMode() {
return !Strings.isNullOrEmpty(
FirebaseProcessEnvironment.getenv("FIREBASE_AUTH_EMULATOR_HOST")
);
}
}