Bug 1824112 - switch to addLoginAsync in tests r=credential-management-reviewers,sync-reviewers,sgalich,markh

Differential Revision: https://phabricator.services.mozilla.com/D175704
This commit is contained in:
Johannes J. Schmidt 2023-04-24 07:52:22 +00:00
parent 0c6a71c247
commit 3211c834ae
86 changed files with 724 additions and 934 deletions

View File

@ -21,7 +21,7 @@ add_task(async function test_showLoginItemErrors() {
"user2",
"pass2"
);
LOGIN_TO_UPDATE = Services.logins.addLogin(LOGIN_TO_UPDATE);
LOGIN_TO_UPDATE = await Services.logins.addLoginAsync(LOGIN_TO_UPDATE);
EXPECTED_ERROR_MESSAGE = "This login already exists.";
const LOGIN_UPDATES = {
origin: "https://example.com",

View File

@ -6,13 +6,13 @@ add_setup(async function() {
"passwordmgr-storage-changed",
(_, data) => data == "addLogin"
);
TEST_LOGIN1 = Services.logins.addLogin(TEST_LOGIN1);
TEST_LOGIN1 = await Services.logins.addLoginAsync(TEST_LOGIN1);
await storageChangedPromised;
storageChangedPromised = TestUtils.topicObserved(
"passwordmgr-storage-changed",
(_, data) => data == "addLogin"
);
TEST_LOGIN2 = Services.logins.addLogin(TEST_LOGIN2);
TEST_LOGIN2 = await Services.logins.addLoginAsync(TEST_LOGIN2);
await storageChangedPromised;
let tabOpenedPromise = BrowserTestUtils.waitForNewTab(
gBrowser,

View File

@ -54,17 +54,12 @@ let TEST_LOGIN3 = new nsLoginInfo(
TEST_LOGIN3.QueryInterface(Ci.nsILoginMetaInfo).timePasswordChanged = 123456;
async function addLogin(login) {
let storageChangedPromised = TestUtils.topicObserved(
"passwordmgr-storage-changed",
(_, data) => data == "addLogin"
);
login = Services.logins.addLogin(login);
await storageChangedPromised;
const result = await Services.logins.addLoginAsync(login);
registerCleanupFunction(() => {
let matchData = Cc["@mozilla.org/hash-property-bag;1"].createInstance(
Ci.nsIWritablePropertyBag2
);
matchData.setPropertyAsAUTF8String("guid", login.guid);
matchData.setPropertyAsAUTF8String("guid", result.guid);
let logins = Services.logins.searchLogins(matchData);
if (!logins.length) {
@ -76,7 +71,7 @@ async function addLogin(login) {
// matches the login that it will be removing.
Services.logins.removeLogin(logins[0]);
});
return login;
return result;
}
let EXPECTED_BREACH = null;

View File

@ -110,7 +110,7 @@ const LOGIN_WITH_NON_STANDARD_URI = LoginTestUtils.testData.formLogin({
});
add_task(async function test_notBreachedLogin() {
Services.logins.addLogin(NOT_BREACHED_LOGIN);
await Services.logins.addLoginAsync(NOT_BREACHED_LOGIN);
const breachesByLoginGUID = await LoginBreaches.getPotentialBreachesByLoginGUID(
[NOT_BREACHED_LOGIN],
TEST_BREACHES
@ -123,7 +123,7 @@ add_task(async function test_notBreachedLogin() {
});
add_task(async function test_breachedLogin() {
Services.logins.addLogin(BREACHED_LOGIN);
await Services.logins.addLoginAsync(BREACHED_LOGIN);
const breachesByLoginGUID = await LoginBreaches.getPotentialBreachesByLoginGUID(
[NOT_BREACHED_LOGIN, BREACHED_LOGIN],
TEST_BREACHES
@ -141,7 +141,7 @@ add_task(async function test_breachedLogin() {
});
add_task(async function test_breachedLoginAfterCrashingUriLogin() {
Services.logins.addLogin(CRASHING_URI_LOGIN);
await Services.logins.addLoginAsync(CRASHING_URI_LOGIN);
const breachesByLoginGUID = await LoginBreaches.getPotentialBreachesByLoginGUID(
[CRASHING_URI_LOGIN, BREACHED_LOGIN],
@ -160,7 +160,7 @@ add_task(async function test_breachedLoginAfterCrashingUriLogin() {
});
add_task(async function test_notBreachedSubdomain() {
Services.logins.addLogin(NOT_BREACHED_SUBDOMAIN_LOGIN);
await Services.logins.addLoginAsync(NOT_BREACHED_SUBDOMAIN_LOGIN);
const breachesByLoginGUID = await LoginBreaches.getPotentialBreachesByLoginGUID(
[NOT_BREACHED_LOGIN, NOT_BREACHED_SUBDOMAIN_LOGIN],
@ -174,7 +174,7 @@ add_task(async function test_notBreachedSubdomain() {
});
add_task(async function test_breachedSubdomain() {
Services.logins.addLogin(BREACHED_SUBDOMAIN_LOGIN);
await Services.logins.addLoginAsync(BREACHED_SUBDOMAIN_LOGIN);
const breachesByLoginGUID = await LoginBreaches.getPotentialBreachesByLoginGUID(
[NOT_BREACHED_SUBDOMAIN_LOGIN, BREACHED_SUBDOMAIN_LOGIN],
@ -188,7 +188,9 @@ add_task(async function test_breachedSubdomain() {
});
add_task(async function test_breachedSiteWithoutPasswords() {
Services.logins.addLogin(LOGIN_FOR_BREACHED_SITE_WITHOUT_PASSWORDS);
await Services.logins.addLoginAsync(
LOGIN_FOR_BREACHED_SITE_WITHOUT_PASSWORDS
);
const breachesByLoginGUID = await LoginBreaches.getPotentialBreachesByLoginGUID(
[LOGIN_FOR_BREACHED_SITE_WITHOUT_PASSWORDS],
@ -252,7 +254,7 @@ add_task(async function test_newBreachAfterDismissal() {
});
add_task(async function test_ExceptionsThrownByNonStandardURIsAreCaught() {
Services.logins.addLogin(LOGIN_WITH_NON_STANDARD_URI);
await Services.logins.addLoginAsync(LOGIN_WITH_NON_STANDARD_URI);
const breachesByLoginGUID = await LoginBreaches.getPotentialBreachesByLoginGUID(
[LOGIN_WITH_NON_STANDARD_URI, BREACHED_LOGIN],

View File

@ -10,7 +10,7 @@ const NEW_HOST = "http://mozilla.com";
const FXA_HOST = "chrome://FirefoxAccounts";
function checkLoginExists(host, shouldExist) {
let logins = Services.logins.findLogins(host, "", null);
const logins = Services.logins.findLogins(host, "", null);
equal(
logins.length,
shouldExist ? 1 : 0,
@ -18,7 +18,7 @@ function checkLoginExists(host, shouldExist) {
);
}
function addLogin(host, timestamp) {
async function addLogin(host, timestamp) {
checkLoginExists(host, false);
let login = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(
Ci.nsILoginInfo
@ -26,15 +26,15 @@ function addLogin(host, timestamp) {
login.init(host, "", null, LOGIN_USERNAME, LOGIN_PASSWORD);
login.QueryInterface(Ci.nsILoginMetaInfo);
login.timePasswordChanged = timestamp;
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
checkLoginExists(host, true);
}
async function setupPasswords() {
Services.logins.removeAllUserFacingLogins();
addLogin(FXA_HOST, REFERENCE_DATE);
addLogin(NEW_HOST, REFERENCE_DATE);
addLogin(OLD_HOST, REFERENCE_DATE - 10000);
await addLogin(FXA_HOST, REFERENCE_DATE);
await addLogin(NEW_HOST, REFERENCE_DATE);
await addLogin(OLD_HOST, REFERENCE_DATE - 10000);
}
add_task(async function testPasswords() {
@ -49,7 +49,7 @@ add_task(async function testPasswords() {
});
}
let extension = ExtensionTestUtils.loadExtension({
const extension = ExtensionTestUtils.loadExtension({
background,
manifest: {
permissions: ["browsingData"],

View File

@ -40,18 +40,20 @@ class TestFirefoxRefresh(MarionetteTestCase):
_expectedURLs = ["about:robots", "about:mozilla"]
def savePassword(self):
self.runCode(
self.runAsyncCode(
"""
let [username, password, resolve] = arguments;
let myLogin = new global.LoginInfo(
"test.marionette.mozilla.com",
"http://test.marionette.mozilla.com/some/form/",
null,
arguments[0],
arguments[1],
username,
password,
"username",
"password"
);
Services.logins.addLogin(myLogin)
Services.logins.addLoginAsync(myLogin)
.then(() => resolve(false), resolve);
""",
script_args=(self._username, self._password),
)

View File

@ -104,12 +104,12 @@ var loginCrypto;
var dbConn;
async function promiseSetPassword(login) {
let encryptedString = await loginCrypto.encryptData(
const encryptedString = await loginCrypto.encryptData(
login.password,
login.version
);
info(`promiseSetPassword: ${encryptedString}`);
let passwordValue = new Uint8Array(
const passwordValue = new Uint8Array(
loginCrypto.stringToArray(encryptedString)
);
return dbConn.execute(
@ -177,7 +177,7 @@ function checkLoginsAreEqual(passwordManagerLogin, chromeLogin, id) {
}
function generateDifferentLogin(login) {
let newLogin = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(
const newLogin = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(
Ci.nsILoginInfo
);
@ -206,13 +206,13 @@ add_task(async function setup() {
// would block the test from finishing if Chrome has already created a matching
// Keychain entry. This allows us to still exercise the keychain lookup code.
// The mock encryption passphrase is used when the Keychain item isn't found.
let mockMacOSKeychain = {
const mockMacOSKeychain = {
passphrase: "bW96aWxsYWZpcmVmb3g=",
serviceName: "TESTING Chrome Safe Storage",
accountName: "TESTING Chrome",
};
if (AppConstants.platform == "macosx") {
let { ChromeMacOSLoginCrypto } = ChromeUtils.importESModule(
const { ChromeMacOSLoginCrypto } = ChromeUtils.importESModule(
"resource:///modules/ChromeMacOSLoginCrypto.sys.mjs"
);
loginCrypto = new ChromeMacOSLoginCrypto(
@ -230,7 +230,7 @@ add_task(async function setup() {
"Login Data",
];
} else if (AppConstants.platform == "win") {
let { ChromeWindowsLoginCrypto } = ChromeUtils.importESModule(
const { ChromeWindowsLoginCrypto } = ChromeUtils.importESModule(
"resource:///modules/ChromeWindowsLoginCrypto.sys.mjs"
);
loginCrypto = new ChromeWindowsLoginCrypto("Chrome");
@ -246,18 +246,18 @@ add_task(async function setup() {
} else {
throw new Error("Not implemented");
}
let dirSvcFile = do_get_file(dirSvcPath);
const dirSvcFile = do_get_file(dirSvcPath);
registerFakePath(pathId, dirSvcFile);
info(PathUtils.join(dirSvcFile.path, ...profilePathSegments));
let loginDataFilePath = PathUtils.join(
const loginDataFilePath = PathUtils.join(
dirSvcFile.path,
...profilePathSegments
);
dbConn = await Sqlite.openConnection({ path: loginDataFilePath });
if (AppConstants.platform == "macosx") {
let migrator = await MigrationUtils.getMigrator("chrome");
const migrator = await MigrationUtils.getMigrator("chrome");
Object.assign(migrator, {
_keychainServiceName: mockMacOSKeychain.serviceName,
_keychainAccountName: mockMacOSKeychain.accountName,
@ -275,11 +275,11 @@ add_task(async function setup() {
});
add_task(async function test_importIntoEmptyDB() {
for (let login of TEST_LOGINS) {
for (const login of TEST_LOGINS) {
await promiseSetPassword(login);
}
let migrator = await MigrationUtils.getMigrator("chrome");
const migrator = await MigrationUtils.getMigrator("chrome");
Assert.ok(
await migrator.isSourceAvailable(),
"Sanity check the source exists"
@ -315,7 +315,7 @@ add_task(async function test_importIntoEmptyDB() {
// Test that existing logins for the same primary key don't get overwritten
add_task(async function test_importExistingLogins() {
let migrator = await MigrationUtils.getMigrator("chrome");
const migrator = await MigrationUtils.getMigrator("chrome");
Assert.ok(
await migrator.isSourceAvailable(),
"Sanity check the source exists"
@ -329,7 +329,7 @@ add_task(async function test_importExistingLogins() {
"There are no logins after removing all of them"
);
let newLogins = [];
const newLogins = [];
// Create 3 new logins that are different but where the key properties are still the same.
for (let i = 0; i < 3; i++) {

View File

@ -12,11 +12,11 @@ const { AboutProtectionsParent } = ChromeUtils.importESModule(
const ABOUT_LOGINS_URL = "about:logins";
add_task(async function testNoLoginsLockwiseCardUI() {
let tab = await BrowserTestUtils.openNewForegroundTab({
const tab = await BrowserTestUtils.openNewForegroundTab({
url: "about:protections",
gBrowser,
});
let aboutLoginsPromise = BrowserTestUtils.waitForNewTab(
const aboutLoginsPromise = BrowserTestUtils.waitForNewTab(
gBrowser,
ABOUT_LOGINS_URL
);
@ -76,18 +76,18 @@ add_task(async function testNoLoginsLockwiseCardUI() {
);
savePasswordsButton.click();
});
let loginsTab = await aboutLoginsPromise;
const loginsTab = await aboutLoginsPromise;
info("about:logins was successfully opened in a new tab");
gBrowser.removeTab(loginsTab);
gBrowser.removeTab(tab);
});
add_task(async function testLockwiseCardUIWithLogins() {
let tab = await BrowserTestUtils.openNewForegroundTab({
const tab = await BrowserTestUtils.openNewForegroundTab({
url: "about:protections",
gBrowser,
});
let aboutLoginsPromise = BrowserTestUtils.waitForNewTab(
const aboutLoginsPromise = BrowserTestUtils.waitForNewTab(
gBrowser,
ABOUT_LOGINS_URL
);
@ -95,7 +95,7 @@ add_task(async function testLockwiseCardUIWithLogins() {
info(
"Add a login and check that lockwise card content for a logged in user is displayed correctly"
);
Services.logins.addLogin(TEST_LOGIN1);
await Services.logins.addLoginAsync(TEST_LOGIN1);
await BrowserTestUtils.reloadTab(tab);
await SpecialPowers.spawn(tab.linkedBrowser, [], async function() {
@ -172,14 +172,14 @@ add_task(async function testLockwiseCardUIWithLogins() {
);
managePasswordsButton.click();
});
let loginsTab = await aboutLoginsPromise;
const loginsTab = await aboutLoginsPromise;
info("about:logins was successfully opened in a new tab");
gBrowser.removeTab(loginsTab);
info(
"Add another login and check that the scanned text about stored logins is updated after reload."
);
Services.logins.addLogin(TEST_LOGIN2);
await Services.logins.addLoginAsync(TEST_LOGIN2);
await BrowserTestUtils.reloadTab(tab);
await SpecialPowers.spawn(tab.linkedBrowser, [], async function() {
@ -204,11 +204,11 @@ add_task(async function testLockwiseCardUIWithBreachedLogins() {
info(
"Add a breached login and test that the lockwise scanned text is displayed correctly"
);
let tab = await BrowserTestUtils.openNewForegroundTab({
const tab = await BrowserTestUtils.openNewForegroundTab({
url: "about:protections",
gBrowser,
});
Services.logins.addLogin(TEST_LOGIN1);
await Services.logins.addLoginAsync(TEST_LOGIN1);
info("Mock monitor data with a breached login to test the Lockwise UI");
AboutProtectionsParent.setTestOverride(
@ -261,7 +261,7 @@ add_task(async function testLockwiseCardUIWithBreachedLogins() {
});
add_task(async function testLockwiseCardPref() {
let tab = await BrowserTestUtils.openNewForegroundTab({
const tab = await BrowserTestUtils.openNewForegroundTab({
url: "about:protections",
gBrowser,
});

View File

@ -18,14 +18,14 @@ const mockMonitorData = {
};
add_task(async function() {
let tab = await BrowserTestUtils.openNewForegroundTab({
const tab = await BrowserTestUtils.openNewForegroundTab({
url: "about:protections",
gBrowser,
});
await BrowserTestUtils.reloadTab(tab);
let monitorCardEnabled = Services.prefs.getBoolPref(
const monitorCardEnabled = Services.prefs.getBoolPref(
"browser.contentblocking.report.monitor.enabled"
);
@ -39,7 +39,7 @@ add_task(async function() {
info(
"Check that the correct content is displayed for users with monitor data."
);
Services.logins.addLogin(TEST_LOGIN1);
await Services.logins.addLoginAsync(TEST_LOGIN1);
AboutProtectionsParent.setTestOverride(mockGetMonitorData(mockMonitorData));
await BrowserTestUtils.reloadTab(tab);

View File

@ -207,7 +207,7 @@ add_task(async function checkTelemetryClickEvents() {
});
// Add user logins.
Services.logins.addLogin(TEST_LOGIN1);
await Services.logins.addLoginAsync(TEST_LOGIN1);
await BrowserTestUtils.reloadTab(tab);
await SpecialPowers.spawn(tab.linkedBrowser, [], async function() {
const managePasswordsButton = await ContentTaskUtils.waitForCondition(

View File

@ -190,7 +190,7 @@ const heuristics = [
Ci.nsILoginInfo,
"init"
);
Services.logins.addLogin(
await Services.logins.addLoginAsync(
new LoginInfo(COM_ORIGIN, "", null, "username", "password", "", "")
);

View File

@ -305,7 +305,7 @@ add_task(async function test_uidMigration() {
"", // aUsernameField
""
); // aPasswordField
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
// ensure we read it.
let storage = new LoginManagerStorage();

View File

@ -143,7 +143,7 @@ add_task(async function test_passwords_change_during_sync() {
"",
""
);
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
await engine._tracker.asyncObserver.promiseObserversComplete();
}
};

View File

@ -45,7 +45,7 @@ add_task(async function test_ignored_fields() {
enableValidationPrefs();
let login = Services.logins.addLogin(
let login = await Services.logins.addLoginAsync(
new LoginInfo(
"https://example.com",
"",
@ -97,7 +97,7 @@ add_task(async function test_ignored_sync_credentials() {
engine._tracker.start();
try {
let login = Services.logins.addLogin(
let login = await Services.logins.addLoginAsync(
new LoginInfo(
FXA_PWDMGR_HOST,
null,
@ -146,7 +146,7 @@ add_task(async function test_password_engine() {
"",
""
);
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
let logins = Services.logins.findLogins("https://example.com", "", "");
equal(logins.length, 1, "Should find new login in login manager");
@ -181,7 +181,7 @@ add_task(async function test_password_engine() {
"",
""
);
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
let props = new PropertyBag();
let localPasswordChangeTime = Date.now() - 1 * 60 * 60 * 24 * 1000;

View File

@ -39,7 +39,7 @@ add_task(async function test_tracking() {
};
recordNum++;
let login = store._nsLoginInfoFromRecord(record);
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
await tracker.asyncObserver.promiseObserversComplete();
}
@ -126,7 +126,7 @@ add_task(async function test_removeAllLogins() {
};
recordNum++;
let login = store._nsLoginInfoFromRecord(record);
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
await tracker.asyncObserver.promiseObserversComplete();
}
try {

View File

@ -20,7 +20,7 @@ add_task(async function test_principal_downloads() {
usernameField: "field_username",
passwordField: "field_password",
});
Services.logins.addLogin(loginInfo);
await Services.logins.addLoginAsync(loginInfo);
Assert.equal(countLogins(URL), 1);
@ -57,7 +57,7 @@ add_task(async function test_all() {
usernameField: "field_username",
passwordField: "field_password",
});
Services.logins.addLogin(loginInfo);
await Services.logins.addLoginAsync(loginInfo);
Assert.equal(countLogins(URL), 1);

View File

@ -107,7 +107,7 @@ function check_disabled_host(aHost, aIsDisabled) {
* @param aHost
* The host to add the login for.
*/
function add_login(aHost) {
async function add_login(aHost) {
check_login_exists(aHost, false);
let login = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(
Ci.nsILoginInfo
@ -121,7 +121,7 @@ function add_login(aHost) {
LOGIN_USERNAME_FIELD,
LOGIN_PASSWORD_FIELD
);
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
check_login_exists(aHost, true);
}
@ -312,21 +312,21 @@ async function test_login_manager_disabled_hosts_not_cleared_with_uri_contains_d
async function test_login_manager_logins_cleared_with_direct_match() {
const TEST_HOST = "http://mozilla.org";
add_login(TEST_HOST);
await add_login(TEST_HOST);
await ForgetAboutSite.removeDataFromDomain("mozilla.org");
check_login_exists(TEST_HOST, true);
}
async function test_login_manager_logins_cleared_with_subdomain() {
const TEST_HOST = "http://www.mozilla.org";
add_login(TEST_HOST);
await add_login(TEST_HOST);
await ForgetAboutSite.removeDataFromDomain("mozilla.org");
check_login_exists(TEST_HOST, true);
}
async function test_login_manager_logins_not_cleared_with_uri_contains_domain() {
const TEST_HOST = "http://ilovemozilla.org";
add_login(TEST_HOST);
await add_login(TEST_HOST);
await ForgetAboutSite.removeDataFromDomain("mozilla.org");
check_login_exists(TEST_HOST, true);

View File

@ -64,13 +64,7 @@ export const LoginTestUtils = {
username,
password,
});
let storageChangedPromised = TestUtils.topicObserved(
"passwordmgr-storage-changed",
(_, data) => data == "addLogin"
);
Services.logins.addLogin(login);
let [savedLogin] = await storageChangedPromised;
return savedLogin;
return Services.logins.addLoginAsync(login);
},
async modifyLogin(oldLogin, newLogin) {

View File

@ -7,14 +7,14 @@ add_setup(async function() {
username: "username1",
password: "password1",
});
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
login = LoginTestUtils.testData.formLogin({
origin: "https://example.org",
formActionOrigin: "https://example.org",
username: "username2",
password: "password2",
});
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
});
// Verify that the autocomplete popup opens when the username field in autofocused.

View File

@ -22,8 +22,7 @@ add_setup(async () => {
password: "password2",
});
Services.logins.addLogin(login1);
Services.logins.addLogin(login2);
await Services.logins.addLogins([login1, login2]);
});
add_task(

View File

@ -29,9 +29,7 @@ add_task(async function test_initialize() {
Services.prefs.clearUserPref("signon.showAutoCompleteFooter");
});
for (let login of loginList()) {
Services.logins.addLogin(login);
}
await Services.logins.addLogins(loginList());
});
add_task(async function test_autocomplete_footer_onclick() {

View File

@ -30,7 +30,7 @@ add_setup(async function() {
username: "username",
password: "password",
});
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
LoginTestUtils.primaryPassword.enable();
registerCleanupFunction(function() {
@ -82,10 +82,10 @@ add_task(async function test_mpAutocompleteUIBusy() {
let win = await BrowserTestUtils.openNewBrowserWindow();
Services.tm.dispatchToMainThread(() => {
Services.tm.dispatchToMainThread(async () => {
try {
// Trigger a MP prompt in the new window by saving a login
Services.logins.addLogin(LoginTestUtils.testData.formLogin());
await Services.logins.addLoginAsync(LoginTestUtils.testData.formLogin());
} catch (e) {
// Handle throwing from MP cancellation
}

View File

@ -35,7 +35,7 @@ add_setup(async function() {
username: "user1",
password: "pass1",
});
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
});
testUrlsWithForm.forEach(testUrl => {

View File

@ -2,20 +2,19 @@ const TEST_URL_PATH =
"://example.org/browser/toolkit/components/passwordmgr/test/browser/";
add_setup(async function() {
let login = LoginTestUtils.testData.formLogin({
const login1 = LoginTestUtils.testData.formLogin({
origin: "http://example.org",
formActionOrigin: "http://example.org",
username: "username",
password: "password",
});
Services.logins.addLogin(login);
login = LoginTestUtils.testData.formLogin({
const login2 = LoginTestUtils.testData.formLogin({
origin: "http://example.org",
formActionOrigin: "http://example.com",
username: "username",
password: "password",
});
Services.logins.addLogin(login);
await Services.logins.addLogins([login1, login2]);
await SpecialPowers.pushPrefEnv({
set: [["signon.autofillForms.http", false]],
});

View File

@ -31,7 +31,7 @@ add_task(async function test() {
"form-basic-username",
"form-basic-password"
);
login = Services.logins.addLogin(login);
login = await Services.logins.addLoginAsync(login);
Assert.equal(
login.timesUsed,
1,

View File

@ -26,9 +26,7 @@ add_task(async function test_initialize() {
Services.prefs.clearUserPref("signon.schemeUpgrades");
Services.prefs.clearUserPref("signon.usernameOnlyForm.enabled");
});
for (let login of loginList()) {
Services.logins.addLogin(login);
}
await Services.logins.addLogins(loginList());
});
/**

View File

@ -22,9 +22,7 @@ add_task(async function test_initialize() {
autocompleteUnexpectedPopupShowing
);
});
for (let login of loginList()) {
Services.logins.addLogin(login);
}
await Services.logins.addLogins(loginList());
autocompletePopup.addEventListener(
"popupshowing",
autocompleteUnexpectedPopupShowing

View File

@ -260,7 +260,7 @@ add_task(async function fill_generated_password_with_matching_logins() {
"passwordmgr-storage-changed",
(_, data) => data == "addLogin"
);
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
await storageChangedPromised;
let formFilled = listenForTestNotification("FormProcessed");

View File

@ -21,9 +21,7 @@ add_task(async function test_initialize() {
Services.prefs.clearUserPref("signon.autofillForms");
Services.prefs.clearUserPref("signon.schemeUpgrades");
});
for (let login of loginList()) {
Services.logins.addLogin(login);
}
await Services.logins.addLogins(loginList());
});
/**

View File

@ -82,10 +82,10 @@ add_task(
let storageUpdatePromise = TestUtils.topicObserved(
"password-storage-updated"
);
Services.logins.addLogin(login1);
await Services.logins.addLoginAsync(login1);
Assert.ok(true, "added login1");
await loginStoreExists();
Services.logins.addLogin(fxaKey);
await Services.logins.addLoginAsync(fxaKey);
Assert.ok(true, "added fxaKey");
await loginBackupExists();
Assert.ok(true, "logins-backup.json now exists");
@ -123,12 +123,12 @@ add_task(async function test_deleteLoginsBackup_removeAllUserFacingLogins() {
"password-storage-updated"
);
info("Add a login to create logins.json");
Services.logins.addLogin(login1);
await Services.logins.addLoginAsync(login1);
await loginStoreExists();
Assert.ok(true, "logins.json now exists");
info("Add a second login to create logins-backup.json");
Services.logins.addLogin(login2);
await Services.logins.addLoginAsync(login2);
await loginBackupExists();
info("logins-backup.json now exists");
@ -166,11 +166,11 @@ add_task(async function test_deleteLoginsBackup_removeAllLogins() {
"password-storage-updated"
);
info("Add a login to create logins.json");
Services.logins.addLogin(login1);
await Services.logins.addLoginAsync(login1);
Assert.ok(true, "added login1");
await loginStoreExists();
Assert.ok(true, "logins.json now exists");
Services.logins.addLogin(login2);
await Services.logins.addLoginAsync(login2);
Assert.ok(true, "added login2");
await loginBackupExists();
info("logins-backup.json now exists");
@ -193,9 +193,9 @@ add_task(async function test_deleteLoginsBackup_removeAllLogins() {
info("Testing the removeAllLogins() case when FxA key is present");
storageUpdatePromise = TestUtils.topicObserved("password-storage-updated");
Services.logins.addLogin(login1);
await Services.logins.addLoginAsync(login1);
await loginStoreExists();
Services.logins.addLogin(fxaKey);
await Services.logins.addLoginAsync(fxaKey);
await loginBackupExists();
info("logins-backup.json now exists");
await storageUpdatePromise;
@ -225,9 +225,9 @@ add_task(async function test_deleteLoginsBackup_removeLogin() {
let storageUpdatePromise = TestUtils.topicObserved(
"password-storage-updated"
);
Services.logins.addLogin(login1);
await Services.logins.addLoginAsync(login1);
await loginStoreExists();
Services.logins.addLogin(login2);
await Services.logins.addLoginAsync(login2);
await loginBackupExists();
info("logins-backup.json now exists");
@ -255,9 +255,9 @@ add_task(async function test_deleteLoginsBackup_removeLogin() {
info("Testing the removeLogin() case when there is a saved fxa key");
info("Adding two logins: one user facing and the fxa key");
storageUpdatePromise = TestUtils.topicObserved("password-storage-updated");
Services.logins.addLogin(login1);
await Services.logins.addLoginAsync(login1);
await loginStoreExists();
Services.logins.addLogin(fxaKey);
await Services.logins.addLoginAsync(fxaKey);
await loginBackupExists();
info("logins-backup.json now exists");

View File

@ -138,8 +138,8 @@ async function _setPrefs() {
});
}
function _addSavedLogin(username) {
Services.logins.addLogin(
async function _addSavedLogins(logins) {
let loginsData = logins.map(({ username }) =>
LoginTestUtils.testData.formLogin({
origin: "https://example.com",
formActionOrigin: "https://example.com",
@ -147,6 +147,7 @@ function _addSavedLogin(username) {
password: "Saved login passwords not used in this test",
})
);
await Services.logins.addLogins(loginsData);
}
async function _clickDropmarker(document, notificationElement) {
@ -180,12 +181,9 @@ add_task(async function test_edit_password() {
Services.logins.removeAllUserFacingLogins();
// Create the pre-existing logins when needed.
info("Adding any saved logins");
if (testCase.savedLogins) {
for (let login of testCase.savedLogins) {
info("Adding login " + JSON.stringify(login));
_addSavedLogin(login.username);
}
info("Adding logins " + JSON.stringify(testCase.savedLogins));
await _addSavedLogins(testCase.savedLogins);
}
info("Opening tab");

View File

@ -166,7 +166,7 @@ add_task(async function test_doorhanger_dismissal_on_change() {
"form-basic-username",
"form-basic-password"
);
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
let passwordFilledPromise = listenForTestNotification(
"PasswordEditedOrGenerated"

View File

@ -30,7 +30,7 @@ add_task(async function test_httpsUpgradeCaptureFields_noChange() {
info(
"Check that we don't prompt to remember when capturing an upgraded login with no change"
);
Services.logins.addLogin(login1);
await Services.logins.addLoginAsync(login1);
// Sanity check the HTTP login exists.
let logins = Services.logins.getAllLogins();
Assert.equal(logins.length, 1, "Should have the HTTP login");
@ -73,7 +73,7 @@ add_task(async function test_httpsUpgradeCaptureFields_changePW() {
info(
"Check that we prompt to change when capturing an upgraded login with a new PW"
);
Services.logins.addLogin(login1);
await Services.logins.addLoginAsync(login1);
// Sanity check the HTTP login exists.
let logins = Services.logins.getAllLogins();
Assert.equal(logins.length, 1, "Should have the HTTP login");
@ -131,8 +131,7 @@ add_task(
info(
"Check that we prompt to change and properly save when capturing an upgraded login with a new PW when an http login also exists for that username"
);
Services.logins.addLogin(login1);
Services.logins.addLogin(login1HTTPS);
await Services.logins.addLogins([login1, login1HTTPS]);
let logins = Services.logins.getAllLogins();
Assert.equal(logins.length, 2, "Should have both HTTP and HTTPS logins");
@ -213,7 +212,7 @@ add_task(
add_task(async function test_httpsUpgradeCaptureFields_captureMatchingHTTP() {
info("Capture a new HTTP login which matches a stored HTTPS one.");
Services.logins.addLogin(login1HTTPS);
await Services.logins.addLoginAsync(login1HTTPS);
await testSubmittingLoginFormHTTP(
"subtst_notifications_1.html",

View File

@ -96,7 +96,7 @@ async function test_save_change(testData) {
} = testData;
// Add a login for the origin of the form if testing a change notification.
if (oldPassword) {
Services.logins.addLogin(
await Services.logins.addLoginAsync(
LoginTestUtils.testData.formLogin({
origin: "https://example.com",
formActionOrigin: "https://example.com",

View File

@ -71,7 +71,7 @@ add_task(async function test_edit_password() {
// Create the pre-existing logins when needed.
if (testCase.usernameInPageExists) {
Services.logins.addLogin(
await Services.logins.addLoginAsync(
LoginTestUtils.testData.formLogin({
origin: "https://example.com",
formActionOrigin: "https://example.com",
@ -82,7 +82,7 @@ add_task(async function test_edit_password() {
}
if (testCase.usernameChangedToExists) {
Services.logins.addLogin(
await Services.logins.addLoginAsync(
LoginTestUtils.testData.formLogin({
origin: "https://example.com",
formActionOrigin: "https://example.com",

View File

@ -419,7 +419,7 @@ add_task(async function test_noPasswordField() {
add_task(async function test_pwOnlyNewLoginMatchesUPForm() {
info("Check for update popup when new existing pw-only login matches form.");
Services.logins.addLogin(login2);
await Services.logins.addLoginAsync(login2);
await testSubmittingLoginFormHTTP(
"subtst_notifications_1.html",
async function(fieldValues) {
@ -473,7 +473,7 @@ add_task(async function test_pwOnlyNewLoginMatchesUPForm() {
add_task(async function test_pwOnlyOldLoginMatchesUPForm() {
info("Check for update popup when old existing pw-only login matches form.");
Services.logins.addLogin(login2);
await Services.logins.addLoginAsync(login2);
// Change the timePasswordChanged to be old so that the password won't be
// revealed in the doorhanger.
@ -542,7 +542,7 @@ add_task(async function test_pwOnlyFormMatchesLogin() {
info(
"Check for no notification popup when pw-only form matches existing login."
);
Services.logins.addLogin(login1);
await Services.logins.addLoginAsync(login1);
await testSubmittingLoginFormHTTP("subtst_notifications_6.html", function(
fieldValues
@ -571,7 +571,7 @@ add_task(async function test_pwOnlyFormDoesntMatchExisting() {
info(
"Check for notification popup when pw-only form doesn't match existing login."
);
Services.logins.addLogin(login1B);
await Services.logins.addLoginAsync(login1B);
await testSubmittingLoginFormHTTP(
"subtst_notifications_6.html",
@ -601,7 +601,7 @@ add_task(async function test_pwOnlyFormDoesntMatchExisting() {
add_task(async function test_changeUPLoginOnUPForm_dont() {
info("Check for change-password popup, u+p login on u+p form. (not changed)");
Services.logins.addLogin(login1);
await Services.logins.addLoginAsync(login1);
await testSubmittingLoginFormHTTP(
"subtst_notifications_8.html",
@ -642,7 +642,7 @@ add_task(async function test_changeUPLoginOnUPForm_dont() {
add_task(async function test_changeUPLoginOnUPForm_remove() {
info("Check for change-password popup, u+p login on u+p form. (remove)");
Services.logins.addLogin(login1);
await Services.logins.addLoginAsync(login1);
await testSubmittingLoginFormHTTP(
"subtst_notifications_8.html",
@ -683,7 +683,7 @@ add_task(async function test_changeUPLoginOnUPForm_remove() {
add_task(async function test_changeUPLoginOnUPForm_change() {
info("Check for change-password popup, u+p login on u+p form.");
Services.logins.addLogin(login1);
await Services.logins.addLoginAsync(login1);
await testSubmittingLoginFormHTTP(
"subtst_notifications_8.html",
@ -739,7 +739,7 @@ add_task(async function test_changeUPLoginOnUPForm_change() {
add_task(async function test_changePLoginOnUPForm() {
info("Check for change-password popup, p-only login on u+p form (empty u).");
Services.logins.addLogin(login2);
await Services.logins.addLoginAsync(login2);
await testSubmittingLoginFormHTTP(
"subtst_notifications_9.html",
@ -927,7 +927,7 @@ add_task(async function test_change2pw0unExistingDifferentUP() {
"is submitted and there is a saved login with a username and different password."
);
Services.logins.addLogin(login1B);
await Services.logins.addLoginAsync(login1B);
await testSubmittingLoginFormHTTP(
"subtst_notifications_2pw_0un.html",
@ -961,7 +961,7 @@ add_task(async function test_change2pw0unExistingDifferentP() {
"is submitted and there is a saved login with no username and different password."
);
Services.logins.addLogin(login2B);
await Services.logins.addLoginAsync(login2B);
await testSubmittingLoginFormHTTP(
"subtst_notifications_2pw_0un.html",
@ -995,7 +995,7 @@ add_task(async function test_change2pw0unExistingWithSameP() {
"is submitted and there is a saved login with a username and the same password."
);
Services.logins.addLogin(login2);
await Services.logins.addLoginAsync(login2);
await testSubmittingLoginFormHTTP(
"subtst_notifications_2pw_0un.html",
@ -1025,7 +1025,7 @@ add_task(async function test_change2pw0unExistingWithSameP() {
add_task(async function test_changeUPLoginOnPUpdateForm() {
info("Check for change-password popup, u+p login on password update form.");
Services.logins.addLogin(login1);
await Services.logins.addLoginAsync(login1);
await testSubmittingLoginFormHTTP(
"subtst_notifications_change_p.html",

View File

@ -89,7 +89,7 @@ async function test_save_change(testData) {
} = testData;
// Add a login for the origin of the form if testing a change notification.
if (oldPassword) {
Services.logins.addLogin(
await Services.logins.addLoginAsync(
LoginTestUtils.testData.formLogin({
origin: "https://example.com",
formActionOrigin: "https://example.com",

View File

@ -276,7 +276,7 @@ function _validateTestCase(tc) {
async function test_submit_telemetry(tc) {
if (tc.savedLogin) {
Services.logins.addLogin(
await Services.logins.addLoginAsync(
LoginTestUtils.testData.formLogin({
origin: "https://example.com",
formActionOrigin: "https://example.com",

View File

@ -57,7 +57,7 @@ add_task(async function test_edit_username() {
// Create the pre-existing logins when needed.
if (testCase.usernameInPageExists) {
Services.logins.addLogin(
await Services.logins.addLoginAsync(
LoginTestUtils.testData.formLogin({
origin: "https://example.com",
formActionOrigin: "https://example.com",
@ -68,7 +68,7 @@ add_task(async function test_edit_username() {
}
if (testCase.usernameChangedToExists) {
Services.logins.addLogin(
await Services.logins.addLoginAsync(
LoginTestUtils.testData.formLogin({
origin: "https://example.com",
formActionOrigin: "https://example.com",

View File

@ -5,7 +5,7 @@
"use strict";
add_setup(function() {
add_setup(async () => {
let nsLoginInfo = Components.Constructor(
"@mozilla.org/login-manager/loginInfo;1",
Ci.nsILoginInfo,
@ -30,8 +30,7 @@ add_setup(function() {
"testpass2"
);
Services.logins.addLogin(login1);
Services.logins.addLogin(login2);
await Services.logins.addLogins([login1, login2]);
});
add_task(async function test_autocompleteFromUsername() {

View File

@ -1,21 +1,19 @@
"use strict";
add_setup(async function() {
let login = LoginTestUtils.testData.formLogin({
add_setup(async () => {
const login1 = LoginTestUtils.testData.formLogin({
origin: "http://10.0.0.0",
formActionOrigin: "https://example.org",
username: "username1",
password: "password1",
});
Services.logins.addLogin(login);
login = LoginTestUtils.testData.formLogin({
const login2 = LoginTestUtils.testData.formLogin({
origin: "https://example.org",
formActionOrigin: "https://example.org",
username: "username2",
password: "password2",
});
Services.logins.addLogin(login);
await Services.logins.addLogins([login1, login2]);
});
add_task(async function test_warningForLocalIP() {

View File

@ -328,7 +328,7 @@ add_task(async function test_normal_popup_notification_3() {
);
Services.logins.removeAllUserFacingLogins();
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
let allLogins = Services.logins.getAllLogins();
// Sanity check the HTTP login exists.
Assert.equal(allLogins.length, 1, "Should have the HTTP login");
@ -387,7 +387,7 @@ add_task(async function test_private_popup_notification_3b() {
);
Services.logins.removeAllUserFacingLogins();
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
let allLogins = Services.logins.getAllLogins();
// Sanity check the HTTP login exists.
Assert.equal(allLogins.length, 1, "Should have the HTTP login");
@ -447,7 +447,7 @@ add_task(async function test_normal_new_password_4() {
" add a new password: popup notification should appear"
);
Services.logins.removeAllUserFacingLogins();
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
let allLogins = Services.logins.getAllLogins();
// Sanity check the HTTP login exists.
Assert.equal(allLogins.length, 1, "Should have the HTTP login");
@ -620,7 +620,7 @@ add_task(async function test_normal_with_login_6() {
add_task(async function test_normal_autofilled_7() {
info("test 7: verify that the user/pass pair was autofilled");
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
// Sanity check the HTTP login exists.
Assert.equal(

View File

@ -59,8 +59,7 @@ add_task(async function test_changeUPLoginOnPUpdateForm_accept() {
info(
"Select an u+p login from multiple logins, on password update form, and accept."
);
Services.logins.addLogin(login1);
Services.logins.addLogin(login1B);
await Services.logins.addLogins([login1, login1B]);
let selectDialogPromise = TestUtils.topicObserved("select-dialog-loaded");
@ -122,8 +121,7 @@ add_task(async function test_changeUPLoginOnPUpdateForm_cancel() {
info(
"Select an u+p login from multiple logins, on password update form, and cancel."
);
Services.logins.addLogin(login1);
Services.logins.addLogin(login1B);
await Services.logins.addLogins([login1, login1B]);
let selectDialogPromise = TestUtils.topicObserved("select-dialog-loaded");

View File

@ -707,27 +707,25 @@ function runInParent(aFunctionOrURL) {
* @param {array} aLogins - a list of logins to add. Each login is an array of the arguments
* that would be passed to nsLoginInfo.init().
*/
function addLoginsInParent(...aLogins) {
async function addLoginsInParent(...aLogins) {
let script = runInParent(function addLoginsInParentInner() {
/* eslint-env mozilla/chrome-script */
addMessageListener("addLogins", logins => {
addMessageListener("addLogins", async logins => {
let nsLoginInfo = Components.Constructor(
"@mozilla.org/login-manager/loginInfo;1",
Ci.nsILoginInfo,
"init"
);
for (let login of logins) {
let loginInfo = new nsLoginInfo(...login);
try {
Services.logins.addLogin(loginInfo);
} catch (e) {
assert.ok(false, "addLogin threw: " + e);
}
const loginInfos = logins.map(login => new nsLoginInfo(...login));
try {
await Services.logins.addLogins(loginInfos);
} catch (e) {
assert.ok(false, "addLogins threw: " + e);
}
});
});
script.sendQuery("addLogins", aLogins);
await script.sendQuery("addLogins", aLogins);
return script;
}

View File

@ -40,7 +40,7 @@ if (LoginHelper.improvedPasswordRulesEnabled) {
* the test can start checking filled-in values. Tests that check observer
* notifications might be confused by this.
*/
function commonInit(selfFilling, testDependsOnDeprecatedLogin) {
async function commonInit(selfFilling, testDependsOnDeprecatedLogin) {
var pwmgr = Services.logins;
assert.ok(pwmgr != null, "Access LoginManager");
@ -69,7 +69,7 @@ function commonInit(selfFilling, testDependsOnDeprecatedLogin) {
"uname",
"pword"
);
pwmgr.addLogin(login);
await pwmgr.addLoginAsync(login);
}
// Last sanity check
@ -145,8 +145,11 @@ addMessageListener("cleanup", () => {
addMessageListener(
"setupParent",
({ selfFilling = false, testDependsOnDeprecatedLogin = false } = {}) => {
commonInit(selfFilling, testDependsOnDeprecatedLogin);
async ({
selfFilling = false,
testDependsOnDeprecatedLogin = false,
} = {}) => {
await commonInit(selfFilling, testDependsOnDeprecatedLogin);
sendAsyncMessage("doneSetup");
}
);

View File

@ -40,7 +40,7 @@ async function openDocumentInWindow(win) {
async function test_password_autofilled() {
info("Adding one login for the page");
addLoginsInParent([DEFAULT_ORIGIN, DEFAULT_ORIGIN, null, "user", "omgsecret!"]);
await addLoginsInParent([DEFAULT_ORIGIN, DEFAULT_ORIGIN, null, "user", "omgsecret!"]);
let numLogins = await LoginManager.countLogins(DEFAULT_ORIGIN, DEFAULT_ORIGIN, null);
is(numLogins, 1, "Correct number of logins");

View File

@ -11,12 +11,12 @@
</head>
<body>
<script>
let readyPromise = registerRunTests(1);
let origin = window.location.origin;
addLoginsInParent(
[origin, "https://autofill", null, "user1", "pass1"],
[origin, "https://autofill", null, "user2", "pass2"]);
const origin = window.location.origin;
const readyPromise = registerRunTests(1)
.then(() => addLoginsInParent(
[origin, "https://autofill", null, "user1", "pass1"],
[origin, "https://autofill", null, "user2", "pass2"]
));
function preventDefaultAndStopProgagation(event) {
event.preventDefault();

View File

@ -11,22 +11,6 @@
</head>
<body>
Login Manager test: no duplicate logins when using autofill and autocomplete with related realms
<script>
addLoginsInParent(
// Simple related domain relationship where example.com and other-example.com are in the related domains list
["https://other-example.com", "https://other-example.com", null, "relatedUser1", "relatedPass1", "uname", "pword"],
// Example.com and example.co.uk are related, so sub.example.co.uk should appear on example.com's autocomplete dropdown
// The intent is to cover the ebay.com/ebay.co.uk and all other country TLD cases
// where the sign in page is actually signin.ebay.com/signin.ebay.co.uk but credentials could have manually been entered
// for ebay.com/ebay.co.uk or automatically stored as signin.ebay.com/sigin.ebay.co.uk
["https://sub.example.co.uk", "https://sub.example.co.uk", null, "subUser1", "subPass1", "uname", "pword"],
// Ensures there are no duplicates for the exact domain that the user is on
["https://example.com", "https://example.com", null, "exactUser1", "exactPass1", "uname", "pword"],
["https://www.example.com", "https://www.example.com", null, "exactWWWUser1", "exactWWWPass1", "uname", "pword"],
);
</script>
<p id="display"></p>
<div id="content">
<form id="form1" action="https://www.example.com" onsubmit="return false;">
@ -52,7 +36,7 @@ function restoreForm() {
}
function sendFakeAutocompleteEvent(element) {
var acEvent = document.createEvent("HTMLEvents");
const acEvent = document.createEvent("HTMLEvents");
acEvent.initEvent("DOMAutoComplete", true, false);
element.dispatchEvent(acEvent);
}
@ -63,29 +47,43 @@ function spinEventLoop() {
async function promiseACPopupClosed() {
return SimpleTest.promiseWaitForCondition(async () => {
let popupState = await getPopupState();
const popupState = await getPopupState();
return !popupState.open;
}, "Wait for AC popup to be closed");
}
add_setup(async () => {
await addLoginsInParent(
// Simple related domain relationship where example.com and other-example.com are in the related domains list
["https://other-example.com", "https://other-example.com", null, "relatedUser1", "relatedPass1", "uname", "pword"],
// Example.com and example.co.uk are related, so sub.example.co.uk should appear on example.com's autocomplete dropdown
// The intent is to cover the ebay.com/ebay.co.uk and all other country TLD cases
// where the sign in page is actually signin.ebay.com/signin.ebay.co.uk but credentials could have manually been entered
// for ebay.com/ebay.co.uk or automatically stored as signin.ebay.com/sigin.ebay.co.uk
["https://sub.example.co.uk", "https://sub.example.co.uk", null, "subUser1", "subPass1", "uname", "pword"],
// Ensures there are no duplicates for the exact domain that the user is on
["https://example.com", "https://example.com", null, "exactUser1", "exactPass1", "uname", "pword"],
["https://www.example.com", "https://www.example.com", null, "exactWWWUser1", "exactWWWPass1", "uname", "pword"],
);
listenForUnexpectedPopupShown();
});
add_task(async function test_no_duplicates_autocomplete_autofill() {
await promiseFormsProcessedInSameProcess();
await SimpleTest.promiseFocus(window);
let results = await popupBy(() => {
const results = await popupBy(() => {
checkLoginForm(uname, "exactUser1", pword, "exactPass1")
restoreForm();
});
let popupState = await getPopupState();
const popupState = await getPopupState();
is(popupState.selectedIndex, -1, "Check no entires are selected upon opening");
let expectedMenuItems = ["exactUser1", "exactWWWUser1", "relatedUser1", "subUser1"];
const expectedMenuItems = ["exactUser1", "exactWWWUser1", "relatedUser1", "subUser1"];
checkAutoCompleteResults(results, expectedMenuItems, window.location.host, "Check all menuitems are displayed correctly");
let acEvents = await getTelemetryEvents({ process: "parent", filterProps: TelemetryFilterPropsAC, clear: true });
const acEvents = await getTelemetryEvents({ process: "parent", filterProps: TelemetryFilterPropsAC, clear: true });
is(acEvents.length, 1, "One autocomplete event");
checkACTelemetryEvent(acEvents[0], uname, {
"hadPrevious": "0",

View File

@ -24,7 +24,7 @@ function addLoginsInParent(...aLogins) {
let initialCount = 5;
addMessageListener("initLogins", logins => {
addMessageListener("initLogins", async logins => {
let nsLoginInfo = Components.Constructor(
"@mozilla.org/login-manager/loginInfo;1",
Ci.nsILoginInfo,
@ -37,7 +37,7 @@ function addLoginsInParent(...aLogins) {
// Only add the first 'initialCount' number of logins.
if (initialCount-- > 0) {
try {
Services.logins.addLogin(loginInfo);
await Services.logins.addLoginAsync(loginInfo);
} catch (e) {
assert.ok(false, "addLogin threw: " + e);
}
@ -46,10 +46,10 @@ function addLoginsInParent(...aLogins) {
}
});
addMessageListener("addLogin", loginVariableName => {
addMessageListener("addLogin", async loginVariableName => {
let login = loginsMap[loginVariableName];
assert.ok(!!login, "Login to add is defined: " + loginVariableName);
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
});
addMessageListener("removeLogin", loginVariableName => {
let login = loginsMap[loginVariableName];

View File

@ -13,10 +13,7 @@
Login Manager test: logins with non-matching formActionOrigin appear in autocomplete dropdown
<script>
var chromeScript = runChecksAfterCommonInit();
addLoginsInParent([window.location.origin, "https://differentFormSubmitURL", null,
"dfsu1", "dfsp1", "uname", "pword"]);
const chromeScript = runChecksAfterCommonInit();
</script>
<p id="display"></p>
@ -50,6 +47,9 @@ function spinEventLoop() {
}
add_setup(async () => {
await addLoginsInParent(
[window.location.origin, "https://differentFormSubmitURL", null, "dfsu1", "dfsp1", "uname", "pword"]
);
listenForUnexpectedPopupShown();
});
@ -58,7 +58,7 @@ add_task(async function test_form1_initial_empty() {
// Make sure initial form is empty.
checkLoginForm(uname, "", pword, "");
let popupState = await getPopupState();
const popupState = await getPopupState();
is(popupState.open, false, "Check popup is initially closed");
});
@ -72,10 +72,10 @@ add_task(async function test_form1_menu_shows_logins_for_different_formActionOri
restoreForm();
const autocompleteItems = await popupByArrowDown();
let popupState = await getPopupState();
const popupState = await getPopupState();
is(popupState.selectedIndex, -1, "Check no entries are selected upon opening");
let expectedMenuItems = ["dfsu1"];
const expectedMenuItems = ["dfsu1"];
checkAutoCompleteResults(autocompleteItems, expectedMenuItems, window.location.host, "Check all menuitems are displayed correctly.");
synthesizeKey("KEY_ArrowDown"); // first item

View File

@ -12,9 +12,9 @@
<body>
<script>
var chromeScript = runChecksAfterCommonInit();
const chromeScript = runChecksAfterCommonInit();
var setupScript = runInParent(function setup() {
const setupScript = runInParent(async function setup() {
// Create some logins just for this form, since we'll be deleting them.
var nsLoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
Ci.nsILoginInfo, "init");
@ -62,23 +62,21 @@ var setupScript = runInParent(function setup() {
// try/catch in case someone runs the tests manually, twice.
try {
Services.logins.addLogin(logins.login0);
Services.logins.addLogin(logins.login1);
Services.logins.addLogin(logins.login2);
Services.logins.addLogin(logins.login3);
Services.logins.addLogin(logins.login4);
} catch (e) {
assert.ok(false, "addLogin threw: " + e);
}
await Services.logins.addLogins([
logins.login0,
logins.login1,
logins.login2,
logins.login3,
logins.login4,
]);
addMessageListener("addLogin", loginVariableName => {
let login = logins[loginVariableName];
const login = logins[loginVariableName];
assert.ok(!!login, "Login to add is defined: " + loginVariableName);
Services.logins.addLogin(login);
});
addMessageListener("removeLogin", loginVariableName => {
let login = logins[loginVariableName];
const login = logins[loginVariableName];
assert.ok(!!login, "Login to delete is defined: " + loginVariableName);
Services.logins.removeLogin(login);
});

View File

@ -11,19 +11,6 @@
</head>
<body>
Login Manager test: related realms autocomplete
<script>
addLoginsInParent(
// Simple related domain relationship where example.com and other-example.com are in the related domains list
["https://other-example.com", "https://other-example.com", null, "relatedUser1", "relatedPass1", "uname", "pword"],
// Example.com and example.co.uk are related, so sub.example.co.uk should appear on example.com's autocomplete dropdown
// The intent is to cover the ebay.com/ebay.co.uk and all other country TLD cases
// where the sign in page is actually signin.ebay.com/signin.ebay.co.uk but credentials could have manually been entered
// for ebay.com/ebay.co.uk or automatically stored as signin.ebay.com/sigin.ebay.co.uk
["https://sub.example.co.uk", "https://sub.example.co.uk", null, "subUser1", "subPass1", "uname", "pword"],
);
</script>
<p id="display"></p>
<div id="content">
<form id="form1" onsubmit="return false;">
@ -66,6 +53,16 @@ async function promiseACPopupClosed() {
}
add_setup(async () => {
await addLoginsInParent(
// Simple related domain relationship where example.com and other-example.com are in the related domains list
["https://other-example.com", "https://other-example.com", null, "relatedUser1", "relatedPass1", "uname", "pword"],
// Example.com and example.co.uk are related, so sub.example.co.uk should appear on example.com's autocomplete dropdown
// The intent is to cover the ebay.com/ebay.co.uk and all other country TLD cases
// where the sign in page is actually signin.ebay.com/signin.ebay.co.uk but credentials could have manually been entered
// for ebay.com/ebay.co.uk or automatically stored as signin.ebay.com/sigin.ebay.co.uk
["https://sub.example.co.uk", "https://sub.example.co.uk", null, "subUser1", "subPass1", "uname", "pword"],
);
listenForUnexpectedPopupShown();
});

View File

@ -11,34 +11,6 @@
</head>
<body>
Login Manager test: logins with non-exact match origin appear in autocomplete dropdown
<script>
let origin = window.location.origin;
let lastDot = origin.lastIndexOf(".");
let suffix = origin.slice(lastDot);
let baseHost = "http://example" + suffix;
let baseSecureHost = "https://example" + suffix;
let oldHost = "http://old.example" + suffix;
let oldSecureHost = "https://old.example" + suffix;
let newHost = "https://new.example" + suffix;
addLoginsInParent(
// The first two logins should never be visible on https: versions of
// *.example.com since the login is for http: and an https: login exists for this username.
[oldHost, oldSecureHost, null, "dsdu1", "dsdp1new", "uname", "pword"],
[baseHost, baseSecureHost, null, "dsdu1", "dsdp1", "uname", "pword"],
[oldSecureHost, oldSecureHost, null, "dsdu1", "dsdp1", "uname", "pword"],
[baseSecureHost, baseSecureHost, null, "dsdu1", "dsdp1", "uname", "pword"],
[newHost, newHost, null, "dsdu1", "dsdp1prime", "uname", "pword"]);
var setupScript = runInParent(function setup() {
addMessageListener("getDateString", () => {
let dateAndTimeFormatter = new Services.intl.DateTimeFormat(undefined, { dateStyle: "medium" });
return dateAndTimeFormatter.format(new Date());
});
});
</script>
<p id="display"></p>
<!-- we presumably can't hide the content for this test. -->
@ -68,7 +40,34 @@ function spinEventLoop() {
return Promise.resolve();
}
const setupScript = runInParent(function setup() {
addMessageListener("getDateString", () => {
const dateAndTimeFormatter = new Services.intl.DateTimeFormat(undefined, { dateStyle: "medium" });
return dateAndTimeFormatter.format(new Date());
});
});
add_setup(async () => {
const origin = window.location.origin;
const lastDot = origin.lastIndexOf(".");
const suffix = origin.slice(lastDot);
const baseHost = "http://example" + suffix;
const baseSecureHost = "https://example" + suffix;
const oldHost = "http://old.example" + suffix;
const oldSecureHost = "https://old.example" + suffix;
const newHost = "https://new.example" + suffix;
await addLoginsInParent(
// The first two logins should never be visible on https: versions of
// *.example.com since the login is for http: and an https: login exists for this username.
[oldHost, oldSecureHost, null, "dsdu1", "dsdp1new", "uname", "pword"],
[baseHost, baseSecureHost, null, "dsdu1", "dsdp1", "uname", "pword"],
[oldSecureHost, oldSecureHost, null, "dsdu1", "dsdp1", "uname", "pword"],
[baseSecureHost, baseSecureHost, null, "dsdu1", "dsdp1", "uname", "pword"],
[newHost, newHost, null, "dsdu1", "dsdp1prime", "uname", "pword"]
);
await SpecialPowers.pushPrefEnv({
set: [
["signon.includeOtherSubdomainsInLookup", true],
@ -82,7 +81,7 @@ add_task(async function test_form1_initial_empty() {
// Make sure initial form is empty.
checkLoginForm(uname, "", pword, "");
let popupState = await getPopupState();
const popupState = await getPopupState();
is(popupState.open, false, "Check popup is initially closed");
});
@ -96,13 +95,13 @@ add_task(async function test_form1_menu_shows_two_logins_same_usernames_for_diff
restoreForm();
const autocompleteItems = await popupByArrowDown();
let popupState = await getPopupState();
const popupState = await getPopupState();
is(popupState.selectedIndex, -1, "Check no entries are selected upon opening");
// The logins are added "today" and since they are duplicates, the date that they were last
// changed will be appended.
let dateString = await setupScript.sendQuery("getDateString");
let username = `dsdu1 (${dateString})`;
const dateString = await setupScript.sendQuery("getDateString");
const username = `dsdu1 (${dateString})`;
checkAutoCompleteResults(autocompleteItems, [username, username], window.location.host, "Check all menuitems are displayed correctly.");

View File

@ -11,13 +11,6 @@
</head>
<body>
Login Manager test: Test that passwords are autocompleted into fields that were previously type=password
<script>
let origin = window.location.origin;
addLoginsInParent(
[origin, origin, null, "user1", "pass1"],
[origin, origin, null, "user2", "pass2"]);
</script>
<p id="display"></p>
<!-- we presumably can't hide the content for this test. -->
@ -48,6 +41,11 @@ function spinEventLoop() {
}
add_setup(async () => {
const origin = window.location.origin;
await addLoginsInParent(
[origin, origin, null, "user1", "pass1"],
[origin, origin, null, "user2", "pass2"]
);
listenForUnexpectedPopupShown();
});
@ -56,7 +54,7 @@ add_task(async function test_form1_initial_empty() {
// Make sure initial form is empty.
checkLoginForm(uname, "", pword, "");
let popupState = await getPopupState();
const popupState = await getPopupState();
is(popupState.open, false, "Check popup is initially closed");
});
@ -70,7 +68,7 @@ add_task(async function test_form1_password_to_type_text() {
restoreForm();
const autocompleteItems = await popupByArrowDown();
let popupState = await getPopupState();
const popupState = await getPopupState();
is(popupState.selectedIndex, -1, "Check no entries are selected upon opening");
checkAutoCompleteResults(autocompleteItems, ["user1", "user2"], window.location.host,

View File

@ -9,15 +9,6 @@
<script type="text/javascript" src="pwmgr_common.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<script>
let readyPromise = registerRunTests(1);
let origin = window.location.origin;
addLoginsInParent(
[origin, "https://autocomplete", null, "user1", "pass1", "", ""],
[origin, "https://autocomplete", null, "user2", "pass2", "", ""]);
</script>
<body>
<p id="display"></p>
<div id="content">
@ -28,19 +19,22 @@ addLoginsInParent(
</form>
<pre id="test">
<script>
let { ContentTaskUtils } = SpecialPowers.ChromeUtils.import(
const { ContentTaskUtils } = SpecialPowers.ChromeUtils.import(
"resource://testing-common/ContentTaskUtils.jsm"
);
add_setup(async () => {
ok(readyPromise, "check promise is available");
await readyPromise;
const origin = window.location.origin;
await addLoginsInParent(
[origin, "https://autocomplete", null, "user1", "pass1", "", ""],
[origin, "https://autocomplete", null, "user2", "pass2", "", ""]
);
});
add_task(async function test_field_highlight_on_autocomplete() {
// Test username autocomplete.
let username = document.getElementById("uname");
let password = document.getElementById("pword");
const username = document.getElementById("uname");
const password = document.getElementById("pword");
await openPopupOn(username);
synthesizeKey("KEY_ArrowDown");

View File

@ -9,15 +9,6 @@
<script type="text/javascript" src="pwmgr_common.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<script>
let readyPromise = registerRunTests(1);
let origin = window.location.origin;
addLoginsInParent(
[origin, "https://autocomplete", null, "user1", "pass1", "", ""],
[origin, "https://autocomplete", null, "user2", "pass2", "", ""]);
</script>
<body>
<p id="display"></p>
<div id="content">
@ -27,13 +18,16 @@ addLoginsInParent(
</form>
<pre id="test">
<script>
let { ContentTaskUtils } = SpecialPowers.ChromeUtils.import(
const { ContentTaskUtils } = SpecialPowers.ChromeUtils.import(
"resource://testing-common/ContentTaskUtils.jsm"
);
add_setup(async () => {
ok(readyPromise, "check promise is available");
await readyPromise;
const origin = window.location.origin;
await addLoginsInParent(
[origin, "https://autocomplete", null, "user1", "pass1", "", ""],
[origin, "https://autocomplete", null, "user2", "pass2", "", ""]
);
});
add_task(async function test_username_field_in_username_only_form_highlight_on_autocomplete() {

View File

@ -14,35 +14,27 @@ PWMGR_COMMON_PARENT.sendAsyncMessage("setupParent", { selfFilling: true });
SimpleTest.waitForExplicitFinish();
let chromeScript = runInParent(function chromeSetup() {
let login1A = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
let login1B = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
let login2A = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
let login2B = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
let login2C = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
const chromeScript = runInParent(async function chromeSetup() {
const login1A = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(Ci.nsILoginInfo);
const login1B = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(Ci.nsILoginInfo);
const login2A = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(Ci.nsILoginInfo);
const login2B = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(Ci.nsILoginInfo);
const login2C = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(Ci.nsILoginInfo);
login1A.init("http://mochi.test:8888", "http://bug444968-1", null,
"testuser1A", "testpass1A", "", "");
login1B.init("http://mochi.test:8888", "http://bug444968-1", null,
"", "testpass1B", "", "");
login1A.init("http://mochi.test:8888", "http://bug444968-1", null, "testuser1A", "testpass1A", "", "");
login1B.init("http://mochi.test:8888", "http://bug444968-1", null, "", "testpass1B", "", "");
login2A.init("http://mochi.test:8888", "http://bug444968-2", null,
"testuser2A", "testpass2A", "", "");
login2B.init("http://mochi.test:8888", "http://bug444968-2", null,
"", "testpass2B", "", "");
login2C.init("http://mochi.test:8888", "http://bug444968-2", null,
"testuser2C", "testpass2C", "", "");
login2A.init("http://mochi.test:8888", "http://bug444968-2", null, "testuser2A", "testpass2A", "", "");
login2B.init("http://mochi.test:8888", "http://bug444968-2", null, "", "testpass2B", "", "");
login2C.init("http://mochi.test:8888", "http://bug444968-2", null, "testuser2C", "testpass2C", "", "");
Services.logins.addLogin(login1A);
Services.logins.addLogin(login1B);
Services.logins.addLogin(login2A);
Services.logins.addLogin(login2B);
Services.logins.addLogin(login2C);
await Services.logins.addLogins([
login1A,
login1B,
login2A,
login2B,
login2C,
]);
addMessageListener("removeLogins", function removeLogins() {
Services.logins.removeLogin(login1A);
@ -63,13 +55,13 @@ registerRunTests();
</div>
<pre id="test">
<script class="testbody" type="text/javascript">
let DEFAULT_ORIGIN = window.location.origin;
const DEFAULT_ORIGIN = window.location.origin;
/* Test for Login Manager: 444968 (password-only forms should prefer a
* password-only login when present )
*/
async function startTest() {
let win = window.open("about:blank");
const win = window.open("about:blank");
SimpleTest.registerCleanupFunction(() => win.close());
await loadFormIntoWindow(DEFAULT_ORIGIN, `
<!-- first 3 forms have matching user+pass and pass-only logins -->

View File

@ -12,19 +12,17 @@
<body>
<script>
var chromeScript = runChecksAfterCommonInit();
const chromeScript = runChecksAfterCommonInit();
var setupScript = runInParent(function setup() {
var nsLoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
Ci.nsILoginInfo, "init");
const setupScript = runInParent(async function setup() {
const nsLoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1", Ci.nsILoginInfo, "init");
assert.ok(nsLoginInfo != null, "nsLoginInfo constructor");
var login1 = new nsLoginInfo("https://example.com", "", null,
"tempuser1", "temppass1", "uname", "pword");
const login1 = new nsLoginInfo("https://example.com", "", null, "tempuser1", "temppass1", "uname", "pword");
// try/catch in case someone runs the tests manually, twice.
try {
Services.logins.addLogin(login1);
await Services.logins.addLogin(login1);
} catch (e) {
assert.ok(false, "addLogin threw: " + e);
}
@ -42,7 +40,7 @@ var setupScript = runInParent(function setup() {
/** Test for Login Manager: form field autofill in sandboxed documents (null principal) **/
let sandboxed = document.getElementById("sandboxed");
const sandboxed = document.getElementById("sandboxed");
let uname;
let pword;
@ -52,8 +50,8 @@ function promiseExecuteSoon() {
add_task(async function test_no_autofill_in_form() {
sandboxed.src = "form_basic.html";
let frameWindow = SpecialPowers.wrap(sandboxed).contentWindow;
let DOMFormHasPasswordPromise = new Promise(resolve => {
const frameWindow = SpecialPowers.wrap(sandboxed).contentWindow;
const DOMFormHasPasswordPromise = new Promise(resolve => {
SpecialPowers.addChromeEventListener("DOMFormHasPassword", function onDFHP() {
SpecialPowers.removeChromeEventListener("DOMFormHasPassword", onDFHP);
resolve();
@ -66,7 +64,7 @@ add_task(async function test_no_autofill_in_form() {
}, "Check frame is loaded");
info("frame loaded");
await DOMFormHasPasswordPromise;
let frameDoc = SpecialPowers.wrap(sandboxed).contentDocument;
const frameDoc = SpecialPowers.wrap(sandboxed).contentDocument;
uname = frameDoc.getElementById("form-basic-username");
pword = frameDoc.getElementById("form-basic-password");
@ -88,8 +86,8 @@ add_task(async function test_no_autofill_in_form() {
add_task(async function test_no_autofill_outside_form() {
sandboxed.src = "formless_basic.html";
let frameWindow = SpecialPowers.wrap(sandboxed).contentWindow;
let DOMInputPasswordAddedPromise = new Promise(resolve => {
const frameWindow = SpecialPowers.wrap(sandboxed).contentWindow;
const DOMInputPasswordAddedPromise = new Promise(resolve => {
SpecialPowers.addChromeEventListener("DOMInputPasswordAdded", function onDIPA() {
SpecialPowers.removeChromeEventListener("DOMInputPasswordAdded", onDIPA);
resolve();
@ -102,7 +100,7 @@ add_task(async function test_no_autofill_outside_form() {
}, "Check frame is loaded");
info("frame loaded");
await DOMInputPasswordAddedPromise;
let frameDoc = SpecialPowers.wrap(sandboxed).contentDocument;
const frameDoc = SpecialPowers.wrap(sandboxed).contentDocument;
uname = frameDoc.getElementById("form-basic-username");
pword = frameDoc.getElementById("form-basic-password");

View File

@ -12,19 +12,14 @@ Login Manager test: html5 input types (email, tel, url, etc.)
<script>
runChecksAfterCommonInit(() => startTest());
let DEFAULT_ORIGIN = window.location.origin;
const DEFAULT_ORIGIN = window.location.origin;
runInParent(function setup() {
let login1 = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
let login2 = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
let login3 = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
let login4 = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
let login5 = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
runInParent(async function setup() {
const login1 = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(Ci.nsILoginInfo);
const login2 = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(Ci.nsILoginInfo);
const login3 = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(Ci.nsILoginInfo);
const login4 = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(Ci.nsILoginInfo);
const login5 = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(Ci.nsILoginInfo);
login1.init("http://mochi.test:8888", "http://bug600551-1", null,
"testuser@example.com", "testpass1", "", "");
@ -37,11 +32,13 @@ runInParent(function setup() {
login5.init("http://mochi.test:8888", "http://bug600551-5", null,
"test", "test", "", "");
Services.logins.addLogin(login1);
Services.logins.addLogin(login2);
Services.logins.addLogin(login3);
Services.logins.addLogin(login4);
Services.logins.addLogin(login5);
await Services.logins.addLogins([
login1,
login2,
login3,
login4,
login5,
]);
});
</script>
@ -55,7 +52,7 @@ runInParent(function setup() {
(Password manager not working with input type=email)
*/
async function startTest() {
let win = window.open("about:blank");
const win = window.open("about:blank");
SimpleTest.registerCleanupFunction(() => win.close());
await loadFormIntoWindow(DEFAULT_ORIGIN, `
<form id="form1" action="http://bug600551-1">

View File

@ -11,31 +11,18 @@
Login Manager test: forms and logins without a username.
<script>
gTestDependsOnDeprecatedLogin = true;
runChecksAfterCommonInit(() => startTest());
runInParent(() => {
var nsLoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1", Ci.nsILoginInfo);
// pwlogin1 uses a unique formActionOrigin, to check forms where no other logins
// will apply. pwlogin2 uses the normal formActionOrigin, so that we can test
runChecksAfterCommonInit(async () => {
// The first login uses a unique formActionOrigin, to check forms where no other logins
// will apply. The second login uses the normal formActionOrigin, so that we can test
// forms with a mix of username and non-username logins that might apply.
//
// Note: pwlogin2 is deleted at the end of the test.
let pwlogin1 = new nsLoginInfo();
let pwlogin2 = new nsLoginInfo();
pwlogin1.init("http://mochi.test:8888", "http://mochi.test:1111", null,
"", "1234");
pwlogin2.init("http://mochi.test:8888", "http://mochi.test:8888", null,
"", "1234");
Services.logins.addLogin(pwlogin1);
Services.logins.addLogin(pwlogin2);
// Note: the second login is deleted at the end of the test.
await addLoginsInParent(
["http://mochi.test:8888", "http://mochi.test:1111", null, "", "1234"],
["http://mochi.test:8888", "http://mochi.test:8888", null, "", "1234"]
);
await startTest();
});
let DEFAULT_ORIGIN = window.location.origin;
</script>
<p id="display"></p>
@ -44,10 +31,11 @@ let DEFAULT_ORIGIN = window.location.origin;
<pre id="test">
<script class="testbody" type="text/javascript">
const DEFAULT_ORIGIN = window.location.origin;
/** Test for Login Manager: password-only logins **/
async function startTest() {
let win = window.open("about:blank");
const win = window.open("about:blank");
SimpleTest.registerCleanupFunction(() => win.close());
await loadFormIntoWindow(DEFAULT_ORIGIN, `
<!-- simple form: no username field, 1 password field -->

View File

@ -77,32 +77,31 @@
{expectedDialogs: 1, test: testAnonymousCredentials},
{expectedDialogs: 0, test: testAnonymousNoAuth}];
let mm = runInParent(() => {
const mm = runInParent(() => {
const { classes: parentCc, interfaces: parentCi } = Components;
let {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
let channel = NetUtil.newChannel({
const channel = NetUtil.newChannel({
uri: "http://example.com",
loadUsingSystemPrincipal: true,
});
let pps = parentCc["@mozilla.org/network/protocol-proxy-service;1"].
const pps = parentCc["@mozilla.org/network/protocol-proxy-service;1"].
getService(parentCi.nsIProtocolProxyService);
pps.asyncResolve(channel, 0, {
onProxyAvailable(req, uri, pi, status) {
let mozproxy = "moz-proxy://" + pi.host + ":" + pi.port;
let login = parentCc["@mozilla.org/login-manager/loginInfo;1"].
async onProxyAvailable(req, uri, pi, status) {
const mozproxy = "moz-proxy://" + pi.host + ":" + pi.port;
const login1 = parentCc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(parentCi.nsILoginInfo);
login.init(mozproxy, null, "proxy_realm", "proxy_user", "proxy_pass",
login1.init(mozproxy, null, "proxy_realm", "proxy_user", "proxy_pass",
"", "");
Services.logins.addLogin(login);
let login2 = parentCc["@mozilla.org/login-manager/loginInfo;1"].
const login2 = parentCc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(parentCi.nsILoginInfo);
login2.init("http://mochi.test:8888", null, "mochirealm", "user1name",
"user1pass", "", "");
Services.logins.addLogin(login2);
await Services.logins.addLogins([login1, login2]);
sendAsyncMessage("setupDone");
},
@ -116,10 +115,10 @@
sendAsyncMessage("prepareForNextTestDone");
});
let modalType = Services.prefs.getIntPref(
const modalType = Services.prefs.getIntPref(
"prompts.modalType.httpAuth"
);
let authPromptIsCommonDialog =
const authPromptIsCommonDialog =
modalType === Services.prompt.MODAL_TYPE_WINDOW
|| (modalType === Services.prompt.MODAL_TYPE_TAB
&& Services.prefs.getBoolPref(
@ -127,7 +126,7 @@
false
));
let dialogObserverTopic = authPromptIsCommonDialog
const dialogObserverTopic = authPromptIsCommonDialog
? "common-dialog-loaded" : "tabmodal-dialog-loaded";
function dialogObserver(subj, topic, data) {
@ -136,7 +135,7 @@
.getElementById("commonDialog")
.acceptDialog();
} else {
let prompt = subj.ownerGlobal.gBrowser.selectedBrowser
const prompt = subj.ownerGlobal.gBrowser.selectedBrowser
.tabModalPromptBox.getPrompt(subj);
prompt.Dialog.ui.button0.click(); // Accept button
}

View File

@ -11,16 +11,6 @@
</head>
<body>
Login Manager test: autocomplete due to multiple matching logins
<script>
runChecksAfterCommonInit(false);
let origin = window.location.origin;
addLoginsInParent(
[origin, "https://autocomplete:8888", null, "name", "pass", "uname", "pword"],
[origin, "https://autocomplete:8888", null, "Name", "Pass", "uname", "pword"],
[origin, "https://autocomplete:8888", null, "USER", "PASS", "uname", "pword"]);
</script>
<p id="display"></p>
<!-- we presumably can't hide the content for this test. -->
@ -37,6 +27,7 @@ addLoginsInParent(
<pre id="test">
<script class="testbody" type="text/javascript">
runChecksAfterCommonInit(false);
/** Test for Login Manager: autocomplete due to multiple matching logins **/
@ -50,6 +41,14 @@ function restoreForm() {
uname.focus();
}
add_setup(async () => {
const origin = window.location.origin;
await addLoginsInParent(
[origin, "https://autocomplete:8888", null, "name", "pass", "uname", "pword"],
[origin, "https://autocomplete:8888", null, "Name", "Pass", "uname", "pword"],
[origin, "https://autocomplete:8888", null, "USER", "PASS", "uname", "pword"]
);
})
add_task(async function test_empty_first_entry() {
/* test 1 */
@ -65,7 +64,7 @@ add_task(async function test_empty_first_entry() {
checkAutoCompleteResults(items, ["name", "Name", "USER"], "example.com", "initial");
// Check first entry
let index0Promise = notifySelectedIndex(0);
const index0Promise = notifySelectedIndex(0);
synthesizeKey("KEY_ArrowDown");
await index0Promise;
checkLoginForm(uname, "", pword, ""); // value shouldn't update

View File

@ -12,21 +12,17 @@ Login Manager test: form with JS submit action
<script>
runChecksAfterCommonInit(() => startTest());
runInParent(function setup() {
let jslogin = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(Ci.nsILoginInfo);
jslogin.init("http://mochi.test:8888", "javascript:", null,
"jsuser", "jspass123", "uname", "pword");
Services.logins.addLogin(jslogin);
});
let DEFAULT_ORIGIN = window.location.origin;
const origin = window.location.origin;
/** Test for Login Manager: JS action URL **/
async function startTest() {
let win = window.open("about:blank");
await addLoginsInParent(
[origin, "javascript:", null, "jsuser", "jspass123", "uname", "pword"]
);
const win = window.open("about:blank");
SimpleTest.registerCleanupFunction(() => win.close());
await loadFormIntoWindow(DEFAULT_ORIGIN, `
await loadFormIntoWindow(origin, `
<form id='form1' action='javascript:alert("never shows")'> 1
<input name="uname">
<input name="pword" type="password">

View File

@ -10,7 +10,7 @@
</head>
<body>
<script type="application/javascript">
let readyPromise = registerRunTests();
const readyPromise = registerRunTests();
const DEFAULT_ORIGIN = window.location.origin;
@ -20,14 +20,14 @@ function removeAllUserFacingLoginsInParent() {
});
}
function add2logins() {
async function add2logins() {
removeAllUserFacingLoginsInParent();
addLoginsInParent([DEFAULT_ORIGIN, DEFAULT_ORIGIN, null, "real••••user", "pass1", "", ""], [DEFAULT_ORIGIN, DEFAULT_ORIGIN, null, "user2", "pass2", "", ""]);
await addLoginsInParent([DEFAULT_ORIGIN, DEFAULT_ORIGIN, null, "real••••user", "pass1", "", ""], [DEFAULT_ORIGIN, DEFAULT_ORIGIN, null, "user2", "pass2", "", ""]);
}
function addSingleLogin() {
async function addSingleLogin() {
removeAllUserFacingLoginsInParent();
addLoginsInParent([DEFAULT_ORIGIN, DEFAULT_ORIGIN, null, "real••••user", "pass1", "", ""])
await addLoginsInParent([DEFAULT_ORIGIN, DEFAULT_ORIGIN, null, "real••••user", "pass1", "", ""])
}
/**
@ -37,14 +37,14 @@ function addSingleLogin() {
function generateTestCases(test) {
const MUNGE_CHARS = ["*", ".", "•"];
let nothingToReplace = Object.values(test).every(value => typeof value !== "string" || !value.includes("!"));
const nothingToReplace = Object.values(test).every(value => typeof value !== "string" || !value.includes("!"));
if (nothingToReplace) {
return test;
};
return MUNGE_CHARS.map(char => {
let newTest = {};
for (let [propName, val] of Object.entries(test)) {
const newTest = {};
for (const [propName, val] of Object.entries(test)) {
if (typeof val === "string") {
newTest[propName] = val.replace(/!/g, char);
} else {
@ -54,7 +54,7 @@ function addSingleLogin() {
return newTest;
})};
let loadPromise = new Promise(resolve => {
const loadPromise = new Promise(resolve => {
document.addEventListener("DOMContentLoaded", () => {
resolve();
});
@ -101,14 +101,14 @@ add_task(async function test_new_logins() {
expected: "*.•*.•*.•*.•*.•*.•",
},
].flatMap(generateTestCases);
for (let tc of TEST_CASES) {
for (const tc of TEST_CASES) {
info("Starting testcase: " + JSON.stringify(tc));
// Create a new window for each test case, because if we instead try to use
// the same window and change the page using window.location, that will trigger
// an onLocationChange event, which can trigger unwanted FormSubmit outside of
// clicking the submit button in each test document.
let win = window.open("about:blank");
let html = `
const win = window.open("about:blank");
const html = `
<form id="form1" onsubmit="return false;">
<input type="text" name="uname" value="${tc.username}">
<input type="password" name="pword" value="thepassword">
@ -116,25 +116,25 @@ add_task(async function test_new_logins() {
</form>`;
await loadFormIntoWindow(DEFAULT_ORIGIN, html, win);
await SpecialPowers.spawn(win, [html], function(contentHtml) {
let doc = this.content.document;
for (let field of doc.querySelectorAll("input")) {
let actualValue = field.value;
const doc = this.content.document;
for (const field of doc.querySelectorAll("input")) {
const actualValue = field.value;
field.value = "";
SpecialPowers.wrap(field).setUserInput(actualValue);
}
});
await SpecialPowers.spawn(win, [tc], function(testcase) {
let doc = this.content.document;
const doc = this.content.document;
Assert.equal(doc.querySelector("[name='uname']").value, testcase.username, "Checking for filled username");
});
// Check data sent via PasswordManager:onFormSubmit
let processedPromise = getSubmitMessage();
const processedPromise = getSubmitMessage();
await SpecialPowers.spawn(win, [], function() {
this.content.document.getElementById("submitBtn").click();
});
let { data } = await processedPromise;
const { data } = await processedPromise;
info("Got submitted result: " + JSON.stringify(data));
if (tc.expected === null) {
@ -177,14 +177,14 @@ add_task(async function test_no_save_dialog_when_password_is_fully_munged() {
},
].flatMap(generateTestCases);
for (let tc of TEST_CASES) {
for (const tc of TEST_CASES) {
info("Starting testcase: " + tc.testName)
// Create a new window for each test case, because if we instead try to use
// the same window and change the page using window.location, that will trigger
// an onLocationChange event, which can trigger unwanted FormSubmit outside of
// clicking the submit button in each test document.
let win = window.open("about:blank");
let html = `
const win = window.open("about:blank");
const html = `
<form id="form1" onsubmit="return false;">
<input type="text" name="uname" value="username">
<input type="password" name="pword" value="${tc.password}">
@ -192,19 +192,19 @@ add_task(async function test_no_save_dialog_when_password_is_fully_munged() {
</form>`;
await loadFormIntoWindow(DEFAULT_ORIGIN, html, win);
await SpecialPowers.spawn(win, [html], function(contentHtml) {
let doc = this.content.document;
for (let field of doc.querySelectorAll("input")) {
let actualValue = field.value;
const doc = this.content.document;
for (const field of doc.querySelectorAll("input")) {
const actualValue = field.value;
field.value = "";
SpecialPowers.wrap(field).setUserInput(actualValue);
}
});
await SpecialPowers.spawn(win, [tc], function(testcase) {
let doc = this.content.document;
const doc = this.content.document;
Assert.equal(doc.querySelector("[name='pword']").value, testcase.password, "Checking for filled password");
});
let formSubmitListener = SpecialPowers.spawn(win, [], function() {
const formSubmitListener = SpecialPowers.spawn(win, [], function() {
return new Promise(resolve => {
this.content.windowRoot.addEventListener(
"PasswordManager:ShowDoorhanger",
@ -220,7 +220,7 @@ add_task(async function test_no_save_dialog_when_password_is_fully_munged() {
this.content.document.getElementById("submitBtn").click();
});
let dialogRequested = await formSubmitListener;
const dialogRequested = await formSubmitListener;
is(dialogRequested, tc.shouldShowPrompt, "Verify 'show save/update prompt' message sent to parent process");
@ -232,18 +232,18 @@ add_task(async function test_no_save_dialog_when_password_is_fully_munged() {
add_task(async function test_no_autofill_munged_username_matching_password() {
// run this test with 2 matching logins from this origin so we don't autofill
await add2logins();
let allLogins = await LoginManager.getAllLogins();
let matchingLogins = Array.prototype.filter.call(allLogins, l => l.origin == DEFAULT_ORIGIN);
const allLogins = await LoginManager.getAllLogins();
const matchingLogins = Array.prototype.filter.call(allLogins, l => l.origin == DEFAULT_ORIGIN);
is(matchingLogins.length, 2, "Expected number of matching logins");
let bulletLogin = matchingLogins.find(l => l.username == "real••••user");
const bulletLogin = matchingLogins.find(l => l.username == "real••••user");
ok(bulletLogin, "Found the real••••user login");
let timesUsed = bulletLogin.timesUsed;
let guid = bulletLogin.guid;
const timesUsed = bulletLogin.timesUsed;
const guid = bulletLogin.guid;
let win = window.open("about:blank");
let html =
const win = window.open("about:blank");
const html =
`<form id="form1" onsubmit="return false;">
<input type="text" name="uname" value="">
<input type="password" name="pword" value="">
@ -251,36 +251,36 @@ add_task(async function test_no_autofill_munged_username_matching_password() {
</form>`;
await loadFormIntoWindow(DEFAULT_ORIGIN, html, win);
await SpecialPowers.spawn(win, [html], function(contentHtml) {
let doc = this.content.document;
for (let field of doc.querySelectorAll("input")) {
let actualValue = field.value;
const doc = this.content.document;
for (const field of doc.querySelectorAll("input")) {
const actualValue = field.value;
field.value = "";
SpecialPowers.wrap(field).setUserInput(actualValue);
}
});
await SpecialPowers.spawn(win, [], function() {
let doc = this.content.document;
const doc = this.content.document;
Assert.equal(doc.querySelector("[name='uname']").value, "", "Check username didn't get autofilled");
SpecialPowers.wrap(doc.querySelector("[name='uname']")).setUserInput("real••••user");
SpecialPowers.wrap(doc.querySelector("[name='pword']")).setUserInput("pass1");
});
// we shouldn't get the save password doorhanger...
let popupShownPromise = noPopupBy();
const popupShownPromise = noPopupBy();
// Check data sent via PasswordManager:onFormSubmit
let processedPromise = getSubmitMessage();
const processedPromise = getSubmitMessage();
await SpecialPowers.spawn(win, [], function() {
this.content.document.getElementById("submitBtn").click();
});
let { data } = await processedPromise;
const { data } = await processedPromise;
info("Got submitted result: " + JSON.stringify(data));
is(data.usernameField, null, "Check usernameField");
let updatedLogins = await LoginManager.getAllLogins();
let updatedLogin = Array.prototype.find.call(updatedLogins, l => l.guid == guid);
const updatedLogins = await LoginManager.getAllLogins();
const updatedLogin = Array.prototype.find.call(updatedLogins, l => l.guid == guid);
ok(updatedLogin, "Got the login via guid");
is(updatedLogin.timesUsed, timesUsed + 1, "timesUsed was incremented");
@ -295,19 +295,19 @@ add_task(async function test_autofill_munged_username_matching_password() {
// only a single matching login so we autofill the username
await addSingleLogin();
let allLogins = await LoginManager.getAllLogins();
let matchingLogins = Array.prototype.filter.call(allLogins, l => l.origin == DEFAULT_ORIGIN);
const allLogins = await LoginManager.getAllLogins();
const matchingLogins = Array.prototype.filter.call(allLogins, l => l.origin == DEFAULT_ORIGIN);
is(matchingLogins.length, 1, "Expected number of matching logins");
info("matched login: " + matchingLogins[0].username);
let bulletLogin = matchingLogins.find(l => l.username == "real••••user");
const bulletLogin = matchingLogins.find(l => l.username == "real••••user");
ok(bulletLogin, "Found the real••••user login");
let timesUsed = bulletLogin.timesUsed;
let guid = bulletLogin.guid;
const timesUsed = bulletLogin.timesUsed;
const guid = bulletLogin.guid;
let win = window.open("about:blank");
let html =
const win = window.open("about:blank");
const html =
`<form id="form1" onsubmit="return false;">
<input type="text" name="uname" value="">
<input type="password" name="pword" value="">
@ -315,35 +315,35 @@ add_task(async function test_autofill_munged_username_matching_password() {
</form>`;
await loadFormIntoWindow(DEFAULT_ORIGIN, html, win);
await SpecialPowers.spawn(win, [html], function(contentHtml) {
let doc = this.content.document;
for (let field of doc.querySelectorAll("input")) {
let actualValue = field.value;
const doc = this.content.document;
for (const field of doc.querySelectorAll("input")) {
const actualValue = field.value;
field.value = "";
SpecialPowers.wrap(field).setUserInput(actualValue);
}
});
await SpecialPowers.spawn(win, [], function() {
let doc = this.content.document;
const doc = this.content.document;
Assert.equal(doc.querySelector("[name='uname']").value, "real••••user", "Check username did get autofilled");
doc.querySelector("[name='pword']").setUserInput("pass1");
});
// we shouldn't get the save/update password doorhanger as it didn't change
let popupShownPromise = noPopupBy();
const popupShownPromise = noPopupBy();
// Check data sent via PasswordManager:onFormSubmit
let processedPromise = getSubmitMessage();
const processedPromise = getSubmitMessage();
await SpecialPowers.spawn(win, [], function() {
this.content.document.getElementById("submitBtn").click();
});
let { data } = await processedPromise;
const { data } = await processedPromise;
info("Got submitted result: " + JSON.stringify(data));
is(data.usernameField, null, "Check usernameField");
let updatedLogins = await LoginManager.getAllLogins();
let updatedLogin = Array.prototype.find.call(updatedLogins, l => l.guid == guid);
const updatedLogins = await LoginManager.getAllLogins();
const updatedLogin = Array.prototype.find.call(updatedLogins, l => l.guid == guid);
ok(updatedLogin, "Got the login via guid");
is(updatedLogin.timesUsed, timesUsed + 1, "timesUsed was incremented");

View File

@ -23,31 +23,20 @@ Login Manager test: primary password.
// Force parent to not look for tab-modal prompts, as they're not used for auth prompts.
modalType = Ci.nsIPrompt.MODAL_TYPE_WINDOW;
var exampleCom = "https://example.com/tests/toolkit/components/passwordmgr/test/mochitest/";
var exampleOrg = "https://example.org/tests/toolkit/components/passwordmgr/test/mochitest/";
const exampleCom = "https://example.com/tests/toolkit/components/passwordmgr/test/mochitest/";
const exampleOrg = "https://example.org/tests/toolkit/components/passwordmgr/test/mochitest/";
gTestDependsOnDeprecatedLogin = true;
var chromeScript = runChecksAfterCommonInit();
const chromeScript = runChecksAfterCommonInit();
runInParent(() => {
var nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1", Ci.nsILoginInfo);
var login1 = new nsLoginInfo();
var login2 = new nsLoginInfo();
login1.init("https://example.com", "https://example.com", null,
"user1", "pass1", "uname", "pword");
login2.init("https://example.org", "https://example.org", null,
"user2", "pass2", "uname", "pword");
Services.logins.addLogin(login1);
Services.logins.addLogin(login2);
});
let win = window.open("about:blank");
const win = window.open("about:blank");
SimpleTest.registerCleanupFunction(() => win.close());
add_setup(async () => {
await addLoginsInParent(
["https://example.com", "https://example.com", null, "user1", "pass1", "uname", "pword"],
["https://example.org", "https://example.org", null, "user2", "pass2", "uname", "pword"]
);
ok(await isLoggedIn(), "should be initially logged in (no PP)");
enablePrimaryPassword();
ok(!await isLoggedIn(), "should be logged out after setting PP");
@ -55,7 +44,7 @@ add_setup(async () => {
add_task(async function test_1() {
// Trigger a MP prompt via the API
var state = {
const state = {
msg: "Please enter your Primary Password.",
title: "the title",
textValue: "",
@ -70,13 +59,13 @@ add_task(async function test_1() {
focused: "passField",
defButton: "button0",
};
var action = {
const action = {
buttonClick: "ok",
passField: LoginTestUtils.primaryPassword.primaryPassword,
};
var promptDone = handlePrompt(state, action);
const promptDone = handlePrompt(state, action);
var logins = await LoginManager.getAllLogins();
const logins = await LoginManager.getAllLogins();
await promptDone;
is(logins.length, 3, "expected number of logins");
@ -88,7 +77,7 @@ add_task(async function test_1() {
add_task(async function test_2() {
// Try again but click cancel.
var state = {
const state = {
msg: "Please enter your Primary Password.",
title: "the title",
textValue: "",
@ -103,19 +92,19 @@ add_task(async function test_2() {
focused: "passField",
defButton: "button0",
};
var action = {
const action = {
buttonClick: "cancel",
};
var promptDone = handlePrompt(state, action);
const promptDone = handlePrompt(state, action);
var logins = await LoginManager.getAllLogins().catch(() => {});
const logins = await LoginManager.getAllLogins().catch(() => {});
await promptDone;
is(logins, undefined, "shouldn't have gotten logins");
ok(!await isLoggedIn(), "should still be logged out");
});
add_task(async function test_3() {
var state = {
const state = {
msg: "Please enter your Primary Password.",
title: "the title",
textValue: "",
@ -130,13 +119,13 @@ add_task(async function test_3() {
focused: "passField",
defButton: "button0",
};
var action = {
const action = {
buttonClick: "ok",
passField: LoginTestUtils.primaryPassword.primaryPassword,
};
var promptDone = handlePrompt(state, action);
const promptDone = handlePrompt(state, action);
var fillPromise = promiseFormsProcessed();
const fillPromise = promiseFormsProcessed();
info("Load a single window to trigger a MP");
await SimpleTest.promiseFocus(win, true);
@ -150,8 +139,8 @@ add_task(async function test_3() {
// check contents of win fields
await SpecialPowers.spawn(win, [], function() {
var u = this.content.document.getElementById("userfield");
var p = this.content.document.getElementById("passfield");
const u = this.content.document.getElementById("userfield");
const p = this.content.document.getElementById("passfield");
Assert.equal(u.value, "user1", "checking expected user to have been filled in");
Assert.equal(p.value, "pass1", "checking expected pass to have been filled in");
u.value = "";
@ -164,7 +153,7 @@ add_task(async function test_3() {
});
add_task(async function test_4() {
var state = {
const state = {
msg: "Please enter your Primary Password.",
title: "the title",
textValue: "",
@ -179,10 +168,10 @@ add_task(async function test_4() {
focused: "passField",
defButton: "button0",
};
var action = {
let action = {
buttonClick: "none",
};
var promptDone = handlePrompt(state, action);
const promptDone = handlePrompt(state, action);
// first part of loading 2 MP-triggering windows
await SimpleTest.promiseFocus(win);
@ -192,8 +181,8 @@ add_task(async function test_4() {
// check contents of win fields
await SpecialPowers.spawn(win, [], function() {
var u = this.content.document.getElementById("userfield");
var p = this.content.document.getElementById("passfield");
const u = this.content.document.getElementById("userfield");
const p = this.content.document.getElementById("passfield");
Assert.equal(u.value, "", "checking expected empty user");
Assert.equal(p.value, "", "checking expected empty pass");
});
@ -208,10 +197,10 @@ add_task(async function test_4() {
// Since the Primary Password prompt is open, we can't focus another tab
// to load the second form. Instead, we load the same form into an iframe.
let url = exampleOrg + "subtst_primary_pass.html";
const url = exampleOrg + "subtst_primary_pass.html";
await SpecialPowers.spawn(win, [url], async function(urlF) {
let iframe = this.content.document.querySelector("iframe");
var loadPromise = new Promise(resolve => {
const iframe = this.content.document.querySelector("iframe");
const loadPromise = new Promise(resolve => {
iframe.addEventListener("load", function onload() {
resolve();
}, { once: true });
@ -229,8 +218,8 @@ add_task(async function test_4() {
// (incorrectly) fill in the form. Note, we cannot use setTimeout()
// here because the modal window suspends all window timers. Instead we
// must use a chrome script to use nsITimer directly.
let chromeURL = SimpleTest.getTestFileURL("chrome_timeout.js");
let script = SpecialPowers.loadChromeScript(chromeURL);
const chromeURL = SimpleTest.getTestFileURL("chrome_timeout.js");
const script = SpecialPowers.loadChromeScript(chromeURL);
script.addMessageListener("ready", _ => {
script.sendAsyncMessage("setTimeout", { delay: 500 });
});
@ -242,10 +231,10 @@ add_task(async function test_4() {
// check contents of iframe fields
await SpecialPowers.spawn(win, [], function() {
let iframe = this.content.document.querySelector("iframe");
let frameDoc = iframe.contentDocument;
var u = frameDoc.getElementById("userfield");
var p = frameDoc.getElementById("passfield");
const iframe = this.content.document.querySelector("iframe");
const frameDoc = iframe.contentDocument;
const u = frameDoc.getElementById("userfield");
const p = frameDoc.getElementById("passfield");
Assert.equal(u.value, "", "checking expected empty user");
Assert.equal(p.value, "", "checking expected empty pass");
});
@ -254,7 +243,7 @@ add_task(async function test_4() {
ok(!await isLoggedIn(), "should be logged out");
// Ok, now enter the MP. The MP prompt is already up.
var fillPromise = promiseFormsProcessed(2);
const fillPromise = promiseFormsProcessed(2);
// fill existing MP dialog with MP.
action = {
@ -272,8 +261,8 @@ add_task(async function test_4() {
// check contents of win fields
await SpecialPowers.spawn(win, [], function() {
var u = this.content.document.getElementById("userfield");
var p = this.content.document.getElementById("passfield");
const u = this.content.document.getElementById("userfield");
const p = this.content.document.getElementById("passfield");
Assert.equal(u.value, "user2", "checking expected user to have been filled in");
Assert.equal(p.value, "pass2", "checking expected pass to have been filled in");
@ -284,10 +273,10 @@ add_task(async function test_4() {
// check contents of iframe fields
await SpecialPowers.spawn(win, [], function() {
let iframe = this.content.document.querySelector("iframe");
let frameDoc = iframe.contentDocument;
var u = frameDoc.getElementById("userfield");
var p = frameDoc.getElementById("passfield");
const iframe = this.content.document.querySelector("iframe");
const frameDoc = iframe.contentDocument;
const u = frameDoc.getElementById("userfield");
const p = frameDoc.getElementById("passfield");
Assert.equal(u.value, "user2", "checking expected user to have been filled in");
Assert.equal(p.value, "pass2", "checking expected pass to have been filled in");

View File

@ -47,44 +47,15 @@ let prompter1 = new PrompterProxy(prompterParent);
const defaultTitle = "the title";
const defaultMsg = "the message";
function initLogins() {
var login1, login2A, login2B, login2C, login2D, login2E;
login1 = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login2A = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login2B = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login2C = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login2D = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login2E = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login1.init("http://example.com", null, "http://example.com",
"", "examplepass", "", "");
login2A.init("http://example2.com", null, "http://example2.com",
"user1name", "user1pass", "", "");
login2B.init("http://example2.com", null, "http://example2.com",
"user2name", "user2pass", "", "");
login2C.init("http://example2.com", null, "http://example2.com",
"user3.name@host", "user3pass", "", "");
login2D.init("http://example2.com", null, "http://example2.com",
"100@beef", "user3pass", "", "");
login2E.init("http://example2.com", null, "http://example2.com",
"100%beef", "user3pass", "", "");
Services.logins.addLogin(login1);
Services.logins.addLogin(login2A);
Services.logins.addLogin(login2B);
Services.logins.addLogin(login2C);
Services.logins.addLogin(login2D);
Services.logins.addLogin(login2E);
}
add_setup(async () => {
runInParent(initLogins);
await addLoginsInParent(
["http://example.com", null, "http://example.com", "", "examplepass", "", ""],
["http://example2.com", null, "http://example2.com", "user1name", "user1pass", "", ""],
["http://example2.com", null, "http://example2.com", "user2name", "user2pass", "", ""],
["http://example2.com", null, "http://example2.com", "user3.name@host", "user3pass", "", ""],
["http://example2.com", null, "http://example2.com", "100@beef", "user3pass", "", ""],
["http://example2.com", null, "http://example2.com", "100%beef", "user3pass", "", ""]
);
});
add_task(async function test_prompt_accept() {

View File

@ -24,49 +24,18 @@ modalType = authPromptModalType;
const AUTHENTICATE_PATH = new URL("authenticate.sjs", window.location.href).pathname;
runInParent(() => {
let login3A, login3B, login4;
login3A = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login3B = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login4 = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
let httpUpgradeLogin = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
let httpsDowngradeLogin = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
let dedupeHttpUpgradeLogin = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
let dedupeHttpsUpgradeLogin = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login3A.init("http://mochi.test:8888", null, "mochitest",
"mochiuser1", "mochipass1", "", "");
login3B.init("http://mochi.test:8888", null, "mochitest2",
"mochiuser2", "mochipass2", "", "");
login4.init("http://mochi.test:8888", null, "mochitest3",
"mochiuser3", "mochipass3-old", "", "");
// Logins to test scheme upgrades (allowed) and downgrades (disallowed)
httpUpgradeLogin.init("http://example.com", null, "schemeUpgrade",
"httpUser", "httpPass", "", "");
httpsDowngradeLogin.init("https://example.com", null, "schemeDowngrade",
"httpsUser", "httpsPass", "", "");
// HTTP and HTTPS version of the same domain and realm but with different passwords.
dedupeHttpUpgradeLogin.init("http://example.org", null, "schemeUpgradeDedupe",
"dedupeUser", "httpPass", "", "");
dedupeHttpsUpgradeLogin.init("https://example.org", null, "schemeUpgradeDedupe",
"dedupeUser", "httpsPass", "", "");
Services.logins.addLogin(login3A);
Services.logins.addLogin(login3B);
Services.logins.addLogin(login4);
Services.logins.addLogin(httpUpgradeLogin);
Services.logins.addLogin(httpsDowngradeLogin);
Services.logins.addLogin(dedupeHttpUpgradeLogin);
Services.logins.addLogin(dedupeHttpsUpgradeLogin);
add_setup(async () => {
await addLoginsInParent(
["http://mochi.test:8888", null, "mochitest", "mochiuser1", "mochipass1", "", ""],
["http://mochi.test:8888", null, "mochitest2", "mochiuser2", "mochipass2", "", ""],
["http://mochi.test:8888", null, "mochitest3", "mochiuser3", "mochipass3-old", "", ""],
// Logins to test scheme upgrades (allowed) and downgrades (disallowed)
["http://example.com", null, "schemeUpgrade", "httpUser", "httpPass", "", ""],
["https://example.com", null, "schemeDowngrade", "httpsUser", "httpsPass", "", ""],
// HTTP and HTTPS version of the same domain and realm but with different passwords.
["http://example.org", null, "schemeUpgradeDedupe", "dedupeUser", "httpPass", "", ""],
["https://example.org", null, "schemeUpgradeDedupe", "dedupeUser", "httpsPass", "", ""]
);
});
add_task(async function test_iframe() {
@ -282,7 +251,7 @@ add_task(async function test_schemeUpgrade() {
});
add_task(async function test_schemeDowngrade() {
let state = {
const state = {
msg: "This site is asking you to sign in. Warning: Your login information " +
"will be shared with example.com, not the website you are currently visiting.",
title: "Authentication Required",
@ -298,14 +267,14 @@ add_task(async function test_schemeDowngrade() {
focused: "textField",
defButton: "button0",
};
let action = {
const action = {
buttonClick: "cancel",
};
let promptDone = handlePrompt(state, action);
const promptDone = handlePrompt(state, action);
// The following tests are driven by iframe loads
let iframeLoaded = onloadPromiseFor("iframe");
const iframeLoaded = onloadPromiseFor("iframe");
iframe.src = "http://example.com" + AUTHENTICATE_PATH +
"?user=unused&pass=unused&realm=schemeDowngrade";
await promptDone;
@ -313,7 +282,7 @@ add_task(async function test_schemeDowngrade() {
});
add_task(async function test_schemeUpgrade_dedupe() {
let state = {
const state = {
msg: "This site is asking you to sign in. Warning: Your login information " +
"will be shared with example.org, not the website you are currently visiting.",
title: "Authentication Required",
@ -329,14 +298,14 @@ add_task(async function test_schemeUpgrade_dedupe() {
focused: "textField",
defButton: "button0",
};
let action = {
const action = {
buttonClick: "ok",
};
let promptDone = handlePrompt(state, action);
const promptDone = handlePrompt(state, action);
// The following tests are driven by iframe loads
let iframeLoaded = onloadPromiseFor("iframe");
const iframeLoaded = onloadPromiseFor("iframe");
iframe.src = "https://example.org" + AUTHENTICATE_PATH +
"?user=dedupeUser&pass=httpsPass&realm=schemeUpgradeDedupe";
await promptDone;

View File

@ -21,21 +21,13 @@
modalType = authPromptModalType;
add_setup(async () => {
let loginAddedPromise = promiseStorageChanged(["addLogin"]);
runInParent(() => {
let login = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login.init("http://mochi.test:8888", null, "mochitest",
"mochiuser1", "mochipass1", "", "");
Services.logins.addLogin(login);
});
await loginAddedPromise;
await addLoginsInParent(
["http://mochi.test:8888", null, "mochitest", "mochiuser1", "mochipass1", "", ""]
);
});
add_task(async function test_sandbox_xhr() {
let state = {
const state = {
msg: "This site is asking you to sign in.",
title: "Authentication Required",
textValue: "mochiuser1",
@ -50,21 +42,21 @@ add_task(async function test_sandbox_xhr() {
focused: "textField",
defButton: "button0",
};
let action = {
const action = {
buttonClick: "ok",
};
let promptDone = handlePrompt(state, action);
const promptDone = handlePrompt(state, action);
let url = new URL("authenticate.sjs?user=mochiuser1&pass=mochipass1", window.location.href);
let sandboxConstructor = SpecialPowers.Cu.Sandbox;
let sandbox = new sandboxConstructor(this, {wantXrays: true});
const url = new URL("authenticate.sjs?user=mochiuser1&pass=mochipass1", window.location.href);
const sandboxConstructor = SpecialPowers.Cu.Sandbox;
const sandbox = new sandboxConstructor(this, {wantXrays: true});
function sandboxedRequest(sandboxedUrl) {
let req = new XMLHttpRequest();
const req = new XMLHttpRequest();
req.open("GET", sandboxedUrl, true);
req.send(null);
}
let loginModifiedPromise = promiseStorageChanged(["modifyLogin"]);
const loginModifiedPromise = promiseStorageChanged(["modifyLogin"]);
sandbox.sandboxedRequest = sandboxedRequest(url);
info("send the XHR request in the sandbox");
SpecialPowers.Cu.evalInSandbox("sandboxedRequest;", sandbox);

View File

@ -16,11 +16,8 @@
<pre id="test">
<script class="testbody" type="text/javascript">
var state, action;
var isOk;
var level = Ci.nsIAuthPrompt2.LEVEL_NONE;
var authinfo = {
const level = Ci.nsIAuthPrompt2.LEVEL_NONE;
const authinfo = {
username: "",
password: "",
domain: "",
@ -33,15 +30,15 @@ var authinfo = {
// Let prompt_common know what kind of modal type is enabled for auth prompts.
modalType = authPromptModalType;
let prompterParent = runInParent(() => {
const prompterParent = runInParent(() => {
const promptFac = Cc["@mozilla.org/passwordmanager/authpromptfactory;1"].
getService(Ci.nsIPromptFactory);
let chromeWin = Services.wm.getMostRecentWindow("navigator:browser");
let prompter2 = promptFac.getPrompt(chromeWin, Ci.nsIAuthPrompt2);
const chromeWin = Services.wm.getMostRecentWindow("navigator:browser");
const prompter2 = promptFac.getPrompt(chromeWin, Ci.nsIAuthPrompt2);
prompter2.QueryInterface(Ci.nsILoginManagerAuthPrompter).browser = chromeWin.gBrowser.selectedBrowser;
let channels = {};
const channels = {};
channels.channel1 = Services.io.newChannel("http://example.com",
null,
null,
@ -63,58 +60,35 @@ let prompterParent = runInParent(() => {
Ci.nsIContentPolicy.TYPE_OTHER);
addMessageListener("proxyPrompter", function onMessage(msg) {
let args = [...msg.args];
let channelName = args.shift();
const args = [...msg.args];
const channelName = args.shift();
// Replace the channel name string (arg. 0) with the channel by that name.
args.unshift(channels[channelName]);
let rv = prompter2[msg.methodName](...args);
const rv = prompter2[msg.methodName](...args);
return {
rv,
// Send the args back to content so out/inout args can be checked.
args: msg.args,
};
});
let login1, login2A, login2B, login2C, login2D, login2E;
login1 = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login2A = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login2B = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login2C = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login2D = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login2E = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login1.init("http://example.com", null, "http://example.com",
"", "examplepass", "", "");
login2A.init("http://example2.com", null, "http://example2.com",
"user1name", "user1pass", "", "");
login2B.init("http://example2.com", null, "http://example2.com",
"user2name", "user2pass", "", "");
login2C.init("http://example2.com", null, "http://example2.com",
"user3.name@host", "user3pass", "", "");
login2D.init("http://example2.com", null, "http://example2.com",
"100@beef", "user3pass", "", "");
login2E.init("http://example2.com", null, "http://example2.com",
"100%beef", "user3pass", "", "");
Services.logins.addLogin(login1);
Services.logins.addLogin(login2A);
Services.logins.addLogin(login2B);
Services.logins.addLogin(login2C);
Services.logins.addLogin(login2D);
Services.logins.addLogin(login2E);
});
let prompter2 = new PrompterProxy(prompterParent);
const prompter2 = new PrompterProxy(prompterParent);
add_setup(async () => {
await addLoginsInParent(
["http://example.com", null, "http://example.com", "", "examplepass", "", ""],
["http://example2.com", null, "http://example2.com", "user1name", "user1pass", "", ""],
["http://example2.com", null, "http://example2.com", "user2name", "user2pass", "", ""],
["http://example2.com", null, "http://example2.com", "user3.name@host", "user3pass", "", ""],
["http://example2.com", null, "http://example2.com", "100@beef", "user3pass", "", ""],
["http://example2.com", null, "http://example2.com", "100%beef", "user3pass", "", ""]
);
});
add_task(async function test_accept() {
state = {
const state = {
msg: "This site is asking you to sign in.",
title: "Authentication Required",
textValue: "inuser",
@ -129,7 +103,7 @@ add_task(async function test_accept() {
focused: "textField",
defButton: "button0",
};
action = {
const action = {
buttonClick: "ok",
textField: "outuser",
passField: "outpass",
@ -142,7 +116,7 @@ add_task(async function test_accept() {
// Since prompter2 is actually a proxy to send a message to a chrome script and
// we can't send a channel in a message, we instead send the channel name that
// already exists in the chromeScript.
isOk = prompter2.promptAuth("channel1", level, authinfo);
const isOk = prompter2.promptAuth("channel1", level, authinfo);
await promptDone;
ok(isOk, "Checking dialog return value (accept)");
@ -151,7 +125,7 @@ add_task(async function test_accept() {
});
add_task(async function test_cancel() {
state = {
const state = {
msg: "This site is asking you to sign in.",
title: "Authentication Required",
textValue: "outuser",
@ -166,11 +140,11 @@ add_task(async function test_cancel() {
focused: "textField",
defButton: "button0",
};
action = {
const action = {
buttonClick: "cancel",
};
promptDone = handlePrompt(state, action);
isOk = prompter2.promptAuth("channel1", level, authinfo);
const isOk = prompter2.promptAuth("channel1", level, authinfo);
await promptDone;
ok(!isOk, "Checking dialog return value (cancel)");
@ -178,7 +152,7 @@ add_task(async function test_cancel() {
add_task(async function test_pwonly() {
// test filling in password-only login
state = {
const state = {
msg: "This site is asking you to sign in.",
title: "Authentication Required",
textValue: "",
@ -193,7 +167,7 @@ add_task(async function test_pwonly() {
focused: "textField",
defButton: "button0",
};
action = {
const action = {
buttonClick: "ok",
};
authinfo.username = "";
@ -201,7 +175,7 @@ add_task(async function test_pwonly() {
authinfo.realm = "http://example.com";
promptDone = handlePrompt(state, action);
isOk = prompter2.promptAuth("channel1", level, authinfo);
const isOk = prompter2.promptAuth("channel1", level, authinfo);
await promptDone;
ok(isOk, "Checking dialog return value (accept)");
@ -212,7 +186,7 @@ add_task(async function test_pwonly() {
add_task(async function test_multipleExisting() {
// test filling in existing login (undetermined from multiple selection)
// user2name/user2pass would also be valid to fill here.
state = {
const state = {
msg: "This site is asking you to sign in.",
title: "Authentication Required",
textValue: "user1name",
@ -227,7 +201,7 @@ add_task(async function test_multipleExisting() {
focused: "textField",
defButton: "button0",
};
action = {
const action = {
buttonClick: "ok",
};
authinfo.username = "";
@ -235,7 +209,7 @@ add_task(async function test_multipleExisting() {
authinfo.realm = "http://example2.com";
promptDone = handlePrompt(state, action);
isOk = prompter2.promptAuth("channel2", level, authinfo);
const isOk = prompter2.promptAuth("channel2", level, authinfo);
await promptDone;
ok(isOk, "Checking dialog return value (accept)");
@ -246,7 +220,7 @@ add_task(async function test_multipleExisting() {
add_task(async function test_multipleExisting2() {
// test filling in existing login (undetermined --> user1)
// user2name/user2pass would also be valid to fill here.
state = {
const state = {
msg: "This site is asking you to sign in.",
title: "Authentication Required",
textValue: "user1name",
@ -262,7 +236,7 @@ add_task(async function test_multipleExisting2() {
defButton: "button0",
};
// enter one of the known logins, test 504+505 exercise the two possible states.
action = {
const action = {
buttonClick: "ok",
textField: "user1name",
passField: "user1pass",
@ -272,7 +246,7 @@ add_task(async function test_multipleExisting2() {
authinfo.realm = "http://example2.com";
promptDone = handlePrompt(state, action);
isOk = prompter2.promptAuth("channel2", level, authinfo);
const isOk = prompter2.promptAuth("channel2", level, authinfo);
await promptDone;
ok(isOk, "Checking dialog return value (accept)");
@ -283,7 +257,7 @@ add_task(async function test_multipleExisting2() {
add_task(async function test_multipleExisting3() {
// test filling in existing login (undetermined --> user2)
// user2name/user2pass would also be valid to fill here.
state = {
const state = {
msg: "This site is asking you to sign in.",
title: "Authentication Required",
textValue: "user1name",
@ -299,7 +273,7 @@ add_task(async function test_multipleExisting3() {
defButton: "button0",
};
// enter one of the known logins, test 504+505 exercise the two possible states.
action = {
const action = {
buttonClick: "ok",
textField: "user2name",
passField: "user2pass",
@ -309,7 +283,7 @@ add_task(async function test_multipleExisting3() {
authinfo.realm = "http://example2.com";
promptDone = handlePrompt(state, action);
isOk = prompter2.promptAuth("channel2", level, authinfo);
const isOk = prompter2.promptAuth("channel2", level, authinfo);
await promptDone;
ok(isOk, "Checking dialog return value (accept)");
@ -320,7 +294,7 @@ add_task(async function test_multipleExisting3() {
add_task(async function test_changingMultiple() {
// test changing a password (undetermined --> user2 w/ newpass)
// user2name/user2pass would also be valid to fill here.
state = {
const state = {
msg: "This site is asking you to sign in.",
title: "Authentication Required",
textValue: "user1name",
@ -336,7 +310,7 @@ add_task(async function test_changingMultiple() {
defButton: "button0",
};
// force to user2, and change the password
action = {
const action = {
buttonClick: "ok",
textField: "user2name",
passField: "NEWuser2pass",
@ -346,7 +320,7 @@ add_task(async function test_changingMultiple() {
authinfo.realm = "http://example2.com";
promptDone = handlePrompt(state, action);
isOk = prompter2.promptAuth("channel2", level, authinfo);
const isOk = prompter2.promptAuth("channel2", level, authinfo);
await promptDone;
ok(isOk, "Checking dialog return value (accept)");
@ -357,7 +331,7 @@ add_task(async function test_changingMultiple() {
add_task(async function test_changingMultiple2() {
// test changing a password (undetermined --> user2 w/ origpass)
// user2name/user2pass would also be valid to fill here.
state = {
const state = {
msg: "This site is asking you to sign in.",
title: "Authentication Required",
textValue: "user1name",
@ -373,7 +347,7 @@ add_task(async function test_changingMultiple2() {
defButton: "button0",
};
// force to user2, and change the password back
action = {
const action = {
buttonClick: "ok",
textField: "user2name",
passField: "user2pass",
@ -383,7 +357,7 @@ add_task(async function test_changingMultiple2() {
authinfo.realm = "http://example2.com";
promptDone = handlePrompt(state, action);
isOk = prompter2.promptAuth("channel2", level, authinfo);
const isOk = prompter2.promptAuth("channel2", level, authinfo);
await promptDone;
ok(isOk, "Checking dialog return value (accept)");

View File

@ -92,7 +92,7 @@ let chromeScript = runInParent(() => {
onStopRequest(request, status) {}
}
function initLogins(pi) {
async function initLogins(pi) {
mozproxyURL = `moz-proxy://${pi.host}:${pi.port}`;
let proxyLogin = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(
@ -109,7 +109,7 @@ let chromeScript = runInParent(() => {
""
);
Services.logins.addLogin(proxyLogin);
await Services.logins.addLoginAsync(proxyLogin);
}
let resolveCallback = {
@ -126,8 +126,8 @@ let chromeScript = runInParent(() => {
return this;
},
onProxyAvailable(req, uri, pi, status) {
initLogins(pi);
async onProxyAvailable(req, uri, pi, status) {
await initLogins(pi);
// I'm cheating a bit here... We should probably do some magic foo to get
// something implementing nsIProxiedProtocolHandler and then call

View File

@ -12,27 +12,11 @@
</head>
<body>
<script>
let readyPromise = registerRunTests(5);
let chromeScript = runInParent(function chromeSetup() {
let login1A = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
let login2A = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
let login2B = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login1A.init("http://mochi.test:8888", "http://username-focus-1", null,
"testuser1A", "testpass1A", "", "");
login2A.init("http://mochi.test:8888", "http://username-focus-2", null,
"testuser2A", "testpass2A", "", "");
login2B.init("http://mochi.test:8888", "http://username-focus-2", null,
"testuser2B", "testpass2B", "", "");
Services.logins.addLogin(login1A);
Services.logins.addLogin(login2A);
Services.logins.addLogin(login2B);
});
const readyPromise = addLoginsInParent(
["http://mochi.test:8888", "http://username-focus-1", null, "testuser1A", "testpass1A", "", ""],
["http://mochi.test:8888", "http://username-focus-2", null, "testuser2A", "testpass2A", "", ""],
["http://mochi.test:8888", "http://username-focus-2", null, "testuser2B", "testpass2B", "", ""]
).then(() => registerRunTests(5));
</script>
<p id="display"></p>
@ -111,7 +95,7 @@ add_setup(async () => {
});
add_task(async function test_autofilled() {
let usernameField = getFormElementByName("-autofilled", "uname");
const usernameField = getFormElementByName("-autofilled", "uname");
info("Username and password already filled so don't show autocomplete");
await noPopupBy(() => usernameField.focus());
@ -122,7 +106,7 @@ add_task(async function test_autofilled() {
});
add_task(async function test_autofilled_prefilled_un() {
let usernameField = getFormElementByName("-autofilled-prefilled-un", "uname");
const usernameField = getFormElementByName("-autofilled-prefilled-un", "uname");
info("Username and password already filled so don't show autocomplete");
await noPopupBy(() => usernameField.focus());
@ -133,14 +117,14 @@ add_task(async function test_autofilled_prefilled_un() {
});
add_task(async function test_autofilled_focused_dynamic() {
let usernameField = getFormElementByName("-autofilled-focused-dynamic", "uname");
let passwordField = getFormElementByName("-autofilled-focused-dynamic", "pword");
const usernameField = getFormElementByName("-autofilled-focused-dynamic", "uname");
const passwordField = getFormElementByName("-autofilled-focused-dynamic", "pword");
info("Username and password will be filled while username focused");
await noPopupBy(() => usernameField.focus());
info("triggering autofill");
await noPopupBy(() => passwordField.type = "password");
let popupState = await getPopupState();
const popupState = await getPopupState();
is(popupState.open, false, "Check popup is closed");
removeFocus();
@ -152,14 +136,14 @@ add_task(async function test_autofilled_focused_dynamic() {
// Begin testing forms that have multiple saved logins
add_task(async function test_multiple() {
let usernameField = getFormElementByName("-multiple", "uname");
const usernameField = getFormElementByName("-multiple", "uname");
info("Fields not filled due to multiple so autocomplete upon focus");
await popupBy(() => usernameField.focus());
});
add_task(async function test_multiple_dynamic() {
let usernameField = getFormElementByName("-multiple-dynamic", "uname");
let passwordField = getFormElementByName("-multiple-dynamic", "pword");
const usernameField = getFormElementByName("-multiple-dynamic", "uname");
const passwordField = getFormElementByName("-multiple-dynamic", "pword");
info("Fields not filled but username is focused upon marking so open");
await noPopupBy(() => usernameField.focus());
@ -168,7 +152,7 @@ add_task(async function test_multiple_dynamic() {
});
add_task(async function test_multiple_prefilled_un1() {
let usernameField = getFormElementByName("-multiple-prefilled-un1", "uname");
const usernameField = getFormElementByName("-multiple-prefilled-un1", "uname");
info("Username and password already filled so don't show autocomplete");
await noPopupBy(() => usernameField.focus());
@ -179,7 +163,7 @@ add_task(async function test_multiple_prefilled_un1() {
});
add_task(async function test_multiple_prefilled_un2() {
let usernameField = getFormElementByName("-multiple-prefilled-un2", "uname");
const usernameField = getFormElementByName("-multiple-prefilled-un2", "uname");
info("Username and password already filled so don't show autocomplete");
await noPopupBy(() => usernameField.focus());
@ -190,14 +174,14 @@ add_task(async function test_multiple_prefilled_un2() {
});
add_task(async function test_multiple_prefilled_focused_dynamic() {
let usernameField = getFormElementByName("-multiple-prefilled-focused-dynamic", "uname");
let passwordField = getFormElementByName("-multiple-prefilled-focused-dynamic", "pword");
const usernameField = getFormElementByName("-multiple-prefilled-focused-dynamic", "uname");
const passwordField = getFormElementByName("-multiple-prefilled-focused-dynamic", "pword");
info("Username and password will be filled while username focused");
await noPopupBy(() => usernameField.focus());
info("triggering autofill");
await noPopupBy(() => passwordField.type = "password");
let popupState = await getPopupState();
const popupState = await getPopupState();
is(popupState.open, false, "Check popup is closed");
removeFocus();

View File

@ -62,22 +62,11 @@ let prompterParent = runInParent(() => {
let prompter1 = new PrompterProxy(prompterParent);
add_task(function setup() {
runInParent(function initLogins() {
let nsLoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
Ci.nsILoginInfo, "init");
let login1 = new nsLoginInfo("http://mochi.test:8888", null, "xhr",
"xhruser1", "xhrpass1");
let login2 = new nsLoginInfo("http://mochi.test:8888", null, "xhr2",
"xhruser2", "xhrpass2");
try {
Services.logins.addLogin(login1);
Services.logins.addLogin(login2);
} catch (e) {
assert.ok(false, "addLogin threw: " + e);
}
});
add_setup(async () => {
await addLoginsInParent(
["http://mochi.test:8888", null, "xhr", "xhruser1", "xhrpass1"],
["http://mochi.test:8888", null, "xhr2", "xhruser2", "xhrpass2"]
);
});
add_task(async function test1() {

View File

@ -1,4 +1,4 @@
let { LoginManagerPrompter } = ChromeUtils.importESModule(
const { LoginManagerPrompter } = ChromeUtils.importESModule(
"resource://gre/modules/LoginManagerPrompter.sys.mjs"
);
@ -110,28 +110,27 @@ function _setPrefs() {
});
}
function _saveLogins(logins) {
logins
.map(loginData => {
let login;
if (loginData.isAuth) {
login = TestData.authLogin({
origin: loginData.origin ?? "https://example.com",
httpRealm: "example-realm",
username: loginData.username,
password: loginData.password,
});
} else {
login = TestData.formLogin({
origin: loginData.origin ?? "https://example.com",
formActionOrigin: "https://example.com",
username: loginData.username,
password: loginData.password,
});
}
return login;
})
.forEach(login => Services.logins.addLogin(login));
async function _saveLogins(loginDatas) {
const logins = loginDatas.map(loginData => {
let login;
if (loginData.isAuth) {
login = TestData.authLogin({
origin: loginData.origin ?? "https://example.com",
httpRealm: "example-realm",
username: loginData.username,
password: loginData.password,
});
} else {
login = TestData.formLogin({
origin: loginData.origin ?? "https://example.com",
formActionOrigin: "https://example.com",
username: loginData.username,
password: loginData.password,
});
}
return login;
});
await Services.logins.addLogins(logins);
}
function _compare(expectedArr, actualArr) {
@ -142,8 +141,8 @@ function _compare(expectedArr, actualArr) {
"Expect expectedArr and actualArr to be the same length"
);
for (let i = 0; i < expectedArr.length; i++) {
let expected = expectedArr[i];
let actual = actualArr[i];
const expected = expectedArr[i];
const actual = actualArr[i];
Assert.ok(
expected.text == actual.text,
@ -159,7 +158,7 @@ function _compare(expectedArr, actualArr) {
async function _test(testCase) {
info(`Starting test case: ${testCase.description}`);
info(`Storing saved logins: ${JSON.stringify(testCase.savedLogins)}`);
_saveLogins(testCase.savedLogins);
await _saveLogins(testCase.savedLogins);
if (!testCase.isLoggedIn) {
// Primary Password should be enabled and locked
@ -167,7 +166,7 @@ async function _test(testCase) {
}
info("Computing results");
let result = await LoginManagerPrompter._getUsernameSuggestions(
const result = await LoginManagerPrompter._getUsernameSuggestions(
LOGIN,
testCase.possibleUsernames
);
@ -183,7 +182,7 @@ async function _test(testCase) {
add_task(async function test_LoginManagerPrompter_getUsernameSuggestions() {
_setPrefs();
for (let tc of TEST_CASES) {
for (const tc of TEST_CASES) {
await _test(tc);
}
});

View File

@ -252,9 +252,7 @@ function authLogin(modifications = {}) {
async function runTestcase({ formOrigin, savedLogins, expectedItems }) {
const DOCUMENT_CONTENT = "<form><input id='pw' type=password></form>";
for (let login of savedLogins) {
Services.logins.addLogin(login);
}
await Services.logins.addLogins(savedLogins);
// Create the logins menuitems fragment.
let { fragment, document } = createLoginsFragment(

View File

@ -41,24 +41,27 @@
* Adds a login with an empty formActionOrigin, then it verifies that no other
* form logins can be added for the same host.
*/
add_task(function test_addLogin_wildcard() {
add_task(async function test_addLogin_wildcard() {
let loginInfo = TestData.formLogin({
origin: "http://any.example.com",
formActionOrigin: "",
});
Services.logins.addLogin(loginInfo);
await Services.logins.addLoginAsync(loginInfo);
// Normal form logins cannot be added anymore.
loginInfo = TestData.formLogin({ origin: "http://any.example.com" });
Assert.throws(() => Services.logins.addLogin(loginInfo), /already exists/);
await Assert.rejects(
Services.logins.addLoginAsync(loginInfo),
/already exists/
);
// Authentication logins can still be added.
loginInfo = TestData.authLogin({ origin: "http://any.example.com" });
Services.logins.addLogin(loginInfo);
await Services.logins.addLoginAsync(loginInfo);
// Form logins can be added for other hosts.
loginInfo = TestData.formLogin({ origin: "http://other.example.com" });
Services.logins.addLogin(loginInfo);
await Services.logins.addLoginAsync(loginInfo);
});
/**

View File

@ -16,27 +16,27 @@
/**
* Tests legacy validation with addLogin.
*/
add_task(function test_addLogin_invalid_characters_legacy() {
add_task(async function test_addLogin_invalid_characters_legacy() {
// Test newlines and carriage returns in properties that contain URLs.
for (let testValue of [
"http://newline\n.example.com",
"http://carriagereturn.example.com\r",
]) {
let loginInfo = TestData.formLogin({ origin: testValue });
Assert.throws(
() => Services.logins.addLogin(loginInfo),
await Assert.rejects(
Services.logins.addLoginAsync(loginInfo),
/login values can't contain newlines/
);
loginInfo = TestData.formLogin({ formActionOrigin: testValue });
Assert.throws(
() => Services.logins.addLogin(loginInfo),
await Assert.rejects(
Services.logins.addLoginAsync(loginInfo),
/login values can't contain newlines/
);
loginInfo = TestData.authLogin({ httpRealm: testValue });
Assert.throws(
() => Services.logins.addLogin(loginInfo),
await Assert.rejects(
Services.logins.addLoginAsync(loginInfo),
/login values can't contain newlines/
);
}
@ -44,35 +44,35 @@ add_task(function test_addLogin_invalid_characters_legacy() {
// Test newlines and carriage returns in form field names.
for (let testValue of ["newline_field\n", "carriagereturn\r_field"]) {
let loginInfo = TestData.formLogin({ usernameField: testValue });
Assert.throws(
() => Services.logins.addLogin(loginInfo),
await Assert.rejects(
Services.logins.addLoginAsync(loginInfo),
/login values can't contain newlines/
);
loginInfo = TestData.formLogin({ passwordField: testValue });
Assert.throws(
() => Services.logins.addLogin(loginInfo),
await Assert.rejects(
Services.logins.addLoginAsync(loginInfo),
/login values can't contain newlines/
);
}
// Test a single dot as the value of usernameField and formActionOrigin.
let loginInfo = TestData.formLogin({ usernameField: "." });
Assert.throws(
() => Services.logins.addLogin(loginInfo),
await Assert.rejects(
Services.logins.addLoginAsync(loginInfo),
/login values can't be periods/
);
loginInfo = TestData.formLogin({ formActionOrigin: "." });
Assert.throws(
() => Services.logins.addLogin(loginInfo),
await Assert.rejects(
Services.logins.addLoginAsync(loginInfo),
/login values can't be periods/
);
// Test the sequence " (" inside the value of the "origin" property.
loginInfo = TestData.formLogin({ origin: "http://parens (.example.com" });
Assert.throws(
() => Services.logins.addLogin(loginInfo),
await Assert.rejects(
Services.logins.addLoginAsync(loginInfo),
/bad parens in origin/
);
});

View File

@ -23,14 +23,17 @@ const MAX_DATE_MS = 8640000000000000;
* This argument is passed to the "Assert.throws" test to determine which
* error is expected from the modification functions.
*/
function checkLoginInvalid(aLoginInfo, aExpectedError) {
async function checkLoginInvalid(aLoginInfo, aExpectedError) {
// Try to add the new login, and verify that no data is stored.
Assert.throws(() => Services.logins.addLogin(aLoginInfo), aExpectedError);
await Assert.rejects(
Services.logins.addLoginAsync(aLoginInfo),
aExpectedError
);
LoginTestUtils.checkLogins([]);
// Add a login for the modification tests.
let testLogin = TestData.formLogin({ origin: "http://modify.example.com" });
Services.logins.addLogin(testLogin);
await Services.logins.addLoginAsync(testLogin);
// Try to modify the existing login using nsILoginInfo and nsIPropertyBag.
Assert.throws(
@ -87,16 +90,17 @@ function compareAttributes(objectA, objectB, attributes) {
/**
* Tests that adding logins to the database works.
*/
add_task(function test_addLogin_removeLogin() {
add_task(async function test_addLogin_removeLogin() {
// Each login from the test data should be valid and added to the list.
for (let loginInfo of TestData.loginList()) {
Services.logins.addLogin(loginInfo);
}
await Services.logins.addLogins(TestData.loginList());
LoginTestUtils.checkLogins(TestData.loginList());
// Trying to add each login again should result in an error.
for (let loginInfo of TestData.loginList()) {
Assert.throws(() => Services.logins.addLogin(loginInfo), /already exists/);
await Assert.rejects(
Services.logins.addLoginAsync(loginInfo),
/This login already exists./
);
}
// Removing each login should succeed.
@ -183,64 +187,70 @@ add_task(async function event_data_includes_plaintext_username_and_password() {
* The legacy case of an empty string in formActionOrigin and a null value in
* httpRealm is also supported for storage at the moment.
*/
add_task(function test_invalid_httpRealm_formActionOrigin() {
add_task(async function test_invalid_httpRealm_formActionOrigin() {
// httpRealm === null, formActionOrigin === null
checkLoginInvalid(
await checkLoginInvalid(
TestData.formLogin({ formActionOrigin: null }),
/without a httpRealm or formActionOrigin/
);
// httpRealm === "", formActionOrigin === null
checkLoginInvalid(
await checkLoginInvalid(
TestData.authLogin({ httpRealm: "" }),
/without a httpRealm or formActionOrigin/
);
// httpRealm === null, formActionOrigin === ""
// TODO: This is not enforced for now.
// checkLoginInvalid(TestData.formLogin({ formActionOrigin: "" }),
// await checkLoginInvalid(TestData.formLogin({ formActionOrigin: "" }),
// /without a httpRealm or formActionOrigin/);
// httpRealm === "", formActionOrigin === ""
let login = TestData.formLogin({ formActionOrigin: "" });
login.httpRealm = "";
checkLoginInvalid(login, /both a httpRealm and formActionOrigin/);
await checkLoginInvalid(login, /both a httpRealm and formActionOrigin/);
// !!httpRealm, !!formActionOrigin
login = TestData.formLogin();
login.httpRealm = "The HTTP Realm";
checkLoginInvalid(login, /both a httpRealm and formActionOrigin/);
await checkLoginInvalid(login, /both a httpRealm and formActionOrigin/);
// httpRealm === "", !!formActionOrigin
login = TestData.formLogin();
login.httpRealm = "";
checkLoginInvalid(login, /both a httpRealm and formActionOrigin/);
await checkLoginInvalid(login, /both a httpRealm and formActionOrigin/);
// !!httpRealm, formActionOrigin === ""
login = TestData.authLogin();
login.formActionOrigin = "";
checkLoginInvalid(login, /both a httpRealm and formActionOrigin/);
await checkLoginInvalid(login, /both a httpRealm and formActionOrigin/);
});
/**
* Tests null or empty values in required login properties.
*/
add_task(function test_missing_properties() {
checkLoginInvalid(
add_task(async function test_missing_properties() {
await checkLoginInvalid(
TestData.formLogin({ origin: null }),
/null or empty origin/
);
checkLoginInvalid(TestData.formLogin({ origin: "" }), /null or empty origin/);
await checkLoginInvalid(
TestData.formLogin({ origin: "" }),
/null or empty origin/
);
checkLoginInvalid(TestData.formLogin({ username: null }), /null username/);
await checkLoginInvalid(
TestData.formLogin({ username: null }),
/null username/
);
checkLoginInvalid(
await checkLoginInvalid(
TestData.formLogin({ password: null }),
/null or empty password/
);
checkLoginInvalid(
await checkLoginInvalid(
TestData.formLogin({ password: "" }),
/null or empty password/
);
@ -249,7 +259,7 @@ add_task(function test_missing_properties() {
/**
* Tests invalid NUL characters in nsILoginInfo properties.
*/
add_task(function test_invalid_characters() {
add_task(async function test_invalid_characters() {
let loginList = [
TestData.authLogin({ origin: "http://null\0X.example.com" }),
TestData.authLogin({ httpRealm: "realm\0" }),
@ -261,7 +271,7 @@ add_task(function test_invalid_characters() {
TestData.formLogin({ password: "pass\0word" }),
];
for (let loginInfo of loginList) {
checkLoginInvalid(loginInfo, /login values can't contain nulls/);
await checkLoginInvalid(loginInfo, /login values can't contain nulls/);
}
});
@ -278,10 +288,9 @@ add_task(function test_removeLogin_nonexisting() {
/**
* Tests removing all logins at once.
*/
add_task(function test_removeAllUserFacingLogins() {
for (let loginInfo of TestData.loginList()) {
Services.logins.addLogin(loginInfo);
}
add_task(async function test_removeAllUserFacingLogins() {
await Services.logins.addLogins(TestData.loginList());
Services.logins.removeAllUserFacingLogins();
LoginTestUtils.checkLogins([]);
@ -292,7 +301,7 @@ add_task(function test_removeAllUserFacingLogins() {
/**
* Tests the modifyLogin function with an nsILoginInfo argument.
*/
add_task(function test_modifyLogin_nsILoginInfo() {
add_task(async function test_modifyLogin_nsILoginInfo() {
let loginInfo = TestData.formLogin();
let updatedLoginInfo = TestData.formLogin({
username: "new username",
@ -309,7 +318,7 @@ add_task(function test_modifyLogin_nsILoginInfo() {
);
// Add the first form login, then modify it to match the second.
Services.logins.addLogin(loginInfo);
await Services.logins.addLoginAsync(loginInfo);
Services.logins.modifyLogin(loginInfo, updatedLoginInfo);
// The data should now match the second login.
@ -324,7 +333,7 @@ add_task(function test_modifyLogin_nsILoginInfo() {
LoginTestUtils.checkLogins([differentLoginInfo]);
// It is now possible to add a login with the old type and origin.
Services.logins.addLogin(loginInfo);
await Services.logins.addLoginAsync(loginInfo);
LoginTestUtils.checkLogins([loginInfo, differentLoginInfo]);
// Modifying a login to match an existing one should not be possible.
@ -340,7 +349,7 @@ add_task(function test_modifyLogin_nsILoginInfo() {
/**
* Tests the modifyLogin function with an nsIPropertyBag argument.
*/
add_task(function test_modifyLogin_nsIProperyBag() {
add_task(async function test_modifyLogin_nsIProperyBag() {
let loginInfo = TestData.formLogin();
let updatedLoginInfo = TestData.formLogin({
username: "new username",
@ -367,7 +376,7 @@ add_task(function test_modifyLogin_nsIProperyBag() {
// Add the first form login, then modify it to match the second, changing
// only some of its properties and checking the behavior with an empty string.
Services.logins.addLogin(loginInfo);
await Services.logins.addLoginAsync(loginInfo);
Services.logins.modifyLogin(
loginInfo,
newPropertyBag({
@ -405,7 +414,7 @@ add_task(function test_modifyLogin_nsIProperyBag() {
LoginTestUtils.checkLogins([differentLoginInfo]);
// It is now possible to add a login with the old type and origin.
Services.logins.addLogin(loginInfo);
await Services.logins.addLoginAsync(loginInfo);
LoginTestUtils.checkLogins([loginInfo, differentLoginInfo]);
// Modifying a login to match an existing one should not be possible.
@ -509,7 +518,7 @@ add_task(function test_deduplicate_keeps_most_recent() {
/**
* Tests handling when adding a login with bad date values
*/
add_task(function test_addLogin_badDates() {
add_task(async function test_addLogin_badDates() {
LoginTestUtils.clearData();
let now = Date.now();
@ -524,7 +533,7 @@ add_task(function test_addLogin_badDates() {
Assert.ok(!defaultsLogin[pname]);
}
Assert.ok(
!!Services.logins.addLogin(defaultsLogin),
!!(await Services.logins.addLoginAsync(defaultsLogin)),
"Sanity check adding defaults formLogin"
);
Services.logins.removeAllUserFacingLogins();
@ -537,7 +546,7 @@ add_task(function test_addLogin_badDates() {
})
);
Assert.ok(
!!Services.logins.addLogin(loginInfo),
!!(await Services.logins.addLoginAsync(loginInfo)),
"Check 0 value for " + pname
);
Services.logins.removeAllUserFacingLogins();
@ -551,7 +560,7 @@ add_task(function test_addLogin_badDates() {
})
);
Assert.ok(
!!Services.logins.addLogin(loginInfo),
!!(await Services.logins.addLoginAsync(loginInfo)),
"Check -1 value for " + pname
);
Services.logins.removeAllUserFacingLogins();
@ -564,8 +573,8 @@ add_task(function test_addLogin_badDates() {
[pname]: MAX_DATE_MS + 1,
})
);
Assert.throws(
() => Services.logins.addLogin(loginInfo),
await Assert.rejects(
Services.logins.addLoginAsync(loginInfo),
/invalid date properties/
);
Assert.equal(Services.logins.getAllLogins().length, 0);
@ -583,33 +592,35 @@ add_task(async function test_addLogins_badDates() {
let defaultsLogin = TestData.formLogin({
username: "defaults",
});
await Services.logins.addLoginAsync(defaultsLogin);
// -11644473600000 is the value you get if you convert Dec 31 1600 16:07:02 to unix epoch time
let timeCreatedLogin = TestData.formLogin({
username: "tc",
timeCreated: -11644473600000,
});
await Assert.rejects(
Services.logins.addLoginAsync(timeCreatedLogin),
/Can\'t add a login with invalid date properties./
);
let timeLastUsedLogin = TestData.formLogin({
username: "tlu",
timeLastUsed: -11644473600000,
});
await Assert.rejects(
Services.logins.addLoginAsync(timeLastUsedLogin),
/Can\'t add a login with invalid date properties./
);
let timePasswordChangedLogin = TestData.formLogin({
username: "tpc",
timePasswordChanged: -11644473600000,
});
await Services.logins.addLogins([
defaultsLogin,
timeCreatedLogin,
timeLastUsedLogin,
timePasswordChangedLogin,
]);
// none of the logins with invalid dates should have been added
let savedLogins = Services.logins.getAllLogins();
Assert.equal(savedLogins.length, 1);
await Assert.rejects(
Services.logins.addLoginAsync(timePasswordChangedLogin),
/Can\'t add a login with invalid date properties./
);
Services.logins.removeAllUserFacingLogins();
});

View File

@ -28,9 +28,7 @@ function resetPrimaryPassword() {
*/
add_task(async function test_logins_decrypt_failure() {
let logins = TestData.loginList();
for (let loginInfo of logins) {
Services.logins.addLogin(loginInfo);
}
await Services.logins.addLogins(logins);
// This makes the existing logins non-decryptable.
resetPrimaryPassword();
@ -57,9 +55,7 @@ add_task(async function test_logins_decrypt_failure() {
Assert.equal(Services.logins.countLogins("", "", ""), logins.length);
// Equivalent logins can be added.
for (let loginInfo of logins) {
Services.logins.addLogin(loginInfo);
}
await Services.logins.addLogins(logins);
LoginTestUtils.checkLogins(logins);
Assert.equal(
(await Services.logins.getAllLoginsAsync()).length,
@ -92,7 +88,7 @@ add_task(async function test_logins_decrypt_failure() {
// Bug 621846 - If a login has a GUID but can't be decrypted, a search for
// that GUID will (correctly) fail. Ensure we can add a new login with that
// same GUID.
add_task(function test_add_logins_with_decrypt_failure() {
add_task(async function test_add_logins_with_decrypt_failure() {
// a login with a GUID.
let login = new LoginInfo(
"http://www.example2.com",
@ -120,7 +116,7 @@ add_task(function test_add_logins_with_decrypt_failure() {
loginDupeGuid.QueryInterface(Ci.nsILoginMetaInfo);
loginDupeGuid.guid = login.guid;
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
// We can search for this login by GUID.
let searchProp = Cc["@mozilla.org/hash-property-bag;1"].createInstance(
@ -131,13 +127,13 @@ add_task(function test_add_logins_with_decrypt_failure() {
equal(Services.logins.searchLogins(searchProp).length, 1);
// We should fail to re-add it as it remains good.
Assert.throws(
() => Services.logins.addLogin(login),
await Assert.rejects(
Services.logins.addLoginAsync(login),
/This login already exists./
);
// We should fail to re-add a different login with the same GUID.
Assert.throws(
() => Services.logins.addLogin(loginDupeGuid),
await Assert.rejects(
Services.logins.addLoginAsync(loginDupeGuid),
/specified GUID already exists/
);
@ -148,7 +144,7 @@ add_task(function test_add_logins_with_decrypt_failure() {
equal(Services.logins.searchLogins(searchProp).length, 0);
// So we should be able to re-add a login with that same GUID.
Services.logins.addLogin(login);
await Services.logins.addLoginAsync(login);
equal(Services.logins.searchLogins(searchProp).length, 1);
Services.logins.removeAllUserFacingLogins();

View File

@ -82,9 +82,9 @@ add_task(function test_initialize() {
* Tests the behavior of addLogin with regard to metadata. The logins added
* here are also used by the following tests.
*/
add_task(function test_addLogin_metainfo() {
add_task(async function test_addLogin_metainfo() {
// Add a login without metadata to the database.
Services.logins.addLogin(gLoginInfo1);
await Services.logins.addLoginAsync(gLoginInfo1);
// The object provided to addLogin should not have been modified.
Assert.equal(gLoginInfo1.guid, null);
@ -104,7 +104,7 @@ add_task(function test_addLogin_metainfo() {
// Add a login without metadata to the database.
let originalLogin = gLoginInfo2.clone().QueryInterface(Ci.nsILoginMetaInfo);
Services.logins.addLogin(gLoginInfo2);
await Services.logins.addLoginAsync(gLoginInfo2);
// The object provided to addLogin should not have been modified.
assertMetaInfoEqual(gLoginInfo2, originalLogin);
@ -114,7 +114,7 @@ add_task(function test_addLogin_metainfo() {
assertMetaInfoEqual(gLoginMetaInfo2, gLoginInfo2);
// Add an authentication login to the database before continuing.
Services.logins.addLogin(gLoginInfo3);
await Services.logins.addLoginAsync(gLoginInfo3);
gLoginMetaInfo3 = retrieveLoginMatching(gLoginInfo3);
LoginTestUtils.checkLogins([gLoginInfo1, gLoginInfo2, gLoginInfo3]);
});
@ -122,13 +122,13 @@ add_task(function test_addLogin_metainfo() {
/**
* Tests that adding a login with a duplicate GUID throws an exception.
*/
add_task(function test_addLogin_metainfo_duplicate() {
add_task(async function test_addLogin_metainfo_duplicate() {
let loginInfo = TestData.formLogin({
origin: "http://duplicate.example.com",
guid: gLoginMetaInfo2.guid,
});
Assert.throws(
() => Services.logins.addLogin(loginInfo),
await Assert.rejects(
Services.logins.addLoginAsync(loginInfo),
/specified GUID already exists/
);

View File

@ -90,10 +90,8 @@ function checkAllSearches(aQuery, aExpectedCount) {
/**
* Prepare data for the following tests.
*/
add_task(function test_initialize() {
for (let login of TestData.loginList()) {
Services.logins.addLogin(login);
}
add_setup(async () => {
await Services.logins.addLogins(TestData.loginList());
});
/**

View File

@ -251,9 +251,7 @@ add_task(async function test_import_from_firefox_various_latest() {
await setupCsv([]);
info("Populate the login list for export");
let logins = LoginTestUtils.testData.loginList();
for (let loginInfo of logins) {
Services.logins.addLogin(loginInfo);
}
await Services.logins.addLogins(logins);
let tmpFilePath = FileTestUtils.getTempFile("logins.csv").path;
await LoginExport.exportAsCSV(tmpFilePath);

View File

@ -51,7 +51,7 @@ let TestObserver = {
},
};
add_task(function test_notifications() {
add_task(async function test_notifications() {
let testnum = 0;
let testdesc = "Setup of nsLoginInfo test-users";
@ -88,7 +88,7 @@ add_task(function test_notifications() {
expectedNotification = "addLogin";
expectedData = testuser1;
Services.logins.addLogin(testuser1);
await Services.logins.addLoginAsync(testuser1);
LoginTestUtils.checkLogins([testuser1]);
Assert.equal(expectedNotification, null); // check that observer got a notification
@ -128,7 +128,7 @@ add_task(function test_notifications() {
expectedNotification = "addLogin";
expectedData = testuser1;
Services.logins.addLogin(testuser1);
await Services.logins.addLoginAsync(testuser1);
expectedNotification = "removeAllLogins";
expectedData = null;

View File

@ -55,10 +55,8 @@ function checkSearch(aQuery, aExpectedCount) {
/**
* Prepare data for the following tests.
*/
add_task(function test_initialize() {
for (let login of TestData.loginList()) {
Services.logins.addLogin(login);
}
add_setup(async () => {
await Services.logins.addLogins(TestData.loginList());
});
/**

View File

@ -34,14 +34,14 @@ add_task(async function test_storage_addLogin_nonascii() {
usernameField: "field_" + String.fromCharCode(533, 537, 7570, 345),
passwordField: "field_" + String.fromCharCode(421, 259, 349, 537),
});
Services.logins.addLogin(loginInfo);
await Services.logins.addLoginAsync(loginInfo);
await reloadAndCheckLoginsGen([loginInfo]);
// Store the string "test" using similarly looking glyphs.
loginInfo = TestData.authLogin({
httpRealm: String.fromCharCode(355, 277, 349, 357),
});
Services.logins.addLogin(loginInfo);
await Services.logins.addLoginAsync(loginInfo);
await reloadAndCheckLoginsGen([loginInfo]);
});
@ -53,7 +53,7 @@ add_task(async function test_storage_addLogin_newlines() {
username: "user\r\nname",
password: "password\r\n",
});
Services.logins.addLogin(loginInfo);
await Services.logins.addLoginAsync(loginInfo);
await reloadAndCheckLoginsGen([loginInfo]);
});
@ -64,11 +64,11 @@ add_task(async function test_storage_addLogin_newlines() {
*/
add_task(async function test_storage_addLogin_dot() {
let loginInfo = TestData.formLogin({ origin: ".", passwordField: "." });
Services.logins.addLogin(loginInfo);
await Services.logins.addLoginAsync(loginInfo);
await reloadAndCheckLoginsGen([loginInfo]);
loginInfo = TestData.authLogin({ httpRealm: "." });
Services.logins.addLogin(loginInfo);
await Services.logins.addLoginAsync(loginInfo);
await reloadAndCheckLoginsGen([loginInfo]);
});
@ -88,8 +88,6 @@ add_task(async function test_storage_addLogin_parentheses() {
TestData.authLogin({ origin: "http://parens(example).example.com" }),
TestData.authLogin({ origin: "http://parens)example(.example.com" }),
];
for (let loginInfo of loginList) {
Services.logins.addLogin(loginInfo);
}
await Services.logins.addLogins(loginList);
await reloadAndCheckLoginsGen(loginList);
});

View File

@ -111,7 +111,7 @@ function testHistogram(histogramId, expectedNonZeroRanges) {
* Enable local telemetry recording for the duration of the tests, and prepare
* the test data that will be used by the following tests.
*/
add_task(function test_initialize() {
add_setup(async () => {
let oldCanRecord = Services.telemetry.canRecordExtended;
Services.telemetry.canRecordExtended = true;
registerCleanupFunction(function() {
@ -119,16 +119,16 @@ add_task(function test_initialize() {
});
let uniqueNumber = 1;
let logins = [];
for (let loginModifications of StatisticsTestData) {
loginModifications.origin = `http://${uniqueNumber++}.example.com`;
let login;
if (typeof loginModifications.httpRealm != "undefined") {
login = TestData.authLogin(loginModifications);
logins.push(TestData.authLogin(loginModifications));
} else {
login = TestData.formLogin(loginModifications);
logins.push(TestData.formLogin(loginModifications));
}
Services.logins.addLogin(login);
}
await Services.logins.addLogins(logins);
});
/**

View File

@ -10,11 +10,11 @@ add_setup(async () => {
add_task(async function test_vulnerable_password_methods() {
const storageJSON = Services.logins.wrappedJSObject._storage.wrappedJSObject;
let logins = TestData.loginList();
const logins = TestData.loginList();
Assert.greater(logins.length, 0, "Initial logins length should be > 0.");
for (let loginInfo of logins) {
Services.logins.addLogin(loginInfo);
for (const loginInfo of logins) {
await Services.logins.addLoginAsync(loginInfo);
Assert.ok(
!storageJSON.isPotentiallyVulnerablePassword(loginInfo),
"No logins should be vulnerable until addVulnerablePasswords is called."
@ -28,7 +28,7 @@ add_task(async function test_vulnerable_password_methods() {
storageJSON.isPotentiallyVulnerablePassword(vulnerableLogin),
"Login should be vulnerable after calling addVulnerablePassword."
);
for (let loginInfo of logins) {
for (const loginInfo of logins) {
Assert.ok(
!storageJSON.isPotentiallyVulnerablePassword(loginInfo),
"No other logins should be vulnerable when addVulnerablePassword is called" +
@ -38,7 +38,7 @@ add_task(async function test_vulnerable_password_methods() {
storageJSON.clearAllPotentiallyVulnerablePasswords();
for (let loginInfo of logins) {
for (const loginInfo of logins) {
Assert.ok(
!storageJSON.isPotentiallyVulnerablePassword(loginInfo),
"No logins should be vulnerable when clearAllPotentiallyVulnerablePasswords is called."