Skip to content

Finish off the emulator hooks #3732

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 4 commits into from
Sep 11, 2020
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
20 changes: 20 additions & 0 deletions packages-exp/auth-exp/src/api/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ import { mockEndpoint } from '../../test/helpers/api/helper';
import { testAuth, TestAuth } from '../../test/helpers/mock_auth';
import * as mockFetch from '../../test/helpers/mock_fetch';
import { AuthErrorCode } from '../core/errors';
import { ConfigInternal } from '../model/auth';
import {
_getFinalTarget,
_performApiRequest,
DEFAULT_API_TIMEOUT_MS,
Endpoint,
Expand Down Expand Up @@ -327,4 +329,22 @@ describe('api/_performApiRequest', () => {
}
});
});

context('_getFinalTarget', () => {
it('works properly with a non-emulated environment', () => {
expect(_getFinalTarget(auth, 'host', '/path', 'query=test')).to.eq(
'mock://host/path?query=test'
);
});

it('works properly with an emulated environment', () => {
(auth.config as ConfigInternal).emulator = {
hostname: 'localhost',
port: 5000
};
expect(_getFinalTarget(auth, 'host', '/path', 'query=test')).to.eq(
'http://localhost:5000/host/path?query=test'
);
});
});
});
6 changes: 3 additions & 3 deletions packages-exp/auth-exp/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
} from '../core/errors';
import { fail } from '../core/util/assert';
import { Delay } from '../core/util/delay';
import { _emulatorUrl } from '../core/util/emulator';
import { FetchProvider } from '../core/util/fetch_provider';
import { Auth, AuthCore } from '../model/auth';
import { IdTokenResponse, TaggedWithTokenResponse } from '../model/id_token';
Expand Down Expand Up @@ -191,14 +192,13 @@ export function _getFinalTarget(
path: string,
query: string
): string {
const { emulator } = auth.config;
const base = `${host}${path}?${query}`;

if (!emulator) {
if (!auth.config.emulator) {
return `${auth.config.apiScheme}://${base}`;
}

return `http://${emulator.hostname}:${emulator.port}/${base}`;
return _emulatorUrl(auth.config, base);
}

function makeNetworkTimeout<T>(appName: string): Promise<T> {
Expand Down
49 changes: 48 additions & 1 deletion packages-exp/auth-exp/src/core/auth/auth_impl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ import * as sinonChai from 'sinon-chai';
import { FirebaseApp } from '@firebase/app-types-exp';
import { FirebaseError } from '@firebase/util';

import { testUser } from '../../../test/helpers/mock_auth';
import { endpointUrl, mockEndpoint } from '../../../test/helpers/api/helper';
import { testAuth, TestAuth, testUser } from '../../../test/helpers/mock_auth';
import * as fetch from '../../../test/helpers/mock_fetch';
import { Endpoint } from '../../api';
import { Auth } from '../../model/auth';
import { User } from '../../model/user';
import { Persistence } from '../persistence';
Expand Down Expand Up @@ -388,3 +391,47 @@ describe('core/auth/auth_impl', () => {
});
});
});

// These tests are separate because they are using a different auth with
// separate setup and config
describe('core/auth/auth_impl useEmulator', () => {
let auth: TestAuth;
let user: User;
let normalEndpoint: fetch.Route;
let emulatorEndpoint: fetch.Route;

beforeEach(async () => {
auth = await testAuth();
user = testUser(_castAuth(auth), 'uid', 'email', true);
fetch.setUp();
normalEndpoint = mockEndpoint(Endpoint.DELETE_ACCOUNT, {});
emulatorEndpoint = fetch.mock(
`http://localhost:2020/${endpointUrl(Endpoint.DELETE_ACCOUNT).replace(
/^.*:\/\//,
''
)}`,
{}
);
});

afterEach(() => {
fetch.tearDown();
});

context('useEmulator', () => {
it('fails if a network request has already been made', async () => {
await user.delete();
expect(() => auth.useEmulator('localhost', 2020)).to.throw(
FirebaseError,
'auth/emulator-config-failed'
);
});

it('updates the endpoint appropriately', async () => {
auth.useEmulator('localhost', 2020);
await user.delete();
expect(normalEndpoint.calls.length).to.eq(0);
expect(emulatorEndpoint.calls.length).to.eq(1);
});
});
});
17 changes: 15 additions & 2 deletions packages-exp/auth-exp/src/core/auth/auth_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
Unsubscribe
} from '@firebase/util';

import { Auth, AuthCore } from '../../model/auth';
import { Auth, AuthCore, ConfigInternal } from '../../model/auth';
import { PopupRedirectResolver } from '../../model/popup_redirect';
import { User, UserParameters } from '../../model/user';
import { AuthErrorCode } from '../errors';
Expand Down Expand Up @@ -82,7 +82,7 @@ export class AuthImplCompat<T extends User> implements Auth, _FirebaseService {

constructor(
public readonly app: FirebaseApp,
public readonly config: externs.Config,
public readonly config: ConfigInternal,
private readonly _userProvider: UserProvider<T>
) {
this.name = app.name;
Expand Down Expand Up @@ -189,6 +189,19 @@ export class AuthImplCompat<T extends User> implements Auth, _FirebaseService {
this.languageCode = _getUserLanguage();
}

useEmulator(hostname: string, port: number): void {
assert(this._canInitEmulator, AuthErrorCode.EMULATOR_CONFIG_FAILED, {
appName: this.name
});

this.config.emulator = {
hostname,
port
};

this.settings.appVerificationDisabledForTesting = true;
}

async _delete(): Promise<void> {
// TODO: Determine what we want to do in this case
}
Expand Down
70 changes: 0 additions & 70 deletions packages-exp/auth-exp/src/core/auth/initialize.test.ts

This file was deleted.

18 changes: 0 additions & 18 deletions packages-exp/auth-exp/src/core/auth/initialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ import { FirebaseApp } from '@firebase/app-types-exp';
import * as externs from '@firebase/auth-types-exp';

import { Dependencies } from '../../model/auth';
import { AuthErrorCode } from '../errors';
import { Persistence } from '../persistence';
import { assert } from '../util/assert';
import { _getInstance } from '../util/instantiator';
import { _castAuth, AuthImpl } from './auth_impl';

Expand All @@ -36,22 +34,6 @@ export function initializeAuth(
return auth;
}

export function useEmulator(
authExtern: externs.Auth,
hostname: string,
port: number
): void {
const auth = _castAuth(authExtern);
assert(auth._canInitEmulator, AuthErrorCode.EMULATOR_CONFIG_FAILED, {
appName: auth.name
});

auth.config.emulator = {
hostname,
port
};
}

export function _initializeAuthInstance(
auth: AuthImpl,
deps?: Dependencies
Expand Down
46 changes: 46 additions & 0 deletions packages-exp/auth-exp/src/core/util/emulator.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* @license
* Copyright 2020 Google LLC
*
* 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.
*/

import { expect } from 'chai';

import { ConfigInternal } from '../../model/auth';
import { _emulatorUrl } from './emulator';

describe('core/util/emulator', () => {
const config: ConfigInternal = {
emulator: {
hostname: 'localhost',
port: 4000
}
} as ConfigInternal;

it('builds the proper URL with no path', () => {
expect(_emulatorUrl(config)).to.eq('http://localhost:4000');
});

it('builds the proper URL with a path', () => {
expect(_emulatorUrl(config, '/test/path')).to.eq(
'http://localhost:4000/test/path'
);
});

it('builds the proper URL with a path missing separator', () => {
expect(_emulatorUrl(config, 'test/path')).to.eq(
'http://localhost:4000/test/path'
);
});
});
32 changes: 32 additions & 0 deletions packages-exp/auth-exp/src/core/util/emulator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* @license
* Copyright 2020 Google LLC
*
* 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.
*/

import { ConfigInternal } from '../../model/auth';
import { debugAssert } from './assert';

export function _emulatorUrl(config: ConfigInternal, path?: string): string {
debugAssert(config.emulator, 'Emulator should always be set here');
const { hostname, port } = config.emulator;

const base = `http://${hostname}:${port}`;
if (!path) {
return base;
}

const sep = path.startsWith('/') ? '' : '/';
return `${base}${sep}${path}`;
}
5 changes: 5 additions & 0 deletions packages-exp/auth-exp/src/core/util/validate_origin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ const IP_ADDRESS_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
const HTTP_REGEX = /^https?/;

export async function _validateOrigin(auth: Auth): Promise<void> {
// Skip origin validation if we are in an emulated environment
if (auth.config.emulator) {
return;
}

const { authorizedDomains } = await _getProjectConfig(auth);

for (const domain of authorizedDomains) {
Expand Down
2 changes: 1 addition & 1 deletion packages-exp/auth-exp/src/model/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export type AppName = string;
export type ApiKey = string;
export type AuthDomain = string;

interface ConfigInternal extends externs.Config {
export interface ConfigInternal extends externs.Config {
emulator?: {
hostname: string;
port: number;
Expand Down
11 changes: 9 additions & 2 deletions packages-exp/auth-exp/src/platform_browser/iframe/iframe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,15 @@ import { querystring } from '@firebase/util';
import { AUTH_ERROR_FACTORY, AuthErrorCode } from '../../core/errors';
import { assert } from '../../core/util/assert';
import { Delay } from '../../core/util/delay';
import { _emulatorUrl } from '../../core/util/emulator';
import { AuthCore } from '../../model/auth';
import { _window } from '../auth_window';
import * as gapiLoader from './gapi';

const PING_TIMEOUT = new Delay(5000, 15000);
const IFRAME_PATH = '__/auth/iframe';
const EMULATED_IFRAME_PATH = 'emulator/auth/iframe';

const IFRAME_ATTRIBUTES = {
style: {
position: 'absolute',
Expand All @@ -36,10 +40,13 @@ const IFRAME_ATTRIBUTES = {
};

function getIframeUrl(auth: AuthCore): string {
const url = `https://${auth.config.authDomain!}/__/auth/iframe`;
const config = auth.config;
const url = config.emulator
? _emulatorUrl(config, EMULATED_IFRAME_PATH)
: `https://${auth.config.authDomain!}/${IFRAME_PATH}`;

const params = {
apiKey: auth.config.apiKey,
apiKey: config.apiKey,
appName: auth.name,
v: SDK_VERSION
};
Expand Down
Loading