/** * Helpers for password manager mochitest-plain tests. */ /* import-globals-from ../../../../../toolkit/components/satchel/test/satchel_common.js */ const { LoginTestUtils } = SpecialPowers.ChromeUtils.importESModule( "resource://testing-common/LoginTestUtils.sys.mjs" ); const Services = SpecialPowers.Services; // Setup LoginTestUtils to report assertions to the mochitest harness. LoginTestUtils.setAssertReporter( SpecialPowers.wrapCallback((err, message, stack) => { SimpleTest.record(!err, err ? err.message : message, null, stack); }) ); const { LoginHelper } = SpecialPowers.ChromeUtils.importESModule( "resource://gre/modules/LoginHelper.sys.mjs" ); const { LENGTH: GENERATED_PASSWORD_LENGTH, REGEX: GENERATED_PASSWORD_REGEX } = LoginTestUtils.generation; const LOGIN_FIELD_UTILS = LoginTestUtils.loginField; const TESTS_DIR = "/tests/toolkit/components/passwordmgr/test/"; // Depending on pref state we either show auth prompts as windows or on tab level. let authPromptModalType = SpecialPowers.Services.prefs.getIntPref( "prompts.modalType.httpAuth" ); // Whether the auth prompt is a commonDialog.xhtml or a TabModalPrompt let authPromptIsCommonDialog = authPromptModalType === SpecialPowers.Services.prompt.MODAL_TYPE_WINDOW || (authPromptModalType === SpecialPowers.Services.prompt.MODAL_TYPE_TAB && SpecialPowers.Services.prefs.getBoolPref( "prompts.tabChromePromptSubDialog", false )); /** * Recreate a DOM tree using the outerHTML to ensure that any event listeners * and internal state for the elements are removed. */ function recreateTree(element) { // eslint-disable-next-line no-unsanitized/property, no-self-assign element.outerHTML = element.outerHTML; } function _checkArrayValues(actualValues, expectedValues, msg) { is( actualValues.length, expectedValues.length, "Checking array values: " + msg ); for (let i = 0; i < expectedValues.length; i++) { is(actualValues[i], expectedValues[i], msg + " Checking array entry #" + i); } } /** * Check autocomplete popup results to ensure that expected * *labels* are being shown correctly as items in the popup. */ function checkAutoCompleteResults(actualValues, expectedValues, hostname, msg) { if (hostname === null) { _checkArrayValues(actualValues, expectedValues, msg); return; } is( typeof hostname, "string", "checkAutoCompleteResults: hostname must be a string" ); isnot( actualValues.length, 0, "There should be items in the autocomplete popup: " + JSON.stringify(actualValues) ); // Check the footer first. let footerResult = actualValues[actualValues.length - 1]; is(footerResult, "View Saved Logins", "the footer text is shown correctly"); if (actualValues.length == 1) { is( expectedValues.length, 0, "If only the footer is present then there should be no expectedValues" ); info("Only the footer is present in the popup"); return; } // Check the rest of the autocomplete item values. _checkArrayValues(actualValues.slice(0, -1), expectedValues, msg); } function getIframeBrowsingContext(window, iframeNumber = 0) { let bc = SpecialPowers.wrap(window).windowGlobalChild.browsingContext; return SpecialPowers.unwrap(bc.children[iframeNumber]); } /** * Set input values via setUserInput to emulate user input * and distinguish them from declarative or script-assigned values */ function setUserInputValues(parentNode, selectorValues, userInput = true) { for (let [selector, newValue] of Object.entries(selectorValues)) { info(`setUserInputValues, selector: ${selector}`); try { let field = SpecialPowers.wrap(parentNode.querySelector(selector)); if (field.value == newValue) { // we don't get an input event if the new value == the old field.value += "#"; } if (userInput) { field.setUserInput(newValue); } else { field.value = newValue; } } catch (ex) { info(ex.message); info(ex.stack); ok( false, `setUserInputValues: Couldn't set value of field: ${ex.message}` ); } } } /** * @param {Function} [aFilterFn = undefined] Function to filter out irrelevant submissions. * @return {Promise} resolving when a relevant form submission was processed. */ function getSubmitMessage(aFilterFn = undefined) { info("getSubmitMessage"); return new Promise((resolve, reject) => { PWMGR_COMMON_PARENT.addMessageListener( "formSubmissionProcessed", function processed(...args) { if (aFilterFn && !aFilterFn(...args)) { // This submission isn't the one we're waiting for. return; } info("got formSubmissionProcessed"); PWMGR_COMMON_PARENT.removeMessageListener( "formSubmissionProcessed", processed ); resolve(args[0]); } ); }); } /** * @return {Promise} resolves when a onPasswordEditedOrGenerated message is received at the parent */ function getPasswordEditedMessage() { info("getPasswordEditedMessage"); return new Promise((resolve, reject) => { PWMGR_COMMON_PARENT.addMessageListener( "passwordEditedOrGenerated", function listener(...args) { info("got passwordEditedOrGenerated"); PWMGR_COMMON_PARENT.removeMessageListener( "passwordEditedOrGenerated", listener ); resolve(args[0]); } ); }); } /** * Create a login form and insert into contents dom (identified by id * `content`). If the form (identified by its number) is already present in the * dom, it gets replaced. * * @param {number} [num = 1] - number of the form, used as id, eg `form1` * @param {string} [action = ""] - action attribute of the form * @param {string} [autocomplete = null] - forms autocomplete attribute. Default is none * @param {object} [username = {}] - object describing attributes to the username field: * @param {string} [username.id = null] - id of the field * @param {string} [username.name = "uname"] - name attribute * @param {string} [username.type = "text"] - type of the field * @param {string} [username.value = null] - initial value of the field * @param {string} [username.autocomplete = null] - autocomplete attribute * @param {object} [password = {}] - an object describing attributes to the password field. If falsy, do not create a password field * @param {string} [password.id = null] - id of the field * @param {string} [password.name = "pword"] - name attribute * @param {string} [password.type = "password"] - type of the field * @param {string} [password.value = null] - initial value of the field * @param {string} [password.label = null] - if present, wrap field in a label containing its value * @param {string} [password.autocomplete = null] - autocomplete attribute * * @return {HTMLDomElement} the form */ function createLoginForm({ num = 1, action = "", autocomplete = null, username = {}, password = {}, } = {}) { username.id ||= null; username.name ||= "uname"; username.type ||= "text"; username.value ||= null; username.autocomplete ||= null; password.id ||= null; password.name ||= "pword"; password.type ||= "password"; password.value ||= null; password.label ||= null; password.autocomplete ||= null; info( `Creating login form ${JSON.stringify({ num, action, username, password })}` ); const form = document.createElement("form"); form.id = `form${num}`; form.action = action; form.onsubmit = () => false; if (autocomplete != null) { form.setAttribute("autocomplete", autocomplete); } const usernameInput = document.createElement("input"); if (username.id != null) { usernameInput.id = username.id; } usernameInput.type = username.type; usernameInput.name = username.name; if (username.value != null) { usernameInput.value = username.value; } if (username.autocomplete != null) { usernameInput.setAttribute("autocomplete", username.autocomplete); } form.appendChild(usernameInput); if (password) { const passwordInput = document.createElement("input"); if (password.id != null) { passwordInput.id = password.id; } passwordInput.type = password.type; passwordInput.name = password.name; if (password.value != null) { passwordInput.value = password.value; } if (password.autocomplete != null) { passwordInput.setAttribute("autocomplete", password.autocomplete); } if (password.label != null) { const passwordLabel = document.createElement("label"); passwordLabel.innerText = password.label; passwordLabel.appendChild(passwordInput); form.appendChild(passwordLabel); } else { form.appendChild(passwordInput); } } const submitButton = document.createElement("button"); submitButton.type = "submit"; submitButton.name = "submit"; submitButton.innerText = "Submit"; form.appendChild(submitButton); const content = document.getElementById("content"); const oldForm = document.getElementById(form.id); if (oldForm) { content.replaceChild(form, oldForm); } else { content.appendChild(form); } return form; } /** * Check for expected username/password in form. * @see `checkForm` below for a similar function. */ function checkLoginForm( usernameField, expectedUsername, passwordField, expectedPassword ) { let formID = usernameField.parentNode.id; is( usernameField.value, expectedUsername, "Checking " + formID + " username is: " + expectedUsername ); is( passwordField.value, expectedPassword, "Checking " + formID + " password is: " + expectedPassword ); } /** * Check repeatedly for a while to see if a particular condition still applies. * This function checks the return value of `condition` repeatedly until either * the condition has a falsy return value, or `retryTimes` is exceeded. */ function ensureCondition( condition, errorMsg = "Condition did not last.", retryTimes = 10 ) { return new Promise((resolve, reject) => { let tries = 0; let conditionFailed = false; let interval = setInterval(async function () { try { const conditionPassed = await condition(); conditionFailed ||= !conditionPassed; } catch (e) { ok(false, e + "\n" + e.stack); conditionFailed = true; } if (conditionFailed || tries >= retryTimes) { ok(!conditionFailed, errorMsg); clearInterval(interval); if (conditionFailed) { reject(errorMsg); } else { resolve(); } } tries++; }, 100); }); } /** * Wait a while to ensure login form stays filled with username and password * @see `checkLoginForm` below for a similar function. * @returns a promise, resolving when done * * TODO: eventually get rid of this time based check, and transition to an * event based approach. See Bug 1811142. * Filling happens by `_fillForm()` which can report it's decision and we can * wait for it. One of the options is to have `didFillFormAsync()` from * https://phabricator.services.mozilla.com/D167214#change-3njWgUgqswws */ function ensureLoginFormStaysFilledWith( usernameField, expectedUsername, passwordField, expectedPassword ) { return ensureCondition(() => { return ( Object.is(usernameField.value, expectedUsername) && Object.is(passwordField.value, expectedPassword) ); }, `Ensuring form ${usernameField.parentNode.id} stays filled with "${expectedUsername}:${expectedPassword}"`); } function checkLoginFormInFrame( iframeBC, usernameFieldId, expectedUsername, passwordFieldId, expectedPassword ) { return SpecialPowers.spawn( iframeBC, [usernameFieldId, expectedUsername, passwordFieldId, expectedPassword], ( usernameFieldIdF, expectedUsernameF, passwordFieldIdF, expectedPasswordF ) => { let usernameField = this.content.document.getElementById(usernameFieldIdF); let passwordField = this.content.document.getElementById(passwordFieldIdF); let formID = usernameField.parentNode.id; Assert.equal( usernameField.value, expectedUsernameF, "Checking " + formID + " username is: " + expectedUsernameF ); Assert.equal( passwordField.value, expectedPasswordF, "Checking " + formID + " password is: " + expectedPasswordF ); } ); } async function checkUnmodifiedFormInFrame(bc, formNum) { return SpecialPowers.spawn(bc, [formNum], formNumF => { let form = this.content.document.getElementById(`form${formNumF}`); ok(form, "Locating form " + formNumF); for (var i = 0; i < form.elements.length; i++) { var ele = form.elements[i]; // No point in checking form submit/reset buttons. if (ele.type == "submit" || ele.type == "reset") { continue; } is( ele.value, ele.defaultValue, "Test to default value of field " + ele.name + " in form " + formNumF ); } }); } /** * Check a form for expected values even if it is in a different top level window * or process. If an argument is null, a field's expected value will be the default * value. * * Similar to the checkForm helper, but it works across (cross-origin) frames. * *