Skip to content

[Auth] Add integration tests (headless & webdriver) for middleware #6161

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
Apr 15, 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
5 changes: 5 additions & 0 deletions packages/auth/test/integration/flows/anonymous.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
getTestInstance,
randomEmail
} from '../../helpers/integration/helpers';
import { generateMiddlewareTests } from './middleware_test_generator';

use(chaiAsPromised);

Expand Down Expand Up @@ -128,4 +129,8 @@ describe('Integration test: anonymous auth', () => {
);
});
});

generateMiddlewareTests(() => auth, () => {
return signInAnonymously(auth);
});
});
5 changes: 5 additions & 0 deletions packages/auth/test/integration/flows/custom.local.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
getTestInstance,
randomEmail
} from '../../helpers/integration/helpers';
import { generateMiddlewareTests } from './middleware_test_generator';

use(chaiAsPromised);

Expand Down Expand Up @@ -225,4 +226,8 @@ describe('Integration test: custom auth', () => {
);
});
});

generateMiddlewareTests(() => auth, () => {
return signInWithCustomToken(auth, customToken);
});
});
5 changes: 5 additions & 0 deletions packages/auth/test/integration/flows/email.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
getTestInstance,
randomEmail
} from '../../helpers/integration/helpers';
import { generateMiddlewareTests } from './middleware_test_generator';

use(chaiAsPromised);

Expand Down Expand Up @@ -168,5 +169,9 @@ describe('Integration test: email/password auth', () => {
);
expect(userA.uid).to.eq(userB.uid);
});

generateMiddlewareTests(() => auth, () => {
return signInWithEmailAndPassword(auth, email, 'password');
});
});
});
8 changes: 8 additions & 0 deletions packages/auth/test/integration/flows/idp.local.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import {
getTestInstance,
randomEmail
} from '../../helpers/integration/helpers';
import { generateMiddlewareTests } from './middleware_test_generator';

use(chaiAsPromised);

Expand Down Expand Up @@ -285,4 +286,11 @@ describe('Integration test: headless IdP', () => {
'github.com'
]);
});

generateMiddlewareTests(() => auth, () => {
return signInWithCredential(
auth,
GoogleAuthProvider.credential(oauthIdToken)
);
});
});
196 changes: 196 additions & 0 deletions packages/auth/test/integration/flows/middleware_test_generator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
/**
* @license
* Copyright 2022 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, use } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import * as sinon from 'sinon';
import sinonChai from 'sinon-chai';

// eslint-disable-next-line import/no-extraneous-dependencies
import {Auth, createUserWithEmailAndPassword, User} from '@firebase/auth';
import { randomEmail } from '../../helpers/integration/helpers';

use(chaiAsPromised);
use(sinonChai);

export function generateMiddlewareTests(authGetter: () => Auth, signIn: () => Promise<unknown>): void {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jamesdaniels I tried to be exhaustive with these tests. Please take a look and see if I'm missing any big use case.

Cross-tab testing is done down in the webdriver/* files.

I'll add the onAbort callback to the tests once that's merged

context('middleware', () => {
let auth: Auth;
let unsubscribes: Array<() => void>;

beforeEach(() => {
auth = authGetter();
unsubscribes = [];
});

afterEach(() => {
for (const u of unsubscribes) {
u();
}
});

/**
* Helper function for adding beforeAuthStateChanged that will
* automatically unsubscribe after every test (since some tests may
* perform cleanup after that would be affected by the middleware)
*/
function beforeAuthStateChanged(callback: (user: User | null) => void | Promise<void>): void {
unsubscribes.push(auth.beforeAuthStateChanged(callback));
}

it('can prevent user sign in', async () => {
beforeAuthStateChanged(() => {
throw new Error('stop sign in');
});

await expect(signIn()).to.be.rejectedWith('auth/login-blocked');
expect(auth.currentUser).to.be.null;
});

it('can prevent user sign in as a promise', async () => {
beforeAuthStateChanged(() => {
return Promise.reject('stop sign in');
});

await expect(signIn()).to.be.rejectedWith('auth/login-blocked');
expect(auth.currentUser).to.be.null;
});

it('keeps previously-logged in user if blocked', async () => {
// Use a random email/password sign in for the base user
const {user: baseUser} = await createUserWithEmailAndPassword(auth, randomEmail(), 'password');

beforeAuthStateChanged(() => {
throw new Error('stop sign in');
});

await expect(signIn()).to.be.rejectedWith('auth/login-blocked');
expect(auth.currentUser).to.eq(baseUser);
});

it('can allow sign in', async () => {
beforeAuthStateChanged(() => {
// Pass
});

await expect(signIn()).not.to.be.rejected;
expect(auth.currentUser).not.to.be.null;
});

it('can allow sign in as a promise', async () => {
beforeAuthStateChanged(() => {
return Promise.resolve();
});

await expect(signIn()).not.to.be.rejected;
expect(auth.currentUser).not.to.be.null;
});

it('overrides previous user if allowed', async () => {
// Use a random email/password sign in for the base user
const {user: baseUser} = await createUserWithEmailAndPassword(auth, randomEmail(), 'password');

beforeAuthStateChanged(() => {
// Pass
});

await expect(signIn()).not.to.be.rejected;
expect(auth.currentUser).not.to.eq(baseUser);
});

it('will reject if one callback fails', async () => {
// Also check that the function is called multiple
// times
const spy = sinon.spy();

beforeAuthStateChanged(spy);
beforeAuthStateChanged(spy);
beforeAuthStateChanged(spy);
beforeAuthStateChanged(() => {
throw new Error('stop sign in');
});

await expect(signIn()).to.be.rejectedWith('auth/login-blocked');
expect(auth.currentUser).to.be.null;
expect(spy).to.have.been.calledThrice;
});

it('keeps previously-logged in user if one rejects', async () => {
// Use a random email/password sign in for the base user
const {user: baseUser} = await createUserWithEmailAndPassword(auth, randomEmail(), 'password');

// Also check that the function is called multiple
// times
const spy = sinon.spy();

beforeAuthStateChanged(spy);
beforeAuthStateChanged(spy);
beforeAuthStateChanged(spy);
beforeAuthStateChanged(() => {
throw new Error('stop sign in');
});

await expect(signIn()).to.be.rejectedWith('auth/login-blocked');
expect(auth.currentUser).to.eq(baseUser);
expect(spy).to.have.been.calledThrice;
});

it('allows sign in with multiple callbacks all pass', async () => {
// Use a random email/password sign in for the base user
const {user: baseUser} = await createUserWithEmailAndPassword(auth, randomEmail(), 'password');

// Also check that the function is called multiple
// times
const spy = sinon.spy();

beforeAuthStateChanged(spy);
beforeAuthStateChanged(spy);
beforeAuthStateChanged(spy);

await expect(signIn()).not.to.be.rejected;
expect(auth.currentUser).not.to.eq(baseUser);
expect(spy).to.have.been.calledThrice;
});

it('does not call subsequent callbacks after rejection', async () => {
const firstSpy = sinon.spy();
const secondSpy = sinon.spy();

beforeAuthStateChanged(firstSpy);
beforeAuthStateChanged(() => {
throw new Error('stop sign in');
});
beforeAuthStateChanged(secondSpy);

await expect(signIn()).to.be.rejectedWith('auth/login-blocked');
expect(firstSpy).to.have.been.calledOnce;
expect(secondSpy).not.to.have.been.called;
});

it('can prevent sign-out', async () => {
await signIn();
const user = auth.currentUser;

beforeAuthStateChanged(() => {
throw new Error('block sign out');
});

await expect(auth.signOut()).to.be.rejectedWith('auth/login-blocked');
expect(auth.currentUser).to.eq(user);
});
});
}
9 changes: 9 additions & 0 deletions packages/auth/test/integration/flows/oob.local.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import {
getTestInstance,
randomEmail
} from '../../helpers/integration/helpers';
import { generateMiddlewareTests } from './middleware_test_generator';

use(chaiAsPromised);

Expand Down Expand Up @@ -267,6 +268,14 @@ describe('Integration test: oob codes', () => {
signInWithEmailLink(auth, email, otherSession.oobLink)
).to.be.rejectedWith(FirebaseError, 'auth/invalid-email');
});

generateMiddlewareTests(() => auth, () => {
return signInWithEmailLink(
auth,
email,
oobSession.oobLink
);
});
});

it('can be used to verify email', async () => {
Expand Down
6 changes: 6 additions & 0 deletions packages/auth/test/integration/flows/phone.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import {
getTestInstance
} from '../../helpers/integration/helpers';
import { getPhoneVerificationCodes } from '../../helpers/integration/emulator_rest_helpers';
import { generateMiddlewareTests } from './middleware_test_generator';

use(chaiAsPromised);

Expand Down Expand Up @@ -306,4 +307,9 @@ describe('Integration test: phone auth', () => {
expect(errorUserCred.user.uid).to.eq(signUpCred.user.uid);
});
});

generateMiddlewareTests(() => auth, async () => {
const cr = await signInWithPhoneNumber(auth, PHONE_A.phoneNumber, verifier);
await cr.confirm(await code(cr, PHONE_A.code));
});
});
39 changes: 38 additions & 1 deletion packages/auth/test/integration/webdriver/persistence.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,22 @@

// eslint-disable-next-line import/no-extraneous-dependencies
import { UserCredential } from '@firebase/auth';
import { expect } from 'chai';
import { expect, use } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import { createAnonAccount } from '../../helpers/integration/emulator_rest_helpers';
import { API_KEY } from '../../helpers/integration/settings';
import { START_FUNCTION } from './util/auth_driver';
import {
AnonFunction,
CoreFunction,
MiddlewareFunction,
PersistenceFunction
} from './util/functions';
import { JsLoadCondition } from './util/js_load_condition';
import { browserDescribe } from './util/test_runner';

use(chaiAsPromised);

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
async function testPersistedUser() {
const account = await createAnonAccount();
Expand Down Expand Up @@ -458,6 +462,39 @@ browserDescribe('WebDriver persistence test', (driver, browser) => {
expect(await driver.getUserSnapshot()).to.contain({ uid: uid2 });
});

it('middleware does not block tab sync', async () => {
if (driver.isCompatLayer()) {
// Compat layer is skipped because it doesn't support middleware
console.warn('Skipping middleware tabs in compat test');
return;
}

// Blocking middleware in main page
await driver.call(MiddlewareFunction.ATTACH_BLOCKING_MIDDLEWARE);

// Check that it blocks basic sign in
await expect(driver.call(
AnonFunction.SIGN_IN_ANONYMOUSLY
)).to.be.rejectedWith('auth/login-blocked');
const userInPopup = await driver.getUserSnapshot();
expect(userInPopup).to.be.null;

// Now sign in in new page
await driver.webDriver.executeScript('window.open(".");');
await driver.selectPopupWindow();
await driver.webDriver.wait(new JsLoadCondition(START_FUNCTION));
await driver.injectConfigAndInitAuth();
await driver.waitForAuthInit();
const cred: UserCredential = await driver.call(
AnonFunction.SIGN_IN_ANONYMOUSLY
);

// And make sure it was updated in main window
await driver.selectMainWindow({ noWait: true });
await driver.pause(700);
expect((await driver.getUserSnapshot()).uid).to.eq(cred.user.uid);
});

it('sync current user across windows with localStorage', async () => {
await driver.webDriver.navigate().refresh();
// Simulate browsers that do not support indexedDB.
Expand Down
Loading