Skip to content

[Auth] Update compat layer credential interception; add webdriver tests #4669

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 10 commits into from
Mar 24, 2021
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
5 changes: 3 additions & 2 deletions packages-exp/auth-compat-exp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
"test:browser:integration": "karma start --single-run --integration",
"test:node": "ts-node -O '{\"module\": \"commonjs\", \"target\": \"es6\"}' scripts/run_node_tests.ts",
"test:node:integration": "ts-node -O '{\"module\": \"commonjs\", \"target\": \"es6\"}' scripts/run_node_tests.ts --integration",
"test:integration": "run-s test:browser:integration test:node:integration"
"test:webdriver": "rollup -c test/integration/webdriver/static/rollup.config.js && ts-node -O '{\"module\": \"commonjs\", \"target\": \"es6\"}' scripts/run_node_tests.ts --webdriver",
"test:integration": "run-s test:browser:integration test:node:integration test:webdriver"
},
"peerDependencies": {
"@firebase/app-compat": "0.x"
Expand All @@ -41,8 +42,8 @@
"license": "Apache-2.0",
"devDependencies": {
"@firebase/app-compat": "0.x",
"rollup": "2.35.1",
"@rollup/plugin-json": "4.1.0",
"rollup": "^2.35.1",
"rollup-plugin-replace": "2.2.0",
"rollup-plugin-typescript2": "0.29.0",
"typescript": "4.2.2"
Expand Down
3 changes: 2 additions & 1 deletion packages-exp/auth-compat-exp/scripts/run_node_tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,14 @@ const nyc = resolve(__dirname, '../../../node_modules/.bin/nyc');
const mocha = resolve(__dirname, '../../../node_modules/.bin/mocha');

process.env.TS_NODE_COMPILER_OPTIONS = '{"module":"commonjs", "target": "es6"}';
process.env.COMPAT_LAYER = 'true';

let testConfig = ['src/**/*.test.ts'];

if (argv.integration) {
testConfig = ['test/integration/flows/**.test.ts'];
} else if (argv.webdriver) {
testConfig = ['test/integration/webdriver/**.test.ts', '--delay'];
testConfig = ['../auth-exp/test/integration/webdriver/*.test.ts', '--delay'];
}

let args = [
Expand Down
11 changes: 9 additions & 2 deletions packages-exp/auth-compat-exp/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import {
convertConfirmationResult,
convertCredential
} from './user_credential';
import { unwrap, Wrapper } from './wrap';
import { ReverseWrapper, unwrap, Wrapper } from './wrap';

const _assert: typeof exp._assert = exp._assert;

Expand All @@ -45,6 +45,7 @@ export class Auth
constructor(readonly app: FirebaseApp, provider: Provider<'auth-exp'>) {
if (provider.isInitialized()) {
this.auth = provider.getImmediate() as exp.AuthImpl;
this.linkUnderlyingAuth();
return;
}

Expand Down Expand Up @@ -89,6 +90,7 @@ export class Auth
}) as exp.AuthImpl;

this.auth._updateErrorMap(exp.debugErrorMap);
this.linkUnderlyingAuth();
}

get emulatorConfig(): compat.EmulatorConfig | null {
Expand Down Expand Up @@ -217,7 +219,9 @@ export class Auth
break;
case Persistence.LOCAL:
// Not using isIndexedDBAvailable() since it only checks if indexedDB is defined.
const isIndexedDBFullySupported = await (exp.indexedDBLocalPersistence as exp.PersistenceInternal)._isAvailable();
const isIndexedDBFullySupported = await exp
._getInstance<exp.PersistenceInternal>(exp.indexedDBLocalPersistence)
._isAvailable();
converted = isIndexedDBFullySupported
? exp.indexedDBLocalPersistence
: exp.browserLocalPersistence;
Expand Down Expand Up @@ -330,6 +334,9 @@ export class Auth
_delete(): Promise<void> {
return this.auth._delete();
}
private linkUnderlyingAuth(): void {
((this.auth as unknown) as ReverseWrapper<Auth>).wrapped = () => this;
}
}

function wrapObservers(
Expand Down
26 changes: 16 additions & 10 deletions packages-exp/auth-compat-exp/src/popup_redirect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,23 +39,17 @@ export class CompatPopupRedirectResolver
) => Promise<exp.UserCredential | null> = exp._getRedirectResult;

async _initialize(auth: exp.AuthImpl): Promise<exp.EventManager> {
if (this.underlyingResolver) {
return this.underlyingResolver._initialize(auth);
}

// We haven't yet determined whether or not we're in Cordova; go ahead
// and determine that state now.
const isCordova = await _isCordova();
this.underlyingResolver = isCordova ? CORDOVA_RESOLVER : BROWSER_RESOLVER;
await this.selectUnderlyingResolver();
return this.assertedUnderlyingResolver._initialize(auth);
}

_openPopup(
async _openPopup(
auth: exp.AuthImpl,
provider: exp.AuthProvider,
authType: exp.AuthEventType,
eventId?: string
): Promise<exp.AuthPopup> {
await this.selectUnderlyingResolver();
return this.assertedUnderlyingResolver._openPopup(
auth,
provider,
Expand All @@ -64,12 +58,13 @@ export class CompatPopupRedirectResolver
);
}

_openRedirect(
async _openRedirect(
auth: exp.AuthImpl,
provider: exp.AuthProvider,
authType: exp.AuthEventType,
eventId?: string
): Promise<void> {
await this.selectUnderlyingResolver();
return this.assertedUnderlyingResolver._openRedirect(
auth,
provider,
Expand Down Expand Up @@ -97,4 +92,15 @@ export class CompatPopupRedirectResolver
_assert(this.underlyingResolver, exp.AuthErrorCode.INTERNAL_ERROR);
return this.underlyingResolver;
}

private async selectUnderlyingResolver(): Promise<void> {
if (this.underlyingResolver) {
return;
}

// We haven't yet determined whether or not we're in Cordova; go ahead
// and determine that state now.
const isCordova = await _isCordova();
this.underlyingResolver = isCordova ? CORDOVA_RESOLVER : BROWSER_RESOLVER;
}
}
131 changes: 105 additions & 26 deletions packages-exp/auth-compat-exp/src/user_credential.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,35 +17,84 @@

import * as exp from '@firebase/auth-exp/internal';
import * as compat from '@firebase/auth-types';
import { FirebaseError } from '@firebase/util';
import { Auth } from './auth';
import { User } from './user';
import { unwrap, wrapped } from './wrap';

function credentialFromResponse(
userCredential: exp.UserCredentialInternal
): exp.AuthCredential | null {
const { providerId, _tokenResponse } = userCredential;
return credentialFromObject(userCredential);
}

function attachExtraErrorFields(auth: exp.Auth, e: FirebaseError): void {
// The response contains all fields from the server which may or may not
// actually match the underlying type
const response = ((e.customData as exp.TaggedWithTokenResponse | undefined)
?._tokenResponse as unknown) as Record<string, string>;
if (e.code === 'auth/multi-factor-auth-required') {
const mfaErr = e as compat.MultiFactorError;
mfaErr.resolver = new MultiFactorResolver(
auth,
exp.getMultiFactorResolver(auth, e as exp.MultiFactorError)
);
} else if (response) {
const credential = credentialFromObject(e);
const credErr = e as compat.AuthError;
if (credential) {
credErr.credential = credential;
credErr.tenantId = response.tenantId || undefined;
credErr.email = response.email || undefined;
credErr.phoneNumber = response.phoneNumber || undefined;
}
}
}

function credentialFromObject(
object: FirebaseError | exp.UserCredential
): exp.AuthCredential | null {
const { _tokenResponse } = (object instanceof FirebaseError
? object.customData
: object) as exp.TaggedWithTokenResponse;
if (!_tokenResponse) {
return null;
}

// Handle phone Auth credential responses, as they have a different format
// from other backend responses (i.e. no providerId).
if ('temporaryProof' in _tokenResponse && 'phoneNumber' in _tokenResponse) {
return exp.PhoneAuthProvider.credentialFromResult(userCredential);
// from other backend responses (i.e. no providerId). This is also only the
// case for user credentials (does not work for errors).
if (!(object instanceof FirebaseError)) {
if ('temporaryProof' in _tokenResponse && 'phoneNumber' in _tokenResponse) {
return exp.PhoneAuthProvider.credentialFromResult(object);
}
}

const providerId = _tokenResponse.providerId;

// Email and password is not supported as there is no situation where the
// server would return the password to the client.
if (!providerId || providerId === exp.ProviderId.PASSWORD) {
return null;
}

let provider: Pick<
typeof exp.OAuthProvider,
'credentialFromResult' | 'credentialFromError'
>;
switch (providerId) {
case exp.ProviderId.GOOGLE:
return exp.GoogleAuthProvider.credentialFromResult(userCredential);
provider = exp.GoogleAuthProvider;
break;
case exp.ProviderId.FACEBOOK:
return exp.FacebookAuthProvider.credentialFromResult(userCredential!);
provider = exp.FacebookAuthProvider;
break;
case exp.ProviderId.GITHUB:
return exp.GithubAuthProvider.credentialFromResult(userCredential!);
provider = exp.GithubAuthProvider;
break;
case exp.ProviderId.TWITTER:
return exp.TwitterAuthProvider.credentialFromResult(userCredential);
provider = exp.TwitterAuthProvider;
break;
default:
const {
oauthIdToken,
Expand All @@ -63,27 +112,30 @@ function credentialFromResponse(
return null;
}
// TODO(avolkovi): uncomment this and get it working with SAML & OIDC
// if (pendingToken) {
// if (providerId.indexOf(compat.constants.SAML_PREFIX) == 0) {
// return new impl.SAMLAuthCredential(providerId, pendingToken);
// } else {
// // OIDC and non-default providers excluding Twitter.
// return new impl.OAuthCredential(
// providerId,
// {
// pendingToken,
// idToken: oauthIdToken,
// accessToken: oauthAccessToken
// },
// providerId);
// }
// }
if (pendingToken) {
if (providerId.startsWith('saml.')) {
return exp.SAMLAuthCredential._create(providerId, pendingToken);
} else {
// OIDC and non-default providers excluding Twitter.
return exp.OAuthCredential._fromParams({
providerId,
signInMethod: providerId,
pendingToken,
idToken: oauthIdToken,
accessToken: oauthAccessToken
});
}
}
return new exp.OAuthProvider(providerId).credential({
idToken: oauthIdToken,
accessToken: oauthAccessToken,
rawNonce: nonce
});
}

return object instanceof FirebaseError
? provider.credentialFromError(object)
: provider.credentialFromResult(object);
}

export async function convertCredential(
Expand All @@ -94,12 +146,12 @@ export async function convertCredential(
try {
credential = await credentialPromise;
} catch (e) {
if (e.code === 'auth/multi-factor-auth-required') {
e.resolver = exp.getMultiFactorResolver(auth, e);
if (e instanceof FirebaseError) {
attachExtraErrorFields(auth, e);
}
throw e;
}
const { operationType, user } = await credential;
const { operationType, user } = credential;

return {
operationType,
Expand All @@ -124,3 +176,30 @@ export async function convertConfirmationResult(
convertCredential(auth, confirmationResultExp.confirm(verificationCode))
};
}

class MultiFactorResolver implements compat.MultiFactorResolver {
readonly auth: Auth;
constructor(
auth: exp.Auth,
private readonly resolver: exp.MultiFactorResolver
) {
this.auth = wrapped(auth);
}

get session(): compat.MultiFactorSession {
return this.resolver.session;
}

get hints(): compat.MultiFactorInfo[] {
return this.resolver.hints;
}

resolveSignIn(
assertion: compat.MultiFactorAssertion
): Promise<compat.UserCredential> {
return convertCredential(
unwrap(this.auth),
this.resolver.resolveSignIn(assertion as exp.MultiFactorAssertion)
);
}
}
10 changes: 10 additions & 0 deletions packages-exp/auth-compat-exp/src/wrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,20 @@
* limitations under the License.
*/

/** Forward direction wrapper from Compat --unwrap-> Exp */
export interface Wrapper<T> {
unwrap(): T;
}

/** Reverse direction wrapper from Exp --wrapped--> Compat */
export interface ReverseWrapper<T> {
wrapped(): T;
}

export function unwrap<T>(object: unknown): T {
return (object as Wrapper<T>).unwrap();
}

export function wrapped<T>(object: unknown): T {
return (object as ReverseWrapper<T>).wrapped();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @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.
*/

export async function anonymousSignIn() {
return compat.auth().signInAnonymously();
}
Loading