Skip to content

Add persistence tests and fix some issues. #4620

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
Mar 13, 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
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ import * as sinonChai from 'sinon-chai';
import { testAuth, testUser, TestAuth } from '../../../test/helpers/mock_auth';
import { UserImpl } from '../user/user_impl';
import { _getInstance } from '../util/instantiator';
import { PersistenceInternal, PersistenceType, StorageEventListener } from './';
import {
PersistenceInternal,
PersistenceType,
PersistenceValue,
StorageEventListener
} from './';
import { inMemoryPersistence } from './in_memory';
import { KeyName, PersistenceUserManager } from './persistence_user_manager';

Expand Down Expand Up @@ -64,19 +69,78 @@ describe('core/persistence/persistence_user_manager', () => {
expect(manager.persistence).to.eq(_getInstance(inMemoryPersistence));
});

it('searches in order for a user', async () => {
it('chooses the first one available', async () => {
const a = makePersistence();
const b = makePersistence();
const c = makePersistence();
const search = [a.persistence, b.persistence, c.persistence];
const auth = await testAuth();
b.stub._get.returns(Promise.resolve(testUser(auth, 'uid').toJSON()));
a.stub._isAvailable.resolves(false);
a.stub._get.onFirstCall().resolves(testUser(auth, 'uid').toJSON());
b.stub._isAvailable.resolves(true);

const out = await PersistenceUserManager.create(auth, search);
expect(a.stub._isAvailable).to.have.been.calledOnce;
expect(b.stub._isAvailable).to.have.been.calledOnce;
expect(c.stub._isAvailable).to.not.have.been.called;

// a should not be chosen since it is not available (despite having a user).
expect(out.persistence).to.eq(b.persistence);
});

it('searches in order for a user', async () => {
const a = makePersistence();
const b = makePersistence();
const c = makePersistence();
const search = [a.persistence, b.persistence, c.persistence];
const auth = await testAuth();
const user = testUser(auth, 'uid');
a.stub._isAvailable.resolves(true);
a.stub._get.resolves(user.toJSON());
b.stub._get.resolves(testUser(auth, 'wrong-uid').toJSON());

const out = await PersistenceUserManager.create(auth, search);
expect(a.stub._get).to.have.been.calledOnce;
expect(b.stub._get).to.have.been.calledOnce;
expect(b.stub._get).not.to.have.been.called;
expect(c.stub._get).not.to.have.been.called;

expect(out.persistence).to.eq(a.persistence);
expect((await out.getCurrentUser())!.uid).to.eq(user.uid);
});

it('migrate found user to the selected persistence and clear others', async () => {
const a = makePersistence();
const b = makePersistence();
const c = makePersistence();
const search = [a.persistence, b.persistence, c.persistence];
const auth = await testAuth();
const user = testUser(auth, 'uid');
a.stub._isAvailable.resolves(true);
b.stub._get.resolves(user.toJSON());
c.stub._get.resolves(testUser(auth, 'wrong-uid').toJSON());

let persistedUserInA: PersistenceValue | null = null;
a.stub._set.callsFake(async (_, value) => {
persistedUserInA = value;
});
a.stub._get.callsFake(async () => persistedUserInA);

const out = await PersistenceUserManager.create(auth, search);
expect(a.stub._set).to.have.been.calledOnceWith(
'firebase:authUser:test-api-key:test-app',
user.toJSON()
);
expect(b.stub._set).to.not.have.been.called;
expect(c.stub._set).to.not.have.been.called;
expect(b.stub._remove).to.have.been.calledOnceWith(
'firebase:authUser:test-api-key:test-app'
);
expect(c.stub._remove).to.have.been.calledOnceWith(
'firebase:authUser:test-api-key:test-app'
);

expect(out.persistence).to.eq(a.persistence);
expect((await out.getCurrentUser())!.uid).to.eq(user.uid);
});

it('uses default user key if none provided', async () => {
Expand All @@ -99,13 +163,17 @@ describe('core/persistence/persistence_user_manager', () => {
);
});

it('returns zeroth persistence if all else fails', async () => {
it('returns in-memory persistence if all else fails', async () => {
const a = makePersistence();
const b = makePersistence();
const c = makePersistence();
const search = [a.persistence, b.persistence, c.persistence];
a.stub._isAvailable.resolves(false);
b.stub._isAvailable.resolves(false);
c.stub._isAvailable.resolves(false);

const out = await PersistenceUserManager.create(auth, search);
expect(out.persistence).to.eq(a.persistence);
expect(out.persistence).to.eq(_getInstance(inMemoryPersistence));
expect(a.stub._get).to.have.been.calledOnce;
expect(b.stub._get).to.have.been.calledOnce;
expect(c.stub._get).to.have.been.called;
Expand All @@ -118,6 +186,7 @@ describe('core/persistence/persistence_user_manager', () => {

beforeEach(async () => {
const { persistence, stub } = makePersistence(PersistenceType.SESSION);
stub._isAvailable.resolves(true);
persistenceStub = stub;
manager = await PersistenceUserManager.create(auth, [persistence]);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,19 +113,52 @@ export class PersistenceUserManager {
);
}

const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);
// Use the first persistence that supports a full read-write roundtrip (or fallback to memory).
let chosenPersistence = _getInstance<PersistenceInternal>(
inMemoryPersistence
);
for (const persistence of persistenceHierarchy) {
if (await persistence._get(key)) {
return new PersistenceUserManager(persistence, auth, userKey);
if (await persistence._isAvailable()) {
chosenPersistence = persistence;
break;
}
}

// Check all the available storage options.
// TODO: Migrate from local storage to indexedDB
// TODO: Clear other forms once one is found
// However, attempt to migrate users stored in other persistences (in the hierarchy order).
let userToMigrate: UserInternal | null = null;
const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);
for (const persistence of persistenceHierarchy) {
// We attempt to call _get without checking _isAvailable since here we don't care if the full
// round-trip (read+write) is supported. We'll take the first one that we can read or give up.
try {
const blob = await persistence._get<PersistedBlob>(key); // throws if unsupported
if (blob) {
const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)
if (persistence !== chosenPersistence) {
userToMigrate = user;
}
break;
}
} catch {}
}

if (userToMigrate) {
// This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
// we'll just let it bubble to surface the error.
await chosenPersistence._set(key, userToMigrate.toJSON());
}

// All else failed, fall back to zeroth persistence
// TODO: Modify this to support non-browser devices
return new PersistenceUserManager(persistenceHierarchy[0], auth, userKey);
// Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
// such as users getting stuck with a previous account after signing out and refreshing the tab.
await Promise.all(
persistenceHierarchy.map(async persistence => {
if (persistence !== chosenPersistence) {
try {
await persistence._remove(key);
} catch {}
}
})
);
return new PersistenceUserManager(chosenPersistence, auth, userKey);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class BrowserLocalPersistence
static type: 'LOCAL' = 'LOCAL';

constructor() {
super(localStorage, PersistenceType.LOCAL);
super(window.localStorage, PersistenceType.LOCAL);
this.boundEventHandler = this.onStorageEvent.bind(this);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class BrowserSessionPersistence
static type: 'SESSION' = 'SESSION';

constructor() {
super(sessionStorage, PersistenceType.SESSION);
super(window.sessionStorage, PersistenceType.SESSION);
}

_addListener(_key: string, _listener: StorageEventListener): void {
Expand Down
147 changes: 147 additions & 0 deletions packages-exp/auth-exp/test/integration/webdriver/persistence.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/**
* @license
* Copyright 2021 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.
*/

// eslint-disable-next-line import/no-extraneous-dependencies
import { UserCredential } from '@firebase/auth-exp';
import { expect } from 'chai';
import { API_KEY } from '../../helpers/integration/settings';
import { AnonFunction, PersistenceFunction } from './util/functions';
import { browserDescribe } from './util/test_runner';

browserDescribe('WebDriver persistence test', driver => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Side note: we should write some tests for the persistence events and cross-tab/cross-browser synchronization (in a different PR) b/182567813

context('default persistence hierarchy (indexedDB > localStorage)', () => {
it('stores user in indexedDB by default', async () => {
const cred: UserCredential = await driver.call(
AnonFunction.SIGN_IN_ANONYMOUSLY
);
const uid = cred.user.uid;

expect(await driver.getUserSnapshot()).to.eql(cred.user);
expect(await driver.call(PersistenceFunction.LOCAL_STORAGE_SNAP)).to.eql(
{}
);
expect(
await driver.call(PersistenceFunction.SESSION_STORAGE_SNAP)
).to.eql({});

const snap = await driver.call(PersistenceFunction.INDEXED_DB_SNAP);
expect(snap)
.to.have.property(`firebase:authUser:${API_KEY}:[DEFAULT]`)
.that.contains({ uid });

// Persistence should survive a refresh:
await driver.webDriver.navigate().refresh();
await driver.injectConfigAndInitAuth();
await driver.waitForAuthInit();
expect(await driver.getUserSnapshot()).to.contain({ uid });
});

it('should work fine if indexedDB is available while localStorage is not', async () => {
await driver.webDriver.navigate().refresh();
// Simulate browsers that do not support localStorage.
await driver.webDriver.executeScript('delete window.localStorage;');
await driver.injectConfigAndInitAuth();
await driver.waitForAuthInit();

const cred: UserCredential = await driver.call(
AnonFunction.SIGN_IN_ANONYMOUSLY
);
const uid = cred.user.uid;

expect(await driver.getUserSnapshot()).to.eql(cred.user);
expect(await driver.call(PersistenceFunction.LOCAL_STORAGE_SNAP)).to.eql(
{}
);
expect(
await driver.call(PersistenceFunction.SESSION_STORAGE_SNAP)
).to.eql({});

const snap = await driver.call(PersistenceFunction.INDEXED_DB_SNAP);
expect(snap)
.to.have.property(`firebase:authUser:${API_KEY}:[DEFAULT]`)
.that.contains({ uid });

// Persistence should survive a refresh:
await driver.webDriver.navigate().refresh();
await driver.injectConfigAndInitAuth();
await driver.waitForAuthInit();
expect(await driver.getUserSnapshot()).to.contain({ uid });
});

it('stores user in localStorage if indexedDB is not available', async () => {
await driver.webDriver.navigate().refresh();
// Simulate browsers that do not support indexedDB.
await driver.webDriver.executeScript('delete window.indexedDB;');
await driver.injectConfigAndInitAuth();
await driver.waitForAuthInit();

const cred: UserCredential = await driver.call(
AnonFunction.SIGN_IN_ANONYMOUSLY
);
const uid = cred.user.uid;

expect(await driver.getUserSnapshot()).to.eql(cred.user);
expect(
await driver.call(PersistenceFunction.SESSION_STORAGE_SNAP)
).to.eql({});

const snap = await driver.call(PersistenceFunction.LOCAL_STORAGE_SNAP);
expect(snap)
.to.have.property(`firebase:authUser:${API_KEY}:[DEFAULT]`)
.that.contains({ uid });

// Persistence should survive a refresh:
await driver.webDriver.navigate().refresh();
await driver.injectConfigAndInitAuth();
await driver.waitForAuthInit();
expect(await driver.getUserSnapshot()).to.contain({ uid });
});

it('fall back to in-memory if neither indexedDB or localStorage is present', async () => {
await driver.webDriver.navigate().refresh();
// Simulate browsers that do not support indexedDB or localStorage.
await driver.webDriver.executeScript(
'delete window.indexedDB; delete window.localStorage;'
);
await driver.injectConfigAndInitAuth();
await driver.waitForAuthInit();

const cred: UserCredential = await driver.call(
AnonFunction.SIGN_IN_ANONYMOUSLY
);

expect(await driver.getUserSnapshot()).to.eql(cred.user);
expect(
await driver.call(PersistenceFunction.SESSION_STORAGE_SNAP)
).to.eql({});
expect(await driver.call(PersistenceFunction.LOCAL_STORAGE_SNAP)).to.eql(
{}
);
expect(await driver.call(PersistenceFunction.INDEXED_DB_SNAP)).to.eql({});

// User will be gone (a.k.a. logged out) after refresh.
await driver.webDriver.navigate().refresh();
await driver.injectConfigAndInitAuth();
await driver.waitForAuthInit();
expect(await driver.getUserSnapshot()).to.equal(null);
});
});

// TODO: Upgrade tests (e.g. migrate user from localStorage to indexedDB).

// TODO: Compatibility tests (e.g. sign in with JS SDK and should stay logged in with TS SDK).
});
11 changes: 2 additions & 9 deletions packages-exp/auth-exp/test/integration/webdriver/static/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { clearPersistence } from './persistence';

export function reset() {
sessionStorage.clear();
localStorage.clear();
const del = indexedDB.deleteDatabase('firebaseLocalStorageDb');

return new Promise(resolve => {
del.addEventListener('success', () => resolve());
del.addEventListener('error', () => resolve());
del.addEventListener('blocked', () => resolve());
});
return clearPersistence();
}

export function authInit() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import * as anonymous from './anonymous';
import * as core from './core';
import * as popup from './popup';
import * as email from './email';
import * as persistence from './persistence';
import { initializeApp } from '@firebase/app-exp';
import { getAuth, useAuthEmulator } from '@firebase/auth-exp';

Expand All @@ -28,6 +29,7 @@ window.anonymous = { ...anonymous };
window.redirect = { ...redirect };
window.popup = { ...popup };
window.email = { ...email };
window.persistence = { ...persistence };

// The config and emulator URL are injected by the test. The test framework
// calls this function after that injection.
Expand Down
Loading