Bug 1680066 - Fall back to window prompts for webextension sidebar. r=Gijs

Differential Revision: https://phabricator.services.mozilla.com/D106513
This commit is contained in:
Paul Zuehlcke 2021-02-26 10:31:25 +00:00
Родитель 33a9ad45f5
Коммит d69fac75b0
5 изменённых файлов: 210 добавлений и 5 удалений

Просмотреть файл

@ -291,8 +291,9 @@ class PromptParent extends JSWindowActorParent {
let bag;
if (
args.modalType === Services.prompt.MODAL_TYPE_TAB ||
args.modalType === Services.prompt.MODAL_TYPE_CONTENT
(args.modalType === Services.prompt.MODAL_TYPE_TAB ||
args.modalType === Services.prompt.MODAL_TYPE_CONTENT) &&
win?.gBrowser?.getTabDialogBox
) {
if (!browser) {
let modal_type =
@ -319,6 +320,9 @@ class PromptParent extends JSWindowActorParent {
bag
);
} else {
// Ensure we set the correct modal type at this point.
// If we use window prompts as a fallback it may not be set.
args.modalType = Services.prompt.MODAL_TYPE_WINDOW;
// Window prompt
bag = PromptUtils.objectToPropBag(args);
Services.ww.openWindow(

Просмотреть файл

@ -0,0 +1,126 @@
function handleRequest(request, response)
{
var match;
var requestAuth = true;
// Allow the caller to drive how authentication is processed via the query.
// Eg, http://localhost:8888/authenticate.sjs?user=foo&realm=bar
// The extra ? allows the user/pass/realm checks to succeed if the name is
// at the beginning of the query string.
var query = "?" + request.queryString;
var expected_user = "test", expected_pass = "testpass", realm = "mochitest";
// user=xxx
match = /[^_]user=([^&]*)/.exec(query);
if (match)
expected_user = match[1];
// pass=xxx
match = /[^_]pass=([^&]*)/.exec(query);
if (match)
expected_pass = match[1];
// realm=xxx
match = /[^_]realm=([^&]*)/.exec(query);
if (match)
realm = match[1];
// Look for an authentication header, if any, in the request.
//
// EG: Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
//
// This test only supports Basic auth. The value sent by the client is
// "username:password", obscured with base64 encoding.
var actual_user = "", actual_pass = "", authHeader, authPresent = false;
if (request.hasHeader("Authorization")) {
authPresent = true;
authHeader = request.getHeader("Authorization");
match = /Basic (.+)/.exec(authHeader);
if (match.length != 2)
throw new Error("Couldn't parse auth header: " + authHeader);
var userpass = base64ToString(match[1]); // no atob() :-(
match = /(.*):(.*)/.exec(userpass);
if (match.length != 3)
throw new Error("Couldn't decode auth header: " + userpass);
actual_user = match[1];
actual_pass = match[2];
}
// Don't request authentication if the credentials we got were what we
// expected.
if (expected_user == actual_user &&
expected_pass == actual_pass) {
requestAuth = false;
}
if (requestAuth) {
response.setStatusLine("1.0", 401, "Authentication required");
response.setHeader("WWW-Authenticate", "basic realm=\"" + realm + "\"", true);
} else {
response.setStatusLine("1.0", 200, "OK");
}
response.setHeader("Content-Type", "application/xhtml+xml", false);
response.write("<html xmlns='http://www.w3.org/1999/xhtml'>");
response.write("<p>Login: <span id='ok'>" + (requestAuth ? "FAIL" : "PASS") + "</span></p>\n");
response.write("<p>Auth: <span id='auth'>" + authHeader + "</span></p>\n");
response.write("<p>User: <span id='user'>" + actual_user + "</span></p>\n");
response.write("<p>Pass: <span id='pass'>" + actual_pass + "</span></p>\n");
response.write("</html>");
}
// base64 decoder
//
// Yoinked from extensions/xml-rpc/src/nsXmlRpcClient.js because btoa()
// doesn't seem to exist. :-(
/* Convert Base64 data to a string */
const toBinaryTable = [
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
-1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
];
const base64Pad = '=';
function base64ToString(data) {
var result = '';
var leftbits = 0; // number of bits decoded, but yet to be appended
var leftdata = 0; // bits decoded, but yet to be appended
// Convert one by one.
for (var i = 0; i < data.length; i++) {
var c = toBinaryTable[data.charCodeAt(i) & 0x7f];
var padding = (data[i] == base64Pad);
// Skip illegal characters and whitespace
if (c == -1) continue;
// Collect data into leftdata, update bitcount
leftdata = (leftdata << 6) | c;
leftbits += 6;
// If we have 8 or more bits, append 8 bits to the result
if (leftbits >= 8) {
leftbits -= 8;
// Append if not padding.
if (!padding)
result += String.fromCharCode((leftdata >> leftbits) & 0xff);
leftdata &= (1 << leftbits) - 1;
}
}
// If there are any bits left, the base64 string was corrupted
if (leftbits)
throw Components.Exception('Corrupted base64 string');
return result;
}

Просмотреть файл

@ -198,6 +198,9 @@ skip-if = debug # Bug 1394984 disable debug builds on all platforms
[browser_ext_sidebarAction_click.js]
[browser_ext_sidebarAction_context.js]
[browser_ext_sidebarAction_contextMenu.js]
[browser_ext_sidebarAction_httpAuth.js]
support-files =
authenticate.sjs
[browser_ext_sidebarAction_incognito.js]
skip-if = true # Bug 1575369
[browser_ext_sidebarAction_runtime.js]

Просмотреть файл

@ -0,0 +1,72 @@
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
const { PromptTestUtils } = ChromeUtils.import(
"resource://testing-common/PromptTestUtils.jsm"
);
add_task(async function sidebar_httpAuthPrompt() {
let data = {
manifest: {
permissions: ["https://example.com/*"],
sidebar_action: {
default_panel: "sidebar.html",
},
},
useAddonManager: "temporary",
files: {
"sidebar.html": `
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"/>
<script src="sidebar.js"></script>
</head>
<body>
A Test Sidebar
</body></html>
`,
"sidebar.js": function() {
fetch(
"https://example.com/browser/browser/components/extensions/test/browser/authenticate.sjs?user=user&pass=pass",
{ credentials: "include" }
).then(response => {
browser.test.sendMessage("fetchResult", response.ok);
});
},
},
};
// Wait for the http auth prompt and close it with accept button.
let promptPromise = PromptTestUtils.handleNextPrompt(
SidebarUI.browser.contentWindow,
{
modalType: Services.prompt.MODAL_TYPE_WINDOW,
promptType: "promptUserAndPass",
},
{ buttonNumClick: 0, loginInput: "user", passwordInput: "pass" }
);
let extension = ExtensionTestUtils.loadExtension(data);
await extension.startup();
let fetchResultPromise = extension.awaitMessage("fetchResult");
await promptPromise;
ok(true, "Extension fetch should trigger auth prompt.");
let responseOk = await fetchResultPromise;
ok(responseOk, "Login should succeed.");
await extension.unload();
// Cleanup
await new Promise(resolve =>
Services.clearData.deleteData(
Ci.nsIClearDataService.CLEAR_AUTH_CACHE,
resolve
)
);
});

Просмотреть файл

@ -148,7 +148,7 @@ let PromptTestUtils = {
} else if (parent instanceof Ci.nsIDOMChromeWindow) {
// Parent is window
parentWindow = parent;
parentBrowser = parentWindow.gBrowser.selectedBrowser;
parentBrowser = parentWindow.gBrowser?.selectedBrowser;
} else {
throw new Error("Invalid parent. Expected browser or dom window");
}
@ -162,7 +162,7 @@ let PromptTestUtils = {
await TestUtils.topicObserved(topic, subject => {
// If we are not given a browser, use the currently selected browser of the window
let browser =
parentBrowser || subject.ownerGlobal.gBrowser.selectedBrowser;
parentBrowser || subject.ownerGlobal.gBrowser?.selectedBrowser;
if (isCommonDialog(modalType)) {
// Is not associated with given parent window, skip
if (parentWindow && subject.opener !== parentWindow) {
@ -170,7 +170,7 @@ let PromptTestUtils = {
}
// For tab prompts, ensure that the associated browser matches.
if (modalType == Services.prompt.MODAL_TYPE_TAB) {
if (browser && modalType == Services.prompt.MODAL_TYPE_TAB) {
let dialogBox = parentWindow.gBrowser.getTabDialogBox(browser);
let hasMatchingDialog = dialogBox._tabDialogManager._dialogs.some(
d => d._frame?.browsingContext == subject.browsingContext