mirror of
https://gitlab.winehq.org/wine/wine-gecko.git
synced 2024-09-13 09:24:08 -07:00
merge mozilla-inbound to mozilla-central a=merge
--HG-- extra : amend_source : 8afac23e33906916e7e6297e2307417e09fa27ae
This commit is contained in:
commit
e8476e21fa
@ -388,9 +388,6 @@ pref("content.ime.strict_policy", true);
|
||||
// $ adb shell start
|
||||
pref("browser.dom.window.dump.enabled", false);
|
||||
|
||||
// Turn on the CSP 1.0 parser for Content Security Policy headers
|
||||
pref("security.csp.speccompliant", true);
|
||||
|
||||
// Default Content Security Policy to apply to privileged and certified apps
|
||||
pref("security.apps.privileged.CSP.default", "default-src *; script-src 'self'; object-src 'none'; style-src 'self' 'unsafe-inline'");
|
||||
// If you change this CSP, make sure to update the fast path in nsCSPService.cpp
|
||||
|
@ -1524,9 +1524,6 @@ pref("social.sidebar.unload_timeout_ms", 10000);
|
||||
|
||||
pref("dom.identity.enabled", false);
|
||||
|
||||
// Turn on the CSP 1.0 parser for Content Security Policy headers
|
||||
pref("security.csp.speccompliant", true);
|
||||
|
||||
// Block insecure active content on https pages
|
||||
pref("security.mixed_content.block_active_content", true);
|
||||
|
||||
|
@ -34,22 +34,22 @@ addMessageListener("Browser:HideSessionRestoreButton", function (message) {
|
||||
}
|
||||
});
|
||||
|
||||
addEventListener("DOMFormHasPassword", function(event) {
|
||||
InsecurePasswordUtils.checkForInsecurePasswords(event.target);
|
||||
LoginManagerContent.onFormPassword(event);
|
||||
});
|
||||
addEventListener("DOMAutoComplete", function(event) {
|
||||
LoginManagerContent.onUsernameInput(event);
|
||||
});
|
||||
addEventListener("blur", function(event) {
|
||||
LoginManagerContent.onUsernameInput(event);
|
||||
});
|
||||
|
||||
if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) {
|
||||
addEventListener("contextmenu", function (event) {
|
||||
sendAsyncMessage("contextmenu", {}, { event: event });
|
||||
}, false);
|
||||
} else {
|
||||
addEventListener("DOMFormHasPassword", function(event) {
|
||||
InsecurePasswordUtils.checkForInsecurePasswords(event.target);
|
||||
LoginManagerContent.onFormPassword(event);
|
||||
});
|
||||
addEventListener("DOMAutoComplete", function(event) {
|
||||
LoginManagerContent.onUsernameInput(event);
|
||||
});
|
||||
addEventListener("blur", function(event) {
|
||||
LoginManagerContent.onUsernameInput(event);
|
||||
});
|
||||
|
||||
addEventListener("mozUITour", function(event) {
|
||||
if (!Services.prefs.getBoolPref("browser.uitour.enabled"))
|
||||
return;
|
||||
|
@ -93,6 +93,9 @@ XPCOMUtils.defineLazyModuleGetter(this, "BrowserUITelemetry",
|
||||
XPCOMUtils.defineLazyModuleGetter(this, "AsyncShutdown",
|
||||
"resource://gre/modules/AsyncShutdown.jsm");
|
||||
|
||||
XPCOMUtils.defineLazyModuleGetter(this, "LoginManagerParent",
|
||||
"resource://gre/modules/LoginManagerParent.jsm");
|
||||
|
||||
#ifdef NIGHTLY_BUILD
|
||||
XPCOMUtils.defineLazyModuleGetter(this, "SignInToWebsiteUX",
|
||||
"resource:///modules/SignInToWebsite.jsm");
|
||||
@ -507,6 +510,8 @@ BrowserGlue.prototype = {
|
||||
RemotePrompt.init();
|
||||
}
|
||||
|
||||
LoginManagerParent.init();
|
||||
|
||||
Services.obs.notifyObservers(null, "browser-ui-startup-complete", "");
|
||||
},
|
||||
|
||||
|
@ -53,8 +53,6 @@ support-files =
|
||||
test-bug-782653-css-errors-1.css
|
||||
test-bug-782653-css-errors-2.css
|
||||
test-bug-782653-css-errors.html
|
||||
test-bug-821877-csperrors.html
|
||||
test-bug-821877-csperrors.html^headers^
|
||||
test-bug-837351-security-errors.html
|
||||
test-bug-846918-hsts-invalid-headers.html
|
||||
test-bug-846918-hsts-invalid-headers.html^headers^
|
||||
@ -100,8 +98,6 @@ support-files =
|
||||
test-repeated-messages.html
|
||||
test-result-format-as-string.html
|
||||
test-webconsole-error-observer.html
|
||||
test_bug_770099_bad_policy_uri.html
|
||||
test_bug_770099_bad_policy_uri.html^headers^
|
||||
test_bug_770099_violation.html
|
||||
test_bug_770099_violation.html^headers^
|
||||
test-autocomplete-in-stackframe.html
|
||||
@ -230,13 +226,11 @@ run-if = os == "win"
|
||||
[browser_webconsole_bug_762593_insecure_passwords_web_console_warning.js]
|
||||
[browser_webconsole_bug_764572_output_open_url.js]
|
||||
[browser_webconsole_bug_766001_JS_Console_in_Debugger.js]
|
||||
[browser_webconsole_bug_770099_bad_policyuri.js]
|
||||
[browser_webconsole_bug_770099_violation.js]
|
||||
[browser_webconsole_bug_782653_CSS_links_in_Style_Editor.js]
|
||||
[browser_webconsole_bug_804845_ctrl_key_nav.js]
|
||||
run-if = os == "mac"
|
||||
[browser_webconsole_bug_817834_add_edited_input_to_history.js]
|
||||
[browser_webconsole_bug_821877_csp_errors.js]
|
||||
[browser_webconsole_bug_837351_securityerrors.js]
|
||||
[browser_webconsole_bug_846918_hsts_invalid-headers.js]
|
||||
[browser_webconsole_bug_915141_toggle_response_logging_with_keyboard.js]
|
||||
|
@ -15,8 +15,8 @@ The expected console messages in the constants CSP_VIOLATION_MSG and CSP_REPORT_
|
||||
*/
|
||||
|
||||
const TEST_VIOLATION = "http://example.com/browser/browser/devtools/webconsole/test/test_bug_1010953_cspro.html";
|
||||
const CSP_VIOLATION_MSG = 'Content Security Policy: The page\'s settings blocked the loading of a resource at http://some.example.com/test.png ("img-src http://example.com:80").';
|
||||
const CSP_REPORT_MSG = 'Content Security Policy: The page\'s settings observed the loading of a resource at http://some.example.com/test_bug_1010953_cspro.js ("script-src http://example.com:80"). A CSP report is being sent.';
|
||||
const CSP_VIOLATION_MSG = 'Content Security Policy: The page\'s settings blocked the loading of a resource at http://some.example.com/test.png ("img-src http://example.com").';
|
||||
const CSP_REPORT_MSG = 'Content Security Policy: The page\'s settings observed the loading of a resource at http://some.example.com/test_bug_1010953_cspro.js ("script-src http://example.com"). A CSP report is being sent.';
|
||||
|
||||
|
||||
let hud = undefined;
|
||||
|
@ -1,40 +0,0 @@
|
||||
/* vim:set ts=2 sw=2 sts=2 et: */
|
||||
/* ***** BEGIN LICENSE BLOCK *****
|
||||
* Any copyright is dedicated to the Public Domain.
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/
|
||||
*
|
||||
* ***** END LICENSE BLOCK ***** */
|
||||
|
||||
// Tests that the Web Console CSP messages are displayed
|
||||
|
||||
const TEST_BAD_POLICY_URI = "https://example.com/browser/browser/devtools/webconsole/test/test_bug_770099_bad_policy_uri.html";
|
||||
|
||||
let hud = undefined;
|
||||
|
||||
function test() {
|
||||
addTab("data:text/html;charset=utf8,Web Console CSP bad policy URI test");
|
||||
browser.addEventListener("load", function _onLoad() {
|
||||
browser.removeEventListener("load", _onLoad, true);
|
||||
openConsole(null, loadDocument);
|
||||
}, true);
|
||||
}
|
||||
|
||||
function loadDocument(theHud) {
|
||||
hud = theHud;
|
||||
hud.jsterm.clearOutput();
|
||||
browser.addEventListener("load", onLoad, true);
|
||||
content.location = TEST_BAD_POLICY_URI;
|
||||
}
|
||||
|
||||
function onLoad(aEvent) {
|
||||
browser.removeEventListener("load", onLoad, true);
|
||||
|
||||
waitForMessages({
|
||||
webconsole: hud,
|
||||
messages: [{
|
||||
text: "can't fetch policy",
|
||||
category: CATEGORY_SECURITY,
|
||||
severity: SEVERITY_ERROR,
|
||||
}],
|
||||
}).then(finishTest);
|
||||
}
|
@ -8,7 +8,7 @@
|
||||
// Tests that the Web Console CSP messages are displayed
|
||||
|
||||
const TEST_VIOLATION = "https://example.com/browser/browser/devtools/webconsole/test/test_bug_770099_violation.html";
|
||||
const CSP_VIOLATION_MSG = 'Content Security Policy: The page\'s settings blocked the loading of a resource at http://some.example.com/test.png ("default-src https://example.com:443").'
|
||||
const CSP_VIOLATION_MSG = 'Content Security Policy: The page\'s settings blocked the loading of a resource at http://some.example.com/test.png ("default-src https://example.com").'
|
||||
|
||||
let hud = undefined;
|
||||
|
||||
|
@ -1,28 +0,0 @@
|
||||
// Tests that CSP errors from nsDocument::InitCSP are logged to the Web Console
|
||||
|
||||
/* Any copyright is dedicated to the Public Domain.
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/ */
|
||||
|
||||
const TEST_URI = "https://example.com/browser/browser/devtools/webconsole/test/test-bug-821877-csperrors.html";
|
||||
const CSP_DEPRECATED_HEADER_MSG = "The X-Content-Security-Policy and X-Content-Security-Report-Only headers will be deprecated in the future. Please use the Content-Security-Policy and Content-Security-Report-Only headers with CSP spec compliant syntax instead.";
|
||||
|
||||
function test()
|
||||
{
|
||||
addTab(TEST_URI);
|
||||
browser.addEventListener("load", function onLoad(aEvent) {
|
||||
browser.removeEventListener(aEvent.type, onLoad, true);
|
||||
openConsole(null, function testCSPErrorLogged (hud) {
|
||||
waitForMessages({
|
||||
webconsole: hud,
|
||||
messages: [
|
||||
{
|
||||
name: "Deprecated CSP header error displayed successfully",
|
||||
text: CSP_DEPRECATED_HEADER_MSG,
|
||||
category: CATEGORY_SECURITY,
|
||||
severity: SEVERITY_WARNING
|
||||
},
|
||||
],
|
||||
}).then(finishTest);
|
||||
});
|
||||
}, true);
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf8">
|
||||
<title>Bug 821877 - Log CSP Errors to Web Console</title>
|
||||
<!-- Any copyright is dedicated to the Public Domain.
|
||||
- http://creativecommons.org/publicdomain/zero/1.0/ -->
|
||||
</head>
|
||||
<body>
|
||||
<p>This page is served with a deprecated CSP header.</p>
|
||||
</body>
|
||||
</html>
|
@ -1 +0,0 @@
|
||||
X-Content-Security-Policy: default-src *; options inline-script
|
@ -1,12 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Test for Bug 770099 - bad policy-uri</title>
|
||||
<!-- Any copyright is dedicated to the Public Domain.
|
||||
http://creativecommons.org/publicdomain/zero/1.0/ -->
|
||||
</head>
|
||||
<body>
|
||||
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=770099">Mozilla Bug 770099</a>
|
||||
</body>
|
||||
</html>
|
@ -1,2 +0,0 @@
|
||||
X-Content-Security-Policy: policy-uri http://example.com/some_policy
|
||||
Content-type: text/html; charset=utf-8
|
@ -1 +1 @@
|
||||
X-Content-Security-Policy: default-src 'self'
|
||||
Content-Security-Policy: default-src 'self'
|
||||
|
@ -7,6 +7,9 @@
|
||||
Cu.import("resource://gre/modules/devtools/dbg-server.jsm")
|
||||
Cu.import("resource://gre/modules/WindowsPrefSync.jsm");
|
||||
|
||||
XPCOMUtils.defineLazyModuleGetter(this, "LoginManagerParent",
|
||||
"resource://gre/modules/LoginManagerParent.jsm");
|
||||
|
||||
/**
|
||||
* Constants
|
||||
*/
|
||||
@ -167,6 +170,7 @@ var BrowserUI = {
|
||||
DialogUI.init();
|
||||
FormHelperUI.init();
|
||||
FindHelperUI.init();
|
||||
LoginManagerParent.init();
|
||||
#ifdef NIGHTLY_BUILD
|
||||
PdfJs.init();
|
||||
#endif
|
||||
|
@ -193,7 +193,7 @@ CSPPolicyURIListener.prototype = {
|
||||
// send the policy we received back to the parent document's CSP
|
||||
// for parsing
|
||||
this._csp.appendPolicy(this._policy, this._docURI,
|
||||
this._reportOnly, this._csp._specCompliant);
|
||||
this._reportOnly, true);
|
||||
}
|
||||
else {
|
||||
// problem fetching policy so fail closed by appending a "block it all"
|
||||
@ -202,7 +202,7 @@ CSPPolicyURIListener.prototype = {
|
||||
this._csp.log(WARN_FLAG, CSPLocalizer.getFormatStr("errorFetchingPolicy",
|
||||
[status]));
|
||||
this._csp.appendPolicy("default-src 'none'", this._docURI,
|
||||
this._reportOnly, this._csp._specCompliant);
|
||||
this._reportOnly, true);
|
||||
}
|
||||
// resume the parent document request
|
||||
this._docRequest.resume();
|
||||
@ -213,49 +213,23 @@ CSPPolicyURIListener.prototype = {
|
||||
|
||||
/**
|
||||
* Class that represents a parsed policy structure.
|
||||
*
|
||||
* @param aSpecCompliant: true: this policy is a CSP 1.0 spec
|
||||
* compliant policy and should be parsed as such.
|
||||
* false or undefined: this is a policy using
|
||||
* our original implementation's CSP syntax.
|
||||
*/
|
||||
this.CSPRep = function CSPRep(aSpecCompliant) {
|
||||
this.CSPRep = function CSPRep() {
|
||||
// this gets set to true when the policy is done parsing, or when a
|
||||
// URI-borne policy has finished loading.
|
||||
this._isInitialized = false;
|
||||
|
||||
this._allowEval = false;
|
||||
this._allowInlineScripts = false;
|
||||
this._allowInlineStyles = false;
|
||||
this._reportOnlyMode = false;
|
||||
|
||||
// don't auto-populate _directives, so it is easier to find bugs
|
||||
this._directives = {};
|
||||
|
||||
// Is this a 1.0 spec compliant CSPRep ?
|
||||
// Default to false if not specified.
|
||||
this._specCompliant = (aSpecCompliant !== undefined) ? aSpecCompliant : false;
|
||||
|
||||
// Only CSP 1.0 spec compliant policies block inline styles by default.
|
||||
this._allowInlineStyles = !aSpecCompliant;
|
||||
}
|
||||
|
||||
// Source directives for our original CSP implementation.
|
||||
// These can be removed when the original implementation is deprecated.
|
||||
CSPRep.SRC_DIRECTIVES_OLD = {
|
||||
DEFAULT_SRC: "default-src",
|
||||
SCRIPT_SRC: "script-src",
|
||||
STYLE_SRC: "style-src",
|
||||
MEDIA_SRC: "media-src",
|
||||
IMG_SRC: "img-src",
|
||||
OBJECT_SRC: "object-src",
|
||||
FRAME_SRC: "frame-src",
|
||||
FRAME_ANCESTORS: "frame-ancestors",
|
||||
FONT_SRC: "font-src",
|
||||
XHR_SRC: "xhr-src"
|
||||
};
|
||||
|
||||
// Source directives for our CSP 1.0 spec compliant implementation.
|
||||
CSPRep.SRC_DIRECTIVES_NEW = {
|
||||
CSPRep.SRC_DIRECTIVES = {
|
||||
DEFAULT_SRC: "default-src",
|
||||
SCRIPT_SRC: "script-src",
|
||||
STYLE_SRC: "style-src",
|
||||
@ -273,268 +247,6 @@ CSPRep.URI_DIRECTIVES = {
|
||||
POLICY_URI: "policy-uri" /* single URI */
|
||||
};
|
||||
|
||||
// These directives no longer exist in CSP 1.0 and
|
||||
// later and will eventually be removed when we no longer
|
||||
// support our original implementation's syntax.
|
||||
CSPRep.OPTIONS_DIRECTIVE = "options";
|
||||
CSPRep.ALLOW_DIRECTIVE = "allow";
|
||||
|
||||
/**
|
||||
* Factory to create a new CSPRep, parsed from a string.
|
||||
*
|
||||
* @param aStr
|
||||
* string rep of a CSP
|
||||
* @param self (optional)
|
||||
* URI representing the "self" source
|
||||
* @param reportOnly (optional)
|
||||
* whether or not this CSP is report-only (defaults to false)
|
||||
* @param docRequest (optional)
|
||||
* request for the parent document which may need to be suspended
|
||||
* while the policy-uri is asynchronously fetched
|
||||
* @param csp (optional)
|
||||
* the CSP object to update once the policy has been fetched
|
||||
* @param enforceSelfChecks (optional)
|
||||
* if present, and "true", will check to be sure "self" has the
|
||||
* appropriate values to inherit when they are omitted from the source.
|
||||
* @returns
|
||||
* an instance of CSPRep
|
||||
*/
|
||||
CSPRep.fromString = function(aStr, self, reportOnly, docRequest, csp,
|
||||
enforceSelfChecks) {
|
||||
var SD = CSPRep.SRC_DIRECTIVES_OLD;
|
||||
var UD = CSPRep.URI_DIRECTIVES;
|
||||
var aCSPR = new CSPRep();
|
||||
aCSPR._originalText = aStr;
|
||||
aCSPR._innerWindowID = innerWindowFromRequest(docRequest);
|
||||
if (typeof reportOnly === 'undefined') reportOnly = false;
|
||||
aCSPR._reportOnlyMode = reportOnly;
|
||||
|
||||
var selfUri = null;
|
||||
if (self instanceof Ci.nsIURI) {
|
||||
selfUri = self.cloneIgnoringRef();
|
||||
// clean userpass out of the URI (not used for CSP origin checking, but
|
||||
// shows up in prePath).
|
||||
try {
|
||||
// GetUserPass throws for some protocols without userPass
|
||||
selfUri.userPass = '';
|
||||
} catch (ex) {}
|
||||
}
|
||||
|
||||
var dirs = aStr.split(";");
|
||||
|
||||
directive:
|
||||
for each(var dir in dirs) {
|
||||
dir = dir.trim();
|
||||
if (dir.length < 1) continue;
|
||||
|
||||
var dirname = dir.split(/\s+/)[0].toLowerCase();
|
||||
var dirvalue = dir.substring(dirname.length).trim();
|
||||
|
||||
if (aCSPR._directives.hasOwnProperty(dirname)) {
|
||||
// Check for (most) duplicate directives
|
||||
cspError(aCSPR, CSPLocalizer.getFormatStr("duplicateDirective",
|
||||
[dirname]));
|
||||
CSPdebug("Skipping duplicate directive: \"" + dir + "\"");
|
||||
continue directive;
|
||||
}
|
||||
|
||||
// OPTIONS DIRECTIVE ////////////////////////////////////////////////
|
||||
if (dirname === CSPRep.OPTIONS_DIRECTIVE) {
|
||||
if (aCSPR._allowInlineScripts || aCSPR._allowEval) {
|
||||
// Check for duplicate options directives
|
||||
cspError(aCSPR, CSPLocalizer.getFormatStr("duplicateDirective",
|
||||
[dirname]));
|
||||
CSPdebug("Skipping duplicate directive: \"" + dir + "\"");
|
||||
continue directive;
|
||||
}
|
||||
|
||||
// grab value tokens and interpret them
|
||||
var options = dirvalue.split(/\s+/);
|
||||
for each (var opt in options) {
|
||||
if (opt === "inline-script")
|
||||
aCSPR._allowInlineScripts = true;
|
||||
else if (opt === "eval-script")
|
||||
aCSPR._allowEval = true;
|
||||
else
|
||||
cspWarn(aCSPR, CSPLocalizer.getFormatStr("ignoringUnknownOption",
|
||||
[opt]));
|
||||
}
|
||||
continue directive;
|
||||
}
|
||||
|
||||
// ALLOW DIRECTIVE //////////////////////////////////////////////////
|
||||
// parse "allow" as equivalent to "default-src", at least until the spec
|
||||
// stabilizes, at which time we can stop parsing "allow"
|
||||
if (dirname === CSPRep.ALLOW_DIRECTIVE) {
|
||||
cspWarn(aCSPR, CSPLocalizer.getStr("allowDirectiveIsDeprecated"));
|
||||
if (aCSPR._directives.hasOwnProperty(SD.DEFAULT_SRC)) {
|
||||
// Check for duplicate default-src and allow directives
|
||||
cspError(aCSPR, CSPLocalizer.getFormatStr("duplicateDirective",
|
||||
[dirname]));
|
||||
CSPdebug("Skipping duplicate directive: \"" + dir + "\"");
|
||||
continue directive;
|
||||
}
|
||||
var dv = CSPSourceList.fromString(dirvalue, aCSPR, selfUri,
|
||||
enforceSelfChecks);
|
||||
if (dv) {
|
||||
aCSPR._directives[SD.DEFAULT_SRC] = dv;
|
||||
continue directive;
|
||||
}
|
||||
}
|
||||
|
||||
// SOURCE DIRECTIVES ////////////////////////////////////////////////
|
||||
for each(var sdi in SD) {
|
||||
if (dirname === sdi) {
|
||||
// process dirs, and enforce that 'self' is defined.
|
||||
var dv = CSPSourceList.fromString(dirvalue, aCSPR, selfUri,
|
||||
enforceSelfChecks);
|
||||
if (dv) {
|
||||
aCSPR._directives[sdi] = dv;
|
||||
continue directive;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// REPORT URI ///////////////////////////////////////////////////////
|
||||
if (dirname === UD.REPORT_URI) {
|
||||
// might be space-separated list of URIs
|
||||
var uriStrings = dirvalue.split(/\s+/);
|
||||
var okUriStrings = [];
|
||||
|
||||
for (let i in uriStrings) {
|
||||
var uri = null;
|
||||
try {
|
||||
// Relative URIs are okay, but to ensure we send the reports to the
|
||||
// right spot, the relative URIs are expanded here during parsing.
|
||||
// The resulting CSPRep instance will have only absolute URIs.
|
||||
uri = gIoService.newURI(uriStrings[i],null,selfUri);
|
||||
|
||||
// if there's no host, this will throw NS_ERROR_FAILURE, causing a
|
||||
// parse failure.
|
||||
uri.host;
|
||||
|
||||
// warn about, but do not prohibit non-http and non-https schemes for
|
||||
// reporting URIs. The spec allows unrestricted URIs resolved
|
||||
// relative to "self", but we should let devs know if the scheme is
|
||||
// abnormal and may fail a POST.
|
||||
if (!uri.schemeIs("http") && !uri.schemeIs("https")) {
|
||||
cspWarn(aCSPR, CSPLocalizer.getFormatStr("reportURInotHttpsOrHttp2",
|
||||
[uri.asciiSpec]));
|
||||
}
|
||||
} catch(e) {
|
||||
switch (e.result) {
|
||||
case Components.results.NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS:
|
||||
case Components.results.NS_ERROR_HOST_IS_IP_ADDRESS:
|
||||
if (uri.host !== selfUri.host) {
|
||||
cspWarn(aCSPR,
|
||||
CSPLocalizer.getFormatStr("pageCannotSendReportsTo",
|
||||
[selfUri.host, uri.host]));
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
cspWarn(aCSPR, CSPLocalizer.getFormatStr("couldNotParseReportURI",
|
||||
[uriStrings[i]]));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// all verification passed
|
||||
okUriStrings.push(uri.asciiSpec);
|
||||
}
|
||||
aCSPR._directives[UD.REPORT_URI] = okUriStrings.join(' ');
|
||||
continue directive;
|
||||
}
|
||||
|
||||
// POLICY URI //////////////////////////////////////////////////////////
|
||||
if (dirname === UD.POLICY_URI) {
|
||||
// POLICY_URI can only be alone
|
||||
if (aCSPR._directives.length > 0 || dirs.length > 1) {
|
||||
cspError(aCSPR, CSPLocalizer.getStr("policyURINotAlone"));
|
||||
return CSPRep.fromString("default-src 'none'", null, reportOnly);
|
||||
}
|
||||
// if we were called without a reference to the parent document request
|
||||
// we won't be able to suspend it while we fetch the policy -> fail closed
|
||||
if (!docRequest || !csp) {
|
||||
cspError(aCSPR, CSPLocalizer.getStr("noParentRequest"));
|
||||
return CSPRep.fromString("default-src 'none'", null, reportOnly);
|
||||
}
|
||||
|
||||
var uri = '';
|
||||
try {
|
||||
uri = gIoService.newURI(dirvalue, null, selfUri);
|
||||
} catch(e) {
|
||||
cspError(aCSPR, CSPLocalizer.getFormatStr("policyURIParseError",
|
||||
[dirvalue]));
|
||||
return CSPRep.fromString("default-src 'none'", null, reportOnly);
|
||||
}
|
||||
|
||||
// Verify that policy URI comes from the same origin
|
||||
if (selfUri) {
|
||||
if (selfUri.host !== uri.host) {
|
||||
cspError(aCSPR, CSPLocalizer.getFormatStr("nonMatchingHost",
|
||||
[uri.host]));
|
||||
return CSPRep.fromString("default-src 'none'", null, reportOnly);
|
||||
}
|
||||
if (selfUri.port !== uri.port) {
|
||||
cspError(aCSPR, CSPLocalizer.getFormatStr("nonMatchingPort",
|
||||
[uri.port.toString()]));
|
||||
return CSPRep.fromString("default-src 'none'", null, reportOnly);
|
||||
}
|
||||
if (selfUri.scheme !== uri.scheme) {
|
||||
cspError(aCSPR, CSPLocalizer.getFormatStr("nonMatchingScheme",
|
||||
[uri.scheme]));
|
||||
return CSPRep.fromString("default-src 'none'", null, reportOnly);
|
||||
}
|
||||
}
|
||||
|
||||
// suspend the parent document request while we fetch the policy-uri
|
||||
try {
|
||||
docRequest.suspend();
|
||||
var chan = gIoService.newChannel(uri.asciiSpec, null, null);
|
||||
// make request anonymous (no cookies, etc.) so the request for the
|
||||
// policy-uri can't be abused for CSRF
|
||||
chan.loadFlags |= Ci.nsIChannel.LOAD_ANONYMOUS;
|
||||
chan.loadGroup = docRequest.loadGroup;
|
||||
chan.asyncOpen(new CSPPolicyURIListener(uri, docRequest, csp, reportOnly), null);
|
||||
}
|
||||
catch (e) {
|
||||
// resume the document request and apply most restrictive policy
|
||||
docRequest.resume();
|
||||
cspError(aCSPR, CSPLocalizer.getFormatStr("errorFetchingPolicy",
|
||||
[e.toString()]));
|
||||
return CSPRep.fromString("default-src 'none'", null, reportOnly);
|
||||
}
|
||||
|
||||
// return a fully-open policy to be used until the contents of the
|
||||
// policy-uri come back.
|
||||
return CSPRep.fromString("default-src *", null, reportOnly);
|
||||
}
|
||||
|
||||
// UNIDENTIFIED DIRECTIVE /////////////////////////////////////////////
|
||||
cspWarn(aCSPR, CSPLocalizer.getFormatStr("couldNotProcessUnknownDirective",
|
||||
[dirname]));
|
||||
|
||||
} // end directive: loop
|
||||
|
||||
// the X-Content-Security-Policy syntax requires an allow or default-src
|
||||
// directive to be present.
|
||||
if (!aCSPR._directives[SD.DEFAULT_SRC]) {
|
||||
cspWarn(aCSPR, CSPLocalizer.getStr("allowOrDefaultSrcRequired"));
|
||||
return CSPRep.fromString("default-src 'none'", null, reportOnly);
|
||||
}
|
||||
|
||||
// If this is a Report-Only header and report-uri is not in the directive
|
||||
// list, tell developer either specify report-uri directive or use
|
||||
// a non-Report-Only CSP header.
|
||||
if (aCSPR._reportOnlyMode && !aCSPR._directives.hasOwnProperty(UD.REPORT_URI)) {
|
||||
cspWarn(aCSPR, CSPLocalizer.getFormatStr("reportURInotInReportOnlyHeader",
|
||||
[selfUri ? selfUri.prePath : "undefined"]))
|
||||
}
|
||||
|
||||
return aCSPR;
|
||||
};
|
||||
|
||||
/**
|
||||
* Factory to create a new CSPRep, parsed from a string, compliant
|
||||
* with the CSP 1.0 spec.
|
||||
@ -556,13 +268,11 @@ CSPRep.fromString = function(aStr, self, reportOnly, docRequest, csp,
|
||||
* @returns
|
||||
* an instance of CSPRep
|
||||
*/
|
||||
// When we deprecate our original CSP implementation, we rename this to
|
||||
// CSPRep.fromString and remove the existing CSPRep.fromString above.
|
||||
CSPRep.fromStringSpecCompliant = function(aStr, self, reportOnly, docRequest, csp,
|
||||
enforceSelfChecks) {
|
||||
var SD = CSPRep.SRC_DIRECTIVES_NEW;
|
||||
CSPRep.fromString = function(aStr, self, reportOnly, docRequest, csp,
|
||||
enforceSelfChecks) {
|
||||
var SD = CSPRep.SRC_DIRECTIVES;
|
||||
var UD = CSPRep.URI_DIRECTIVES;
|
||||
var aCSPR = new CSPRep(true);
|
||||
var aCSPR = new CSPRep();
|
||||
aCSPR._originalText = aStr;
|
||||
aCSPR._innerWindowID = innerWindowFromRequest(docRequest);
|
||||
if (typeof reportOnly === 'undefined') reportOnly = false;
|
||||
@ -587,7 +297,10 @@ CSPRep.fromStringSpecCompliant = function(aStr, self, reportOnly, docRequest, cs
|
||||
|
||||
var dirname = dir.split(/\s+/)[0].toLowerCase();
|
||||
var dirvalue = dir.substring(dirname.length).trim();
|
||||
dirs[dirname] = dirvalue;
|
||||
// skip duplicates
|
||||
if (!dirs.hasOwnProperty(dirname)) {
|
||||
dirs[dirname] = dirvalue;
|
||||
}
|
||||
}
|
||||
|
||||
// Spec compliant policies have different default behavior for inline
|
||||
@ -712,13 +425,13 @@ CSPRep.fromStringSpecCompliant = function(aStr, self, reportOnly, docRequest, cs
|
||||
// POLICY_URI can only be alone
|
||||
if (aCSPR._directives.length > 0 || dirs.length > 1) {
|
||||
cspError(aCSPR, CSPLocalizer.getStr("policyURINotAlone"));
|
||||
return CSPRep.fromStringSpecCompliant("default-src 'none'", null, reportOnly);
|
||||
return CSPRep.fromString("default-src 'none'", null, reportOnly);
|
||||
}
|
||||
// if we were called without a reference to the parent document request
|
||||
// we won't be able to suspend it while we fetch the policy -> fail closed
|
||||
if (!docRequest || !csp) {
|
||||
cspError(aCSPR, CSPLocalizer.getStr("noParentRequest"));
|
||||
return CSPRep.fromStringSpecCompliant("default-src 'none'", null, reportOnly);
|
||||
return CSPRep.fromString("default-src 'none'", null, reportOnly);
|
||||
}
|
||||
|
||||
var uri = '';
|
||||
@ -726,22 +439,22 @@ CSPRep.fromStringSpecCompliant = function(aStr, self, reportOnly, docRequest, cs
|
||||
uri = gIoService.newURI(dirvalue, null, selfUri);
|
||||
} catch(e) {
|
||||
cspError(aCSPR, CSPLocalizer.getFormatStr("policyURIParseError", [dirvalue]));
|
||||
return CSPRep.fromStringSpecCompliant("default-src 'none'", null, reportOnly);
|
||||
return CSPRep.fromString("default-src 'none'", null, reportOnly);
|
||||
}
|
||||
|
||||
// Verify that policy URI comes from the same origin
|
||||
if (selfUri) {
|
||||
if (selfUri.host !== uri.host){
|
||||
cspError(aCSPR, CSPLocalizer.getFormatStr("nonMatchingHost", [uri.host]));
|
||||
return CSPRep.fromStringSpecCompliant("default-src 'none'", null, reportOnly);
|
||||
return CSPRep.fromString("default-src 'none'", null, reportOnly);
|
||||
}
|
||||
if (selfUri.port !== uri.port){
|
||||
cspError(aCSPR, CSPLocalizer.getFormatStr("nonMatchingPort", [uri.port.toString()]));
|
||||
return CSPRep.fromStringSpecCompliant("default-src 'none'", null, reportOnly);
|
||||
return CSPRep.fromString("default-src 'none'", null, reportOnly);
|
||||
}
|
||||
if (selfUri.scheme !== uri.scheme){
|
||||
cspError(aCSPR, CSPLocalizer.getFormatStr("nonMatchingScheme", [uri.scheme]));
|
||||
return CSPRep.fromStringSpecCompliant("default-src 'none'", null, reportOnly);
|
||||
return CSPRep.fromString("default-src 'none'", null, reportOnly);
|
||||
}
|
||||
}
|
||||
|
||||
@ -759,12 +472,12 @@ CSPRep.fromStringSpecCompliant = function(aStr, self, reportOnly, docRequest, cs
|
||||
// resume the document request and apply most restrictive policy
|
||||
docRequest.resume();
|
||||
cspError(aCSPR, CSPLocalizer.getFormatStr("errorFetchingPolicy", [e.toString()]));
|
||||
return CSPRep.fromStringSpecCompliant("default-src 'none'", null, reportOnly);
|
||||
return CSPRep.fromString("default-src 'none'", null, reportOnly);
|
||||
}
|
||||
|
||||
// return a fully-open policy to be used until the contents of the
|
||||
// policy-uri come back
|
||||
return CSPRep.fromStringSpecCompliant("default-src *", null, reportOnly);
|
||||
return CSPRep.fromString("default-src *", null, reportOnly);
|
||||
}
|
||||
|
||||
// UNIDENTIFIED DIRECTIVE /////////////////////////////////////////////
|
||||
@ -819,10 +532,6 @@ CSPRep.prototype = {
|
||||
function csp_toString() {
|
||||
var dirs = [];
|
||||
|
||||
if (!this._specCompliant && (this._allowEval || this._allowInlineScripts)) {
|
||||
dirs.push("options" + (this._allowEval ? " eval-script" : "")
|
||||
+ (this._allowInlineScripts ? " inline-script" : ""));
|
||||
}
|
||||
for (var i in this._directives) {
|
||||
if (this._directives[i]) {
|
||||
dirs.push(i + " " + this._directives[i].toString());
|
||||
@ -867,7 +576,7 @@ CSPRep.prototype = {
|
||||
return true;
|
||||
|
||||
// make sure the right directive set is used
|
||||
let DIRS = this._specCompliant ? CSPRep.SRC_DIRECTIVES_NEW : CSPRep.SRC_DIRECTIVES_OLD;
|
||||
let DIRS = CSPRep.SRC_DIRECTIVES;
|
||||
|
||||
let directiveInPolicy = false;
|
||||
for (var i in DIRS) {
|
||||
@ -904,8 +613,8 @@ CSPRep.prototype = {
|
||||
}
|
||||
|
||||
// no relevant directives present -- this means for CSP 1.0 that the load
|
||||
// should be permitted (and for the old CSP, to block it).
|
||||
return this._specCompliant;
|
||||
// should be permitted.
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
@ -1541,7 +1250,11 @@ CSPSource.prototype = {
|
||||
s = s + this.scheme + "://";
|
||||
if (this._host)
|
||||
s = s + this._host;
|
||||
if (this.port)
|
||||
|
||||
// CSP 1.0 4.11 says the report should use URI-reference from RFC 3986,
|
||||
// 3.2.3 and indicates that the default port should be omitted.
|
||||
// Non-default ports are included.
|
||||
if (this.port && gIoService.getProtocolHandler(this.scheme).defaultPort != this.port)
|
||||
s = s + ":" + this.port;
|
||||
return s;
|
||||
},
|
||||
|
@ -24,11 +24,6 @@ const Cu = Components.utils;
|
||||
|
||||
const CSP_VIOLATION_TOPIC = "csp-on-violate-policy";
|
||||
|
||||
// Needed to support CSP 1.0 spec and our original CSP implementation - should
|
||||
// be removed when our original implementation is deprecated.
|
||||
const CSP_TYPE_XMLHTTPREQUEST_SPEC_COMPLIANT = "csp_type_xmlhttprequest_spec_compliant";
|
||||
const CSP_TYPE_WEBSOCKET_SPEC_COMPLIANT = "csp_type_websocket_spec_compliant";
|
||||
|
||||
const WARN_FLAG = Ci.nsIScriptError.warningFlag;
|
||||
const ERROR_FLAG = Ci.nsIScriptError.ERROR_FLAG;
|
||||
|
||||
@ -71,14 +66,13 @@ function ContentSecurityPolicy() {
|
||||
{
|
||||
let cp = Ci.nsIContentPolicy;
|
||||
let csp = ContentSecurityPolicy;
|
||||
let cspr_sd_old = CSPRep.SRC_DIRECTIVES_OLD;
|
||||
let cspr_sd_new = CSPRep.SRC_DIRECTIVES_NEW;
|
||||
let cspr_sd = CSPRep.SRC_DIRECTIVES;
|
||||
|
||||
csp._MAPPINGS=[];
|
||||
|
||||
/* default, catch-all case */
|
||||
// This is the same in old and new CSP so use the new mapping.
|
||||
csp._MAPPINGS[cp.TYPE_OTHER] = cspr_sd_new.DEFAULT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_OTHER] = cspr_sd.DEFAULT_SRC;
|
||||
|
||||
/* self */
|
||||
csp._MAPPINGS[cp.TYPE_DOCUMENT] = null;
|
||||
@ -87,44 +81,26 @@ function ContentSecurityPolicy() {
|
||||
csp._MAPPINGS[cp.TYPE_REFRESH] = null;
|
||||
|
||||
/* categorized content types */
|
||||
// These are the same in old and new CSP's so just use the new mappings.
|
||||
csp._MAPPINGS[cp.TYPE_SCRIPT] = cspr_sd_new.SCRIPT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_IMAGE] = cspr_sd_new.IMG_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_STYLESHEET] = cspr_sd_new.STYLE_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_OBJECT] = cspr_sd_new.OBJECT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_OBJECT_SUBREQUEST] = cspr_sd_new.OBJECT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_SUBDOCUMENT] = cspr_sd_new.FRAME_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_MEDIA] = cspr_sd_new.MEDIA_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_FONT] = cspr_sd_new.FONT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_XSLT] = cspr_sd_new.SCRIPT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_BEACON] = cspr_sd_new.CONNECT_SRC;
|
||||
|
||||
/* Our original CSP implementation's mappings for XHR and websocket
|
||||
* These should be changed to be = cspr_sd.CONNECT_SRC when we remove
|
||||
* the original implementation - NOTE: order in this array is important !!!
|
||||
*/
|
||||
csp._MAPPINGS[cp.TYPE_XMLHTTPREQUEST] = cspr_sd_old.XHR_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_WEBSOCKET] = cspr_sd_old.XHR_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_SCRIPT] = cspr_sd.SCRIPT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_IMAGE] = cspr_sd.IMG_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_STYLESHEET] = cspr_sd.STYLE_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_OBJECT] = cspr_sd.OBJECT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_OBJECT_SUBREQUEST] = cspr_sd.OBJECT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_SUBDOCUMENT] = cspr_sd.FRAME_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_MEDIA] = cspr_sd.MEDIA_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_FONT] = cspr_sd.FONT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_XSLT] = cspr_sd.SCRIPT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_BEACON] = cspr_sd.CONNECT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_XMLHTTPREQUEST] = cspr_sd.CONNECT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_WEBSOCKET] = cspr_sd.CONNECT_SRC;
|
||||
|
||||
/* CSP cannot block CSP reports */
|
||||
csp._MAPPINGS[cp.TYPE_CSP_REPORT] = null;
|
||||
|
||||
/* These must go through the catch-all */
|
||||
csp._MAPPINGS[cp.TYPE_XBL] = cspr_sd_new.DEFAULT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_PING] = cspr_sd_new.DEFAULT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_DTD] = cspr_sd_new.DEFAULT_SRC;
|
||||
|
||||
/* CSP 1.0 spec compliant mappings for XHR and websocket */
|
||||
// The directive name for XHR, websocket, and EventSource is different
|
||||
// in the 1.0 spec than in our original implementation, these mappings
|
||||
// address this. These won't be needed when we deprecate our original
|
||||
// implementation.
|
||||
csp._MAPPINGS[CSP_TYPE_XMLHTTPREQUEST_SPEC_COMPLIANT] = cspr_sd_new.CONNECT_SRC;
|
||||
csp._MAPPINGS[CSP_TYPE_WEBSOCKET_SPEC_COMPLIANT] = cspr_sd_new.CONNECT_SRC;
|
||||
// TODO : EventSource will be here and also will use connect-src
|
||||
// after we fix Bug 802872 - CSP should restrict EventSource using the connect-src
|
||||
// directive. For background see Bug 667490 - EventSource should use the same
|
||||
// nsIContentPolicy type as XHR (which is fixed)
|
||||
csp._MAPPINGS[cp.TYPE_XBL] = cspr_sd.DEFAULT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_PING] = cspr_sd.DEFAULT_SRC;
|
||||
csp._MAPPINGS[cp.TYPE_DTD] = cspr_sd.DEFAULT_SRC;
|
||||
}
|
||||
|
||||
ContentSecurityPolicy.prototype = {
|
||||
@ -157,7 +133,7 @@ ContentSecurityPolicy.prototype = {
|
||||
|
||||
_buildViolatedDirectiveString:
|
||||
function(aDirectiveName, aPolicy) {
|
||||
var SD = CSPRep.SRC_DIRECTIVES_NEW;
|
||||
var SD = CSPRep.SRC_DIRECTIVES;
|
||||
var cspContext = (SD[aDirectiveName] in aPolicy._directives) ? SD[aDirectiveName] : SD.DEFAULT_SRC;
|
||||
var directive = aPolicy._directives[cspContext];
|
||||
return cspContext + ' ' + directive.toString();
|
||||
@ -410,8 +386,7 @@ ContentSecurityPolicy.prototype = {
|
||||
*/
|
||||
appendPolicy:
|
||||
function csp_appendPolicy(aPolicy, selfURI, aReportOnly, aSpecCompliant) {
|
||||
return this._appendPolicyInternal(aPolicy, selfURI, aReportOnly,
|
||||
aSpecCompliant, true);
|
||||
return this._appendPolicyInternal(aPolicy, selfURI, aReportOnly, true);
|
||||
},
|
||||
|
||||
/**
|
||||
@ -420,12 +395,10 @@ ContentSecurityPolicy.prototype = {
|
||||
* @returns the count of policies.
|
||||
*/
|
||||
_appendPolicyInternal:
|
||||
function csp_appendPolicy(aPolicy, selfURI, aReportOnly, aSpecCompliant,
|
||||
aEnforceSelfChecks) {
|
||||
function csp_appendPolicy(aPolicy, selfURI, aReportOnly, aEnforceSelfChecks) {
|
||||
#ifndef MOZ_B2G
|
||||
CSPdebug("APPENDING POLICY: " + aPolicy);
|
||||
CSPdebug(" SELF: " + (selfURI ? selfURI.asciiSpec : " null"));
|
||||
CSPdebug("CSP 1.0 COMPLIANT : " + aSpecCompliant);
|
||||
#endif
|
||||
|
||||
// For nested schemes such as view-source: make sure we are taking the
|
||||
@ -446,26 +419,9 @@ ContentSecurityPolicy.prototype = {
|
||||
// Note that we pass the full URI since when it's parsed as 'self' to construct a
|
||||
// CSPSource only the scheme, host, and port are kept.
|
||||
|
||||
// If we want to be CSP 1.0 spec compliant, use the new parser.
|
||||
// The old one will be deprecated in the future and will be
|
||||
// removed at that time.
|
||||
if (aSpecCompliant) {
|
||||
newpolicy = CSPRep.fromStringSpecCompliant(aPolicy,
|
||||
selfURI,
|
||||
aReportOnly,
|
||||
this._weakDocRequest.get(),
|
||||
this,
|
||||
aEnforceSelfChecks);
|
||||
} else {
|
||||
newpolicy = CSPRep.fromString(aPolicy,
|
||||
selfURI,
|
||||
aReportOnly,
|
||||
this._weakDocRequest.get(),
|
||||
this,
|
||||
aEnforceSelfChecks);
|
||||
}
|
||||
|
||||
newpolicy._specCompliant = !!aSpecCompliant;
|
||||
newpolicy = CSPRep.fromString(aPolicy, selfURI, aReportOnly,
|
||||
this._weakDocRequest.get(),
|
||||
this, aEnforceSelfChecks);
|
||||
newpolicy._isInitialized = true;
|
||||
this._policies.push(newpolicy);
|
||||
this._cache.clear(); // reset cache since effective policy changes
|
||||
@ -711,7 +667,7 @@ ContentSecurityPolicy.prototype = {
|
||||
// scan the discovered ancestors
|
||||
// frame-ancestors is the same in both old and new source directives,
|
||||
// so don't need to differentiate here.
|
||||
let cspContext = CSPRep.SRC_DIRECTIVES_NEW.FRAME_ANCESTORS;
|
||||
let cspContext = CSPRep.SRC_DIRECTIVES.FRAME_ANCESTORS;
|
||||
for (let i in ancestors) {
|
||||
let ancestor = ancestors[i];
|
||||
if (!policy.permits(ancestor, cspContext)) {
|
||||
@ -806,22 +762,11 @@ ContentSecurityPolicy.prototype = {
|
||||
for (let policyIndex=0; policyIndex < this._policies.length; policyIndex++) {
|
||||
let policy = this._policies[policyIndex];
|
||||
|
||||
cspContext = ContentSecurityPolicy._MAPPINGS[aContentType];
|
||||
|
||||
#ifndef MOZ_B2G
|
||||
CSPdebug("policy is " + (policy._specCompliant ?
|
||||
"1.0 compliant" : "pre-1.0"));
|
||||
CSPdebug("policy is " + (policy._reportOnlyMode ?
|
||||
"report-only" : "blocking"));
|
||||
#endif
|
||||
|
||||
if (aContentType == cp.TYPE_XMLHTTPREQUEST && this._policies[policyIndex]._specCompliant) {
|
||||
cspContext = ContentSecurityPolicy._MAPPINGS[CSP_TYPE_XMLHTTPREQUEST_SPEC_COMPLIANT];
|
||||
} else if (aContentType == cp.TYPE_WEBSOCKET && this._policies[policyIndex]._specCompliant) {
|
||||
cspContext = ContentSecurityPolicy._MAPPINGS[CSP_TYPE_WEBSOCKET_SPEC_COMPLIANT];
|
||||
} else {
|
||||
cspContext = ContentSecurityPolicy._MAPPINGS[aContentType];
|
||||
}
|
||||
|
||||
#ifndef MOZ_B2G
|
||||
CSPdebug("shouldLoad cspContext = " + cspContext);
|
||||
#endif
|
||||
|
||||
@ -979,11 +924,9 @@ ContentSecurityPolicy.prototype = {
|
||||
for (let pCount = aStream.read32(); pCount > 0; pCount--) {
|
||||
let polStr = aStream.readString();
|
||||
let reportOnly = aStream.readBoolean();
|
||||
let specCompliant = aStream.readBoolean();
|
||||
// don't need self info because when the policy is turned back into a
|
||||
// string, 'self' is replaced with the explicit source expression.
|
||||
this._appendPolicyInternal(polStr, null, reportOnly, specCompliant,
|
||||
false);
|
||||
this._appendPolicyInternal(polStr, null, reportOnly, false);
|
||||
}
|
||||
|
||||
// NOTE: the document instance that's deserializing this object (via its
|
||||
@ -1010,7 +953,6 @@ ContentSecurityPolicy.prototype = {
|
||||
for each (var policy in this._policies) {
|
||||
aStream.writeWStringZ(policy.toString());
|
||||
aStream.writeBoolean(policy._reportOnlyMode);
|
||||
aStream.writeBoolean(policy._specCompliant);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
@ -821,6 +821,7 @@ class CSPReportSenderRunnable MOZ_FINAL : public nsRunnable
|
||||
CSPReportSenderRunnable(nsISupports* aBlockedContentSource,
|
||||
nsIURI* aOriginalURI,
|
||||
uint32_t aViolatedPolicyIndex,
|
||||
bool aReportOnlyFlag,
|
||||
const nsAString& aViolatedDirective,
|
||||
const nsAString& aObserverSubject,
|
||||
const nsAString& aSourceFile,
|
||||
@ -831,6 +832,7 @@ class CSPReportSenderRunnable MOZ_FINAL : public nsRunnable
|
||||
: mBlockedContentSource(aBlockedContentSource)
|
||||
, mOriginalURI(aOriginalURI)
|
||||
, mViolatedPolicyIndex(aViolatedPolicyIndex)
|
||||
, mReportOnlyFlag(aReportOnlyFlag)
|
||||
, mViolatedDirective(aViolatedDirective)
|
||||
, mSourceFile(aSourceFile)
|
||||
, mScriptSample(aScriptSample)
|
||||
@ -887,7 +889,9 @@ class CSPReportSenderRunnable MOZ_FINAL : public nsRunnable
|
||||
nsString blockedDataChar16 = NS_ConvertUTF8toUTF16(blockedDataStr);
|
||||
const char16_t* params[] = { mViolatedDirective.get(),
|
||||
blockedDataChar16.get() };
|
||||
CSP_LogLocalizedStr(NS_LITERAL_STRING("CSPViolationWithURI").get(),
|
||||
|
||||
CSP_LogLocalizedStr(mReportOnlyFlag ? NS_LITERAL_STRING("CSPROViolationWithURI").get() :
|
||||
NS_LITERAL_STRING("CSPViolationWithURI").get(),
|
||||
params, ArrayLength(params),
|
||||
mSourceFile, mScriptSample, mLineNum, 0,
|
||||
nsIScriptError::errorFlag, "CSP", mInnerWindowID);
|
||||
@ -899,6 +903,7 @@ class CSPReportSenderRunnable MOZ_FINAL : public nsRunnable
|
||||
nsCOMPtr<nsISupports> mBlockedContentSource;
|
||||
nsCOMPtr<nsIURI> mOriginalURI;
|
||||
uint32_t mViolatedPolicyIndex;
|
||||
bool mReportOnlyFlag;
|
||||
nsString mViolatedDirective;
|
||||
nsCOMPtr<nsISupports> mObserverSubject;
|
||||
nsString mSourceFile;
|
||||
@ -943,9 +948,12 @@ nsCSPContext::AsyncReportViolation(nsISupports* aBlockedContentSource,
|
||||
const nsAString& aScriptSample,
|
||||
uint32_t aLineNum)
|
||||
{
|
||||
NS_ENSURE_ARG_MAX(aViolatedPolicyIndex, mPolicies.Length() - 1);
|
||||
|
||||
NS_DispatchToMainThread(new CSPReportSenderRunnable(aBlockedContentSource,
|
||||
aOriginalURI,
|
||||
aViolatedPolicyIndex,
|
||||
mPolicies[aViolatedPolicyIndex]->getReportOnlyFlag(),
|
||||
aViolatedDirective,
|
||||
aObserverSubject,
|
||||
aSourceFile,
|
||||
|
@ -519,7 +519,7 @@ nsContentList::Item(uint32_t aIndex, bool aDoFlush)
|
||||
}
|
||||
|
||||
if (mState != LIST_UP_TO_DATE)
|
||||
PopulateSelf(std::min(aIndex, uint32_t(UINT32_MAX - 1)) + 1);
|
||||
PopulateSelf(std::min(aIndex, UINT32_MAX - 1) + 1);
|
||||
|
||||
ASSERT_IN_SYNC;
|
||||
NS_ASSERTION(!mRootNode || mState != LIST_DIRTY,
|
||||
|
@ -2682,18 +2682,9 @@ nsDocument::InitCSP(nsIChannel* aChannel)
|
||||
}
|
||||
|
||||
nsAutoCString tCspHeaderValue, tCspROHeaderValue;
|
||||
nsAutoCString tCspOldHeaderValue, tCspOldROHeaderValue;
|
||||
|
||||
nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aChannel);
|
||||
if (httpChannel) {
|
||||
httpChannel->GetResponseHeader(
|
||||
NS_LITERAL_CSTRING("x-content-security-policy"),
|
||||
tCspOldHeaderValue);
|
||||
|
||||
httpChannel->GetResponseHeader(
|
||||
NS_LITERAL_CSTRING("x-content-security-policy-report-only"),
|
||||
tCspOldROHeaderValue);
|
||||
|
||||
httpChannel->GetResponseHeader(
|
||||
NS_LITERAL_CSTRING("content-security-policy"),
|
||||
tCspHeaderValue);
|
||||
@ -2704,35 +2695,6 @@ nsDocument::InitCSP(nsIChannel* aChannel)
|
||||
}
|
||||
NS_ConvertASCIItoUTF16 cspHeaderValue(tCspHeaderValue);
|
||||
NS_ConvertASCIItoUTF16 cspROHeaderValue(tCspROHeaderValue);
|
||||
NS_ConvertASCIItoUTF16 cspOldHeaderValue(tCspOldHeaderValue);
|
||||
NS_ConvertASCIItoUTF16 cspOldROHeaderValue(tCspOldROHeaderValue);
|
||||
|
||||
// Only use the CSP 1.0 spec compliant headers if a pref to do so
|
||||
// is set. This lets us turn on the 1.0 parser per platform. This
|
||||
// pref is also set by the tests for 1.0 spec compliant CSP.
|
||||
bool specCompliantEnabled =
|
||||
Preferences::GetBool("security.csp.speccompliant");
|
||||
|
||||
// If spec compliant pref isn't set, pretend we never got these headers.
|
||||
if ((!cspHeaderValue.IsEmpty() || !cspROHeaderValue.IsEmpty()) &&
|
||||
!specCompliantEnabled) {
|
||||
PR_LOG(gCspPRLog, PR_LOG_DEBUG,
|
||||
("Got spec compliant CSP headers but pref was not set"));
|
||||
cspHeaderValue.Truncate();
|
||||
cspROHeaderValue.Truncate();
|
||||
}
|
||||
|
||||
// If both the new header AND the old header are present, warn that
|
||||
// the old header will be ignored. Otherwise, if the old header is
|
||||
// present, warn that it will be deprecated.
|
||||
bool oldHeaderIsPresent = !cspOldHeaderValue.IsEmpty() || !cspOldROHeaderValue.IsEmpty();
|
||||
bool newHeaderIsPresent = !cspHeaderValue.IsEmpty() || !cspROHeaderValue.IsEmpty();
|
||||
|
||||
if (oldHeaderIsPresent && newHeaderIsPresent) {
|
||||
mCSPWebConsoleErrorQueue.Add("BothCSPHeadersPresent");
|
||||
} else if (oldHeaderIsPresent) {
|
||||
mCSPWebConsoleErrorQueue.Add("OldCSPHeaderDeprecated");
|
||||
}
|
||||
|
||||
// Figure out if we need to apply an app default CSP or a CSP from an app manifest
|
||||
nsIPrincipal* principal = NodePrincipal();
|
||||
@ -2760,9 +2722,7 @@ nsDocument::InitCSP(nsIChannel* aChannel)
|
||||
if (!applyAppDefaultCSP &&
|
||||
!applyAppManifestCSP &&
|
||||
cspHeaderValue.IsEmpty() &&
|
||||
cspROHeaderValue.IsEmpty() &&
|
||||
cspOldHeaderValue.IsEmpty() &&
|
||||
cspOldROHeaderValue.IsEmpty()) {
|
||||
cspROHeaderValue.IsEmpty()) {
|
||||
#ifdef PR_LOGGING
|
||||
nsCOMPtr<nsIURI> chanURI;
|
||||
aChannel->GetURI(getter_AddRefs(chanURI));
|
||||
@ -2812,7 +2772,7 @@ nsDocument::InitCSP(nsIChannel* aChannel)
|
||||
// * however, we still support XCSP headers during the transition phase
|
||||
// and fall back to the JS implementation if we find an XCSP header.
|
||||
|
||||
if (newHeaderIsPresent && CSPService::sNewBackendEnabled) {
|
||||
if (CSPService::sNewBackendEnabled) {
|
||||
csp = do_CreateInstance("@mozilla.org/cspcontext;1", &rv);
|
||||
}
|
||||
else {
|
||||
@ -2845,36 +2805,25 @@ nsDocument::InitCSP(nsIChannel* aChannel)
|
||||
}
|
||||
|
||||
if (appCSP) {
|
||||
// Use the 1.0 CSP parser for apps if the pref to do so is set.
|
||||
csp->AppendPolicy(appCSP, selfURI, false, specCompliantEnabled);
|
||||
csp->AppendPolicy(appCSP, selfURI, false, true);
|
||||
}
|
||||
}
|
||||
|
||||
// ----- if the doc is an app and specifies a CSP in its manifest, apply it.
|
||||
if (applyAppManifestCSP) {
|
||||
// Use the 1.0 CSP parser for apps if the pref to do so is set.
|
||||
csp->AppendPolicy(appManifestCSP, selfURI, false, specCompliantEnabled);
|
||||
csp->AppendPolicy(appManifestCSP, selfURI, false, true);
|
||||
}
|
||||
|
||||
// While we are supporting both CSP 1.0 and the x- headers, the 1.0 headers
|
||||
// take priority. If both are present, the x-* headers are ignored.
|
||||
|
||||
// ----- if there's a full-strength CSP header, apply it.
|
||||
if (!cspHeaderValue.IsEmpty()) {
|
||||
rv = AppendCSPFromHeader(csp, cspHeaderValue, selfURI, false, true);
|
||||
NS_ENSURE_SUCCESS(rv, rv);
|
||||
} else if (!cspOldHeaderValue.IsEmpty()) {
|
||||
rv = AppendCSPFromHeader(csp, cspOldHeaderValue, selfURI, false, false);
|
||||
NS_ENSURE_SUCCESS(rv, rv);
|
||||
}
|
||||
|
||||
// ----- if there's a report-only CSP header, apply it.
|
||||
if (!cspROHeaderValue.IsEmpty()) {
|
||||
rv = AppendCSPFromHeader(csp, cspROHeaderValue, selfURI, true, true);
|
||||
NS_ENSURE_SUCCESS(rv, rv);
|
||||
} else if (!cspOldROHeaderValue.IsEmpty()) {
|
||||
rv = AppendCSPFromHeader(csp, cspOldROHeaderValue, selfURI, true, false);
|
||||
NS_ENSURE_SUCCESS(rv, rv);
|
||||
}
|
||||
|
||||
// ----- Enforce frame-ancestor policy on any applied policies
|
||||
|
@ -1715,7 +1715,7 @@ private:
|
||||
nsRefPtr<mozilla::dom::ImportManager> mImportManager;
|
||||
|
||||
#ifdef DEBUG
|
||||
protected:
|
||||
public:
|
||||
bool mWillReparent;
|
||||
#endif
|
||||
};
|
||||
|
@ -6,7 +6,6 @@
|
||||
|
||||
TEST_TOOL_DIRS += [
|
||||
'csp',
|
||||
'xcsp',
|
||||
'websocket_hybi',
|
||||
]
|
||||
|
||||
|
@ -1,163 +0,0 @@
|
||||
|
||||
const Cc = Components.classes;
|
||||
const Ci = Components.interfaces;
|
||||
const Cu = Components.utils;
|
||||
const Cr = Components.results;
|
||||
|
||||
Cu.import('resource://gre/modules/CSPUtils.jsm');
|
||||
|
||||
var httpserv = null;
|
||||
|
||||
const POLICY_FROM_URI = "allow 'self'; img-src *";
|
||||
const POLICY_PORT = 9000;
|
||||
const POLICY_URI = "http://localhost:" + POLICY_PORT + "/policy";
|
||||
const POLICY_URI_RELATIVE = "/policy";
|
||||
const DOCUMENT_URI = "http://localhost:" + POLICY_PORT + "/document";
|
||||
const CSP_DOC_BODY = "CSP doc content";
|
||||
const SD = CSPRep.SRC_DIRECTIVES;
|
||||
|
||||
// this will get populated by run_tests()
|
||||
var TESTS = [];
|
||||
|
||||
// helper to make URIs
|
||||
function mkuri(foo) {
|
||||
return Cc["@mozilla.org/network/io-service;1"]
|
||||
.getService(Ci.nsIIOService)
|
||||
.newURI(foo, null, null);
|
||||
}
|
||||
|
||||
// helper to use .equals on stuff
|
||||
function do_check_equivalent(foo, bar, stack) {
|
||||
if (!stack)
|
||||
stack = Components.stack.caller;
|
||||
|
||||
var text = foo + ".equals(" + bar + ")";
|
||||
|
||||
if (foo.equals && foo.equals(bar)) {
|
||||
dump("TEST-PASS | " + stack.filename + " | [" + stack.name + " : " +
|
||||
stack.lineNumber + "] " + text + "\n");
|
||||
return;
|
||||
}
|
||||
do_throw(text, stack);
|
||||
}
|
||||
|
||||
function listener(csp, cspr_static) {
|
||||
this.buffer = "";
|
||||
this._csp = csp;
|
||||
this._cspr_static = cspr_static;
|
||||
}
|
||||
|
||||
listener.prototype = {
|
||||
onStartRequest: function (request, ctx) {
|
||||
},
|
||||
|
||||
onDataAvailable: function (request, ctx, stream, offset, count) {
|
||||
var sInputStream = Cc["@mozilla.org/scriptableinputstream;1"]
|
||||
.createInstance(Ci.nsIScriptableInputStream);
|
||||
sInputStream.init(stream);
|
||||
this.buffer = this.buffer.concat(sInputStream.read(count));
|
||||
},
|
||||
|
||||
onStopRequest: function (request, ctx, status) {
|
||||
// make sure that we have the full document content, guaranteeing that
|
||||
// the document channel has been resumed, before we do the comparisons
|
||||
if (this.buffer == CSP_DOC_BODY) {
|
||||
|
||||
// need to re-grab cspr since it may have changed inside the document's
|
||||
// nsIContentSecurityPolicy instance. The problem is, this cspr_str is a
|
||||
// string and not a policy due to the way it's exposed from
|
||||
// nsIContentSecurityPolicy, so we have to re-parse it.
|
||||
let cspr_str = this._csp.getPolicy(0);
|
||||
let cspr = CSPRep.fromString(cspr_str, mkuri(DOCUMENT_URI));
|
||||
|
||||
// and in reparsing it, we lose the 'self' relationships, so need to also
|
||||
// reparse the static one (or find a way to resolve 'self' in the parsed
|
||||
// policy when doing comparisons).
|
||||
let cspr_static_str = this._cspr_static.toString();
|
||||
let cspr_static_reparse = CSPRep.fromString(cspr_static_str, mkuri(DOCUMENT_URI));
|
||||
|
||||
// not null, and one policy .equals the other one
|
||||
do_check_neq(null, cspr);
|
||||
do_check_true(cspr.equals(cspr_static_reparse));
|
||||
|
||||
// final teardown
|
||||
if (TESTS.length == 0) {
|
||||
httpserv.stop(do_test_finished);
|
||||
} else {
|
||||
do_test_finished();
|
||||
(TESTS.shift())();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function run_test() {
|
||||
httpserv = new HttpServer();
|
||||
httpserv.registerPathHandler("/document", csp_doc_response);
|
||||
httpserv.registerPathHandler("/policy", csp_policy_response);
|
||||
httpserv.start(POLICY_PORT);
|
||||
TESTS = [ test_CSPRep_fromPolicyURI, test_CSPRep_fromRelativePolicyURI ];
|
||||
|
||||
// when this triggers the "onStopRequest" callback, it'll
|
||||
// go to the next test.
|
||||
(TESTS.shift())();
|
||||
}
|
||||
|
||||
function makeChan(url) {
|
||||
var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
|
||||
var chan = ios.newChannel(url, null, null).QueryInterface(Ci.nsIHttpChannel);
|
||||
return chan;
|
||||
}
|
||||
|
||||
function csp_doc_response(metadata, response) {
|
||||
response.setStatusLine(metadata.httpVersion, 200, "OK");
|
||||
response.setHeader("Content-Type", "text/html", false);
|
||||
response.bodyOutputStream.write(CSP_DOC_BODY, CSP_DOC_BODY.length);
|
||||
}
|
||||
|
||||
function csp_policy_response(metadata, response) {
|
||||
response.setStatusLine(metadata.httpVersion, 200, "OK");
|
||||
response.setHeader("Content-Type", "text/csp", false);
|
||||
response.bodyOutputStream.write(POLICY_FROM_URI, POLICY_FROM_URI.length);
|
||||
}
|
||||
|
||||
///////////////////// TEST POLICY_URI //////////////////////
|
||||
function test_CSPRep_fromPolicyURI() {
|
||||
do_test_pending();
|
||||
let csp = Cc["@mozilla.org/contentsecuritypolicy;1"]
|
||||
.createInstance(Ci.nsIContentSecurityPolicy);
|
||||
// once the policy-uri is returned we will compare our static CSPRep with one
|
||||
// we generated from the content we got back from the network to make sure
|
||||
// they are equivalent
|
||||
let cspr_static = CSPRep.fromString(POLICY_FROM_URI, mkuri(DOCUMENT_URI));
|
||||
|
||||
// simulates the request for the parent document
|
||||
var docChan = makeChan(DOCUMENT_URI);
|
||||
docChan.asyncOpen(new listener(csp, cspr_static), null);
|
||||
|
||||
// the resulting policy here can be discarded, since it's going to be
|
||||
// "allow *"; when the policy-uri fetching call-back happens, the *real*
|
||||
// policy will be in csp.policy
|
||||
CSPRep.fromString("policy-uri " + POLICY_URI,
|
||||
mkuri(DOCUMENT_URI), false, docChan, csp);
|
||||
}
|
||||
|
||||
function test_CSPRep_fromRelativePolicyURI() {
|
||||
do_test_pending();
|
||||
let csp = Cc["@mozilla.org/contentsecuritypolicy;1"]
|
||||
.createInstance(Ci.nsIContentSecurityPolicy);
|
||||
// once the policy-uri is returned we will compare our static CSPRep with one
|
||||
// we generated from the content we got back from the network to make sure
|
||||
// they are equivalent
|
||||
let cspr_static = CSPRep.fromString(POLICY_FROM_URI, mkuri(DOCUMENT_URI));
|
||||
|
||||
// simulates the request for the parent document
|
||||
var docChan = makeChan(DOCUMENT_URI);
|
||||
docChan.asyncOpen(new listener(csp, cspr_static), null);
|
||||
|
||||
// the resulting policy here can be discarded, since it's going to be
|
||||
// "allow *"; when the policy-uri fetching call-back happens, the *real*
|
||||
// policy will be in csp.policy
|
||||
CSPRep.fromString("policy-uri " + POLICY_URI_RELATIVE,
|
||||
mkuri(DOCUMENT_URI), false, docChan, csp);
|
||||
}
|
@ -27,7 +27,7 @@ function testValidSRCsHostSourceWithSchemeAndPath() {
|
||||
]
|
||||
|
||||
var obj;
|
||||
var expected = "http://test1.example.com:80";
|
||||
var expected = "http://test1.example.com";
|
||||
for (let i in csps) {
|
||||
var src = csps[i];
|
||||
obj = CSPSourceList.fromString(src, undefined, self);
|
||||
@ -53,7 +53,7 @@ function testValidSRCsRegularHost() {
|
||||
]
|
||||
|
||||
var obj;
|
||||
var expected = "http://test1.example.com:80";
|
||||
var expected = "http://test1.example.com";
|
||||
for (let i in csps) {
|
||||
var src = csps[i];
|
||||
obj = CSPSourceList.fromString(src, undefined, self);
|
||||
@ -77,7 +77,7 @@ function testValidSRCsWildCardHost() {
|
||||
]
|
||||
|
||||
var obj;
|
||||
var expected = "http://*.example.com:80";
|
||||
var expected = "http://*.example.com";
|
||||
for (let i in csps) {
|
||||
var src = csps[i];
|
||||
obj = CSPSourceList.fromString(src, undefined, self);
|
||||
@ -99,7 +99,7 @@ function testValidSRCsRegularPort() {
|
||||
]
|
||||
|
||||
var obj;
|
||||
var expected = "http://test1.example.com:80";
|
||||
var expected = "http://test1.example.com";
|
||||
for (let i in csps) {
|
||||
var src = csps[i];
|
||||
obj = CSPSourceList.fromString(src, undefined, self);
|
||||
|
@ -63,8 +63,9 @@ function makeTest(id, expectedJSON, useReportOnlyPolicy, callback) {
|
||||
|
||||
// set up a new CSP instance for each test.
|
||||
var csp = Cc["@mozilla.org/contentsecuritypolicy;1"]
|
||||
//var csp = Cc["@mozilla.org/cspcontext;1"]
|
||||
.createInstance(Ci.nsIContentSecurityPolicy);
|
||||
var policy = "allow 'none'; " +
|
||||
var policy = "default-src 'none'; " +
|
||||
"report-uri " + REPORT_SERVER_URI +
|
||||
":" + REPORT_SERVER_PORT +
|
||||
"/test" + id;
|
||||
@ -80,7 +81,7 @@ function makeTest(id, expectedJSON, useReportOnlyPolicy, callback) {
|
||||
|
||||
// Load up the policy
|
||||
// set as report-only if that's the case
|
||||
csp.appendPolicy(policy, selfuri, useReportOnlyPolicy, false);
|
||||
csp.appendPolicy(policy, selfuri, useReportOnlyPolicy, true);
|
||||
|
||||
// prime the report server
|
||||
var handler = makeReportHandler("/test" + id, "Test " + id, expectedJSON);
|
||||
|
@ -35,7 +35,7 @@ function do_check_in_array(arr, val, stack) {
|
||||
var text = val + " in [" + arr.join(",") + "]";
|
||||
|
||||
for(var i in arr) {
|
||||
dump(".......... " + i + "> " + arr[i] + "\n");
|
||||
//dump(".......... " + i + "> " + arr[i] + "\n");
|
||||
if(arr[i] == val) {
|
||||
//succeed
|
||||
++_passedChecks;
|
||||
@ -261,7 +261,7 @@ test(
|
||||
test(
|
||||
function test_CSPSourceList_fromString_twohost() {
|
||||
var str = "foo.bar:21 https://ras.bar";
|
||||
var parsed = "http://foo.bar:21 https://ras.bar:443";
|
||||
var parsed = "http://foo.bar:21 https://ras.bar";
|
||||
var sd = CSPSourceList.fromString(str, undefined, URI("http://self.com:80"));
|
||||
//"two-host list should parse"
|
||||
do_check_neq(null,sd);
|
||||
@ -321,43 +321,26 @@ test(
|
||||
do_check_false(wildcardHostSourceList.permits("http://barbaz.com"));
|
||||
});
|
||||
|
||||
///////////////////// Test the Whole CSP rep object //////////////////////
|
||||
|
||||
//////////////// TEST CSP REP SPEC COMPLIANT PARSER ////////////
|
||||
test(
|
||||
function test_CSPRep_fromString() {
|
||||
|
||||
// check default init
|
||||
//ASSERT(!(new CSPRep())._isInitialized, "Uninitialized rep thinks it is.")
|
||||
|
||||
var cspr;
|
||||
var cspr_allowval;
|
||||
var SD = CSPRep.SRC_DIRECTIVES_OLD;
|
||||
var SD = CSPRep.SRC_DIRECTIVES;
|
||||
var DEFAULTS = [SD.STYLE_SRC, SD.MEDIA_SRC, SD.IMG_SRC, SD.SCRIPT_SRC, SD.FONT_SRC,
|
||||
SD.OBJECT_SRC, SD.FRAME_SRC, SD.CONNECT_SRC];
|
||||
|
||||
// check default policy "allow *"
|
||||
cspr = CSPRep.fromString("allow *", URI("http://self.com:80"));
|
||||
// "DEFAULT_SRC directive is missing when specified in fromString"
|
||||
do_check_has_key(cspr._directives, SD.DEFAULT_SRC);
|
||||
|
||||
});
|
||||
|
||||
|
||||
test(
|
||||
function test_CSPRep_defaultSrc() {
|
||||
var cspr, cspr_default_val, cspr_allow;
|
||||
var SD = CSPRep.SRC_DIRECTIVES_OLD;
|
||||
|
||||
// apply policy of "default-src *" (e.g. "allow *")
|
||||
// check default policy "default-src *"
|
||||
cspr = CSPRep.fromString("default-src *", URI("http://self.com:80"));
|
||||
// "DEFAULT_SRC directive is missing when specified in fromString"
|
||||
do_check_has_key(cspr._directives, SD.DEFAULT_SRC);
|
||||
|
||||
// check that |allow *| and |default-src *| are parsed equivalently and
|
||||
// result in the same set of explicit policy directives
|
||||
cspr = CSPRep.fromString("default-src *", URI("http://self.com:80"));
|
||||
cspr_allow = CSPRep.fromString("allow *", URI("http://self.com:80"));
|
||||
|
||||
do_check_equivalent(cspr._directives['default-src'],
|
||||
cspr_allow._directives['default-src']);
|
||||
for(var x in DEFAULTS) {
|
||||
// each of these should be equivalent to DEFAULT_SRC
|
||||
//DEFAULTS[x] + " does not use default rule."
|
||||
do_check_true(cspr.permits("http://bar.com", DEFAULTS[x]));
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@ -365,11 +348,12 @@ test(
|
||||
function test_CSPRep_fromString_oneDir() {
|
||||
|
||||
var cspr;
|
||||
var SD = CSPRep.SRC_DIRECTIVES_OLD;
|
||||
var DEFAULTS = [SD.STYLE_SRC, SD.MEDIA_SRC, SD.IMG_SRC, SD.FRAME_SRC];
|
||||
var SD = CSPRep.SRC_DIRECTIVES;
|
||||
var DEFAULTS = [SD.STYLE_SRC, SD.MEDIA_SRC, SD.IMG_SRC,
|
||||
SD.FRAME_SRC, SD.CONNECT_SRC];
|
||||
|
||||
// check one-directive policies
|
||||
cspr = CSPRep.fromString("allow bar.com; script-src https://foo.com",
|
||||
cspr = CSPRep.fromString("default-src bar.com; script-src https://foo.com",
|
||||
URI("http://self.com"));
|
||||
|
||||
for(var x in DEFAULTS) {
|
||||
@ -389,15 +373,18 @@ test(
|
||||
});
|
||||
|
||||
test(
|
||||
function test_CSPRep_fromString_twodir() {
|
||||
function test_CSPRep_fromString_twoDir() {
|
||||
var cspr;
|
||||
var SD = CSPRep.SRC_DIRECTIVES_OLD;
|
||||
var DEFAULTS = [SD.STYLE_SRC, SD.MEDIA_SRC, SD.FRAME_SRC];
|
||||
|
||||
var SD = CSPRep.SRC_DIRECTIVES;
|
||||
|
||||
var DEFAULTS = [SD.STYLE_SRC, SD.MEDIA_SRC, SD.FRAME_SRC,
|
||||
SD.CONNECT_SRC];
|
||||
|
||||
// check two-directive policies
|
||||
var polstr = "allow allow.com; "
|
||||
+ "script-src https://foo.com; "
|
||||
+ "img-src bar.com:*";
|
||||
var polstr = "default-src allow.com; " +
|
||||
"script-src https://foo.com; " +
|
||||
"img-src bar.com:*";
|
||||
cspr = CSPRep.fromString(polstr, URI("http://self.com"));
|
||||
|
||||
for(var x in DEFAULTS) {
|
||||
@ -425,123 +412,12 @@ test(
|
||||
|
||||
test(function test_CSPRep_fromString_withself() {
|
||||
var cspr;
|
||||
var SD = CSPRep.SRC_DIRECTIVES_OLD;
|
||||
var self = "https://self.com:34";
|
||||
var SD = CSPRep.SRC_DIRECTIVES;
|
||||
|
||||
// check one-directive policies
|
||||
cspr = CSPRep.fromString("allow 'self'; script-src 'self' https://*:*",
|
||||
URI(self));
|
||||
//"img-src does not enforce default rule, 'self'.
|
||||
do_check_false(cspr.permits("https://foo.com:400", SD.IMG_SRC));
|
||||
//"img-src does not allow self
|
||||
do_check_true(cspr.permits(self, SD.IMG_SRC));
|
||||
//"script-src is too relaxed
|
||||
do_check_false(cspr.permits("http://evil.com", SD.SCRIPT_SRC));
|
||||
//"script-src should allow self
|
||||
do_check_true(cspr.permits(self, SD.SCRIPT_SRC));
|
||||
//"script-src is too strict on host/port
|
||||
do_check_true(cspr.permits("https://evil.com:100", SD.SCRIPT_SRC));
|
||||
});
|
||||
|
||||
|
||||
//////////////// TEST CSP REP SPEC COMPLIANT PARSER ////////////
|
||||
test(
|
||||
function test_CSPRep_fromStringSpecCompliant() {
|
||||
|
||||
var cspr;
|
||||
var cspr_allowval;
|
||||
var SD = CSPRep.SRC_DIRECTIVES_NEW;
|
||||
var DEFAULTS = [SD.STYLE_SRC, SD.MEDIA_SRC, SD.IMG_SRC, SD.SCRIPT_SRC, SD.FONT_SRC,
|
||||
SD.OBJECT_SRC, SD.FRAME_SRC, SD.CONNECT_SRC];
|
||||
|
||||
// check default policy "default-src *"
|
||||
cspr = CSPRep.fromStringSpecCompliant("default-src *", URI("http://self.com:80"));
|
||||
// "DEFAULT_SRC directive is missing when specified in
|
||||
// fromStringSpecCompliant"
|
||||
do_check_has_key(cspr._directives, SD.DEFAULT_SRC);
|
||||
|
||||
for(var x in DEFAULTS) {
|
||||
// each of these should be equivalent to DEFAULT_SRC
|
||||
//DEFAULTS[x] + " does not use default rule."
|
||||
do_check_true(cspr.permits("http://bar.com", DEFAULTS[x]));
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
test(
|
||||
function test_CSPRep_fromStringSpecCompliant_oneDir() {
|
||||
|
||||
var cspr;
|
||||
var SD = CSPRep.SRC_DIRECTIVES_NEW;
|
||||
var DEFAULTS = [SD.STYLE_SRC, SD.MEDIA_SRC, SD.IMG_SRC,
|
||||
SD.FRAME_SRC, SD.CONNECT_SRC];
|
||||
|
||||
// check one-directive policies
|
||||
cspr = CSPRep.fromStringSpecCompliant("default-src bar.com; script-src https://foo.com",
|
||||
URI("http://self.com"));
|
||||
|
||||
for(var x in DEFAULTS) {
|
||||
//DEFAULTS[x] + " does not use default rule."
|
||||
do_check_false(cspr.permits("http://bar.com:22", DEFAULTS[x]));
|
||||
//DEFAULTS[x] + " does not use default rule."
|
||||
do_check_true(cspr.permits("http://bar.com:80", DEFAULTS[x]));
|
||||
//DEFAULTS[x] + " does not use default rule."
|
||||
do_check_false(cspr.permits("https://foo.com:400", DEFAULTS[x]));
|
||||
//DEFAULTS[x] + " does not use default rule."
|
||||
do_check_false(cspr.permits("https://foo.com", DEFAULTS[x]));
|
||||
}
|
||||
//"script-src false positive in policy.
|
||||
do_check_false(cspr.permits("http://bar.com:22", SD.SCRIPT_SRC));
|
||||
//"script-src false negative in policy.
|
||||
do_check_true(cspr.permits("https://foo.com:443", SD.SCRIPT_SRC));
|
||||
});
|
||||
|
||||
test(
|
||||
function test_CSPRep_fromStringSpecCompliant_twodir() {
|
||||
var cspr;
|
||||
|
||||
var SD = CSPRep.SRC_DIRECTIVES_NEW;
|
||||
|
||||
var DEFAULTS = [SD.STYLE_SRC, SD.MEDIA_SRC, SD.FRAME_SRC,
|
||||
SD.CONNECT_SRC];
|
||||
|
||||
// check two-directive policies
|
||||
var polstr = "default-src allow.com; " +
|
||||
"script-src https://foo.com; " +
|
||||
"img-src bar.com:*";
|
||||
cspr = CSPRep.fromStringSpecCompliant(polstr, URI("http://self.com"));
|
||||
|
||||
for(var x in DEFAULTS) {
|
||||
do_check_true(cspr.permits("http://allow.com", DEFAULTS[x]));
|
||||
//DEFAULTS[x] + " does not use default rule.
|
||||
do_check_false(cspr.permits("https://foo.com:400", DEFAULTS[x]));
|
||||
//DEFAULTS[x] + " does not use default rule.
|
||||
do_check_false(cspr.permits("http://bar.com:400", DEFAULTS[x]));
|
||||
//DEFAULTS[x] + " does not use default rule.
|
||||
}
|
||||
//"img-src does not use default rule.
|
||||
do_check_false(cspr.permits("http://allow.com:22", SD.IMG_SRC));
|
||||
//"img-src does not use default rule.
|
||||
do_check_false(cspr.permits("https://foo.com:400", SD.IMG_SRC));
|
||||
//"img-src does not use default rule.
|
||||
do_check_true(cspr.permits("http://bar.com:88", SD.IMG_SRC));
|
||||
|
||||
//"script-src does not use default rule.
|
||||
do_check_false(cspr.permits("http://allow.com:22", SD.SCRIPT_SRC));
|
||||
//"script-src does not use default rule.
|
||||
do_check_true(cspr.permits("https://foo.com:443", SD.SCRIPT_SRC));
|
||||
//"script-src does not use default rule.
|
||||
do_check_false(cspr.permits("http://bar.com:400", SD.SCRIPT_SRC));
|
||||
});
|
||||
|
||||
test(function test_CSPRep_fromStringSpecCompliant_withself() {
|
||||
var cspr;
|
||||
var self = "https://self.com:34";
|
||||
var SD = CSPRep.SRC_DIRECTIVES_NEW;
|
||||
|
||||
// check one-directive policies
|
||||
cspr = CSPRep.fromStringSpecCompliant("default-src 'self'; script-src 'self' https://*:*",
|
||||
URI(self));
|
||||
cspr = CSPRep.fromString("default-src 'self'; script-src 'self' https://*:*",
|
||||
URI(self));
|
||||
//"img-src does not enforce default rule, 'self'.
|
||||
do_check_false(cspr.permits("https://foo.com:400", SD.IMG_SRC));
|
||||
//"img-src does not allow self
|
||||
@ -559,34 +435,10 @@ test(function test_CSPRep_fromStringSpecCompliant_withself() {
|
||||
// (see bug 555068)
|
||||
test(function test_FrameAncestor_defaults() {
|
||||
var cspr;
|
||||
var SD = CSPRep.SRC_DIRECTIVES_OLD;
|
||||
var self = "http://self.com:34";
|
||||
var SD = CSPRep.SRC_DIRECTIVES;
|
||||
|
||||
cspr = CSPRep.fromString("allow 'none'", URI(self));
|
||||
|
||||
//"frame-ancestors should default to * not 'allow' value"
|
||||
do_check_true(cspr.permits("https://foo.com:400", SD.FRAME_ANCESTORS));
|
||||
do_check_true(cspr.permits("http://self.com:34", SD.FRAME_ANCESTORS));
|
||||
do_check_true(cspr.permits("https://self.com:34", SD.FRAME_ANCESTORS));
|
||||
do_check_true(cspr.permits("http://self.com", SD.FRAME_ANCESTORS));
|
||||
do_check_true(cspr.permits("http://subd.self.com:34", SD.FRAME_ANCESTORS));
|
||||
|
||||
cspr = CSPRep.fromString("allow 'none'; frame-ancestors 'self'", URI(self));
|
||||
|
||||
//"frame-ancestors should only allow self"
|
||||
do_check_true(cspr.permits("http://self.com:34", SD.FRAME_ANCESTORS));
|
||||
do_check_false(cspr.permits("https://foo.com:400", SD.FRAME_ANCESTORS));
|
||||
do_check_false(cspr.permits("https://self.com:34", SD.FRAME_ANCESTORS));
|
||||
do_check_false(cspr.permits("http://self.com", SD.FRAME_ANCESTORS));
|
||||
do_check_false(cspr.permits("http://subd.self.com:34", SD.FRAME_ANCESTORS));
|
||||
});
|
||||
|
||||
test(function test_FrameAncestor_defaults_specCompliant() {
|
||||
var cspr;
|
||||
var self = "http://self.com:34";
|
||||
var SD = CSPRep.SRC_DIRECTIVES_NEW;
|
||||
|
||||
cspr = CSPRep.fromStringSpecCompliant("default-src 'none'", URI(self));
|
||||
cspr = CSPRep.fromString("default-src 'none'", URI(self));
|
||||
|
||||
//"frame-ancestors should default to * not 'default-src' value"
|
||||
do_check_true(cspr.permits("https://foo.com:400", SD.FRAME_ANCESTORS));
|
||||
@ -595,7 +447,7 @@ test(function test_FrameAncestor_defaults_specCompliant() {
|
||||
do_check_true(cspr.permits("http://self.com", SD.FRAME_ANCESTORS));
|
||||
do_check_true(cspr.permits("http://subd.self.com:34", SD.FRAME_ANCESTORS));
|
||||
|
||||
cspr = CSPRep.fromStringSpecCompliant("default-src 'none'; frame-ancestors 'self'", URI(self));
|
||||
cspr = CSPRep.fromString("default-src 'none'; frame-ancestors 'self'", URI(self));
|
||||
|
||||
//"frame-ancestors should only allow self"
|
||||
do_check_true(cspr.permits("http://self.com:34", SD.FRAME_ANCESTORS));
|
||||
@ -608,10 +460,10 @@ test(function test_FrameAncestor_defaults_specCompliant() {
|
||||
|
||||
test(function test_FrameAncestor_TLD_defaultPorts() {
|
||||
var cspr;
|
||||
var SD = CSPRep.SRC_DIRECTIVES_OLD;
|
||||
var SD = CSPRep.SRC_DIRECTIVES;
|
||||
var self = "http://self"; //TLD only, no .com or anything.
|
||||
|
||||
cspr = CSPRep.fromString("allow 'self'; frame-ancestors 'self' http://foo:80 bar:80 http://three", URI(self));
|
||||
cspr = CSPRep.fromString("default-src 'self'; frame-ancestors 'self' http://foo:80 bar:80 http://three", URI(self));
|
||||
|
||||
//"frame-ancestors should default to * not 'allow' value"
|
||||
do_check_true(cspr.permits("http://self", SD.FRAME_ANCESTORS));
|
||||
@ -630,7 +482,7 @@ test(function test_FrameAncestor_TLD_defaultPorts() {
|
||||
|
||||
test(function test_FrameAncestor_ignores_userpass_bug779918() {
|
||||
var cspr;
|
||||
var SD = CSPRep.SRC_DIRECTIVES_OLD;
|
||||
var SD = CSPRep.SRC_DIRECTIVES;
|
||||
var self = "http://self.com/bar";
|
||||
var testPolicy = "default-src 'self'; frame-ancestors 'self'";
|
||||
|
||||
@ -678,7 +530,7 @@ test(function test_FrameAncestor_ignores_userpass_bug779918() {
|
||||
|
||||
test(function test_CSP_ReportURI_parsing() {
|
||||
var cspr;
|
||||
var SD = CSPRep.SRC_DIRECTIVES_NEW;
|
||||
var SD = CSPRep.SRC_DIRECTIVES;
|
||||
var self = "http://self.com:34";
|
||||
var parsedURIs = [];
|
||||
|
||||
@ -692,48 +544,48 @@ test(function test_CSP_ReportURI_parsing() {
|
||||
var uri_other_scheme_absolute = "https://self.com/report.py";
|
||||
var uri_other_scheme_and_host_absolute = "https://foo.com/report.py";
|
||||
|
||||
cspr = CSPRep.fromStringSpecCompliant("default-src *; report-uri " + uri_valid_absolute, URI(self));
|
||||
cspr = CSPRep.fromString("default-src *; report-uri " + uri_valid_absolute, URI(self));
|
||||
parsedURIs = cspr.getReportURIs().split(/\s+/);
|
||||
do_check_in_array(parsedURIs, uri_valid_absolute);
|
||||
do_check_eq(parsedURIs.length, 1);
|
||||
|
||||
cspr = CSPRep.fromStringSpecCompliant("default-src *; report-uri " + uri_other_host_absolute, URI(self));
|
||||
cspr = CSPRep.fromString("default-src *; report-uri " + uri_other_host_absolute, URI(self));
|
||||
parsedURIs = cspr.getReportURIs().split(/\s+/);
|
||||
do_check_in_array(parsedURIs, uri_other_host_absolute);
|
||||
do_check_eq(parsedURIs.length, 1); // the empty string is in there.
|
||||
|
||||
cspr = CSPRep.fromStringSpecCompliant("default-src *; report-uri " + uri_invalid_relative, URI(self));
|
||||
cspr = CSPRep.fromString("default-src *; report-uri " + uri_invalid_relative, URI(self));
|
||||
parsedURIs = cspr.getReportURIs().split(/\s+/);
|
||||
do_check_in_array(parsedURIs, "");
|
||||
do_check_eq(parsedURIs.length, 1);
|
||||
|
||||
cspr = CSPRep.fromStringSpecCompliant("default-src *; report-uri " + uri_valid_relative, URI(self));
|
||||
cspr = CSPRep.fromString("default-src *; report-uri " + uri_valid_relative, URI(self));
|
||||
parsedURIs = cspr.getReportURIs().split(/\s+/);
|
||||
do_check_in_array(parsedURIs, uri_valid_relative_expanded);
|
||||
do_check_eq(parsedURIs.length, 1);
|
||||
|
||||
cspr = CSPRep.fromStringSpecCompliant("default-src *; report-uri " + uri_valid_relative2, URI(self));
|
||||
cspr = CSPRep.fromString("default-src *; report-uri " + uri_valid_relative2, URI(self));
|
||||
parsedURIs = cspr.getReportURIs().split(/\s+/);
|
||||
dump(parsedURIs.length);
|
||||
do_check_in_array(parsedURIs, uri_valid_relative2_expanded);
|
||||
do_check_eq(parsedURIs.length, 1);
|
||||
|
||||
// make sure cross-scheme reporting works
|
||||
cspr = CSPRep.fromStringSpecCompliant("default-src *; report-uri " + uri_other_scheme_absolute, URI(self));
|
||||
cspr = CSPRep.fromString("default-src *; report-uri " + uri_other_scheme_absolute, URI(self));
|
||||
parsedURIs = cspr.getReportURIs().split(/\s+/);
|
||||
dump(parsedURIs.length);
|
||||
do_check_in_array(parsedURIs, uri_other_scheme_absolute);
|
||||
do_check_eq(parsedURIs.length, 1);
|
||||
|
||||
// make sure cross-scheme, cross-host reporting works
|
||||
cspr = CSPRep.fromStringSpecCompliant("default-src *; report-uri " + uri_other_scheme_and_host_absolute, URI(self));
|
||||
cspr = CSPRep.fromString("default-src *; report-uri " + uri_other_scheme_and_host_absolute, URI(self));
|
||||
parsedURIs = cspr.getReportURIs().split(/\s+/);
|
||||
dump(parsedURIs.length);
|
||||
do_check_in_array(parsedURIs, uri_other_scheme_and_host_absolute);
|
||||
do_check_eq(parsedURIs.length, 1);
|
||||
|
||||
// combination!
|
||||
cspr = CSPRep.fromStringSpecCompliant("default-src *; report-uri " +
|
||||
cspr = CSPRep.fromString("default-src *; report-uri " +
|
||||
uri_valid_relative2 + " " +
|
||||
uri_valid_absolute, URI(self));
|
||||
parsedURIs = cspr.getReportURIs().split(/\s+/);
|
||||
@ -741,7 +593,7 @@ test(function test_CSP_ReportURI_parsing() {
|
||||
do_check_in_array(parsedURIs, uri_valid_absolute);
|
||||
do_check_eq(parsedURIs.length, 2);
|
||||
|
||||
cspr = CSPRep.fromStringSpecCompliant("default-src *; report-uri " +
|
||||
cspr = CSPRep.fromString("default-src *; report-uri " +
|
||||
uri_valid_relative2 + " " +
|
||||
uri_other_host_absolute + " " +
|
||||
uri_valid_absolute, URI(self));
|
||||
@ -755,32 +607,22 @@ test(function test_CSP_ReportURI_parsing() {
|
||||
test(
|
||||
function test_bug634778_duplicateDirective_Detection() {
|
||||
var cspr;
|
||||
var SD = CSPRep.SRC_DIRECTIVES_OLD;
|
||||
var SD = CSPRep.SRC_DIRECTIVES;
|
||||
var self = "http://self.com:34";
|
||||
var firstDomain = "http://first.com";
|
||||
var secondDomain = "http://second.com";
|
||||
var thirdDomain = "http://third.com";
|
||||
|
||||
// check for duplicate "default-src" directives
|
||||
// Spec says first directive persists (subsequent re-statement is
|
||||
// ignored)
|
||||
cspr = CSPRep.fromString("default-src " + self + "; default-src " +
|
||||
firstDomain, URI(self));
|
||||
do_check_true(cspr.permits(self, SD.DEFAULT_SRC));
|
||||
do_check_false(cspr.permits(firstDomain, SD.DEFAULT_SRC));
|
||||
|
||||
// check for duplicate "allow" directives
|
||||
cspr = CSPRep.fromString("allow " + self + "; allow " + firstDomain,
|
||||
URI(self));
|
||||
do_check_true(cspr.permits(self, SD.DEFAULT_SRC));
|
||||
do_check_false(cspr.permits(firstDomain, SD.DEFAULT_SRC));
|
||||
|
||||
// check for duplicate "allow" + "default-src" directives
|
||||
cspr = CSPRep.fromString("allow " + self + "; default-src " + firstDomain,
|
||||
URI(self));
|
||||
do_check_true(cspr.permits(self, SD.DEFAULT_SRC));
|
||||
do_check_false(cspr.permits(firstDomain, SD.DEFAULT_SRC));
|
||||
|
||||
// check for duplicate report-uri directives
|
||||
cspr = CSPRep.fromString("allow *; report-uri " + self + "/report.py; report-uri "
|
||||
cspr = CSPRep.fromString("default-src *; report-uri " + self + "/report.py; report-uri "
|
||||
+ firstDomain + "/report.py", URI(self));
|
||||
parsedURIs = cspr.getReportURIs().split(/\s+/);
|
||||
do_check_in_array(parsedURIs, self + "/report.py");
|
||||
@ -896,9 +738,7 @@ test(
|
||||
|
||||
test(
|
||||
function test_bug764937_defaultSrcMissing() {
|
||||
var cspObjSpecCompliant = Cc["@mozilla.org/contentsecuritypolicy;1"]
|
||||
.createInstance(Ci.nsIContentSecurityPolicy);
|
||||
var cspObjOld = Cc["@mozilla.org/contentsecuritypolicy;1"]
|
||||
var cspObj = Cc["@mozilla.org/contentsecuritypolicy;1"]
|
||||
.createInstance(Ci.nsIContentSecurityPolicy);
|
||||
var selfURI = URI("http://self.com/");
|
||||
|
||||
@ -908,39 +748,21 @@ test(
|
||||
};
|
||||
|
||||
const policy = "script-src 'self'";
|
||||
cspObjSpecCompliant.appendPolicy(policy, selfURI, false, true);
|
||||
cspObj.appendPolicy(policy, selfURI, false, true);
|
||||
|
||||
// Spec-Compliant policy default-src defaults to *.
|
||||
// This means all images are allowed, and only 'self'
|
||||
// script is allowed.
|
||||
do_check_true(testPermits(cspObjSpecCompliant,
|
||||
do_check_true(testPermits(cspObj,
|
||||
URI("http://bar.com/foo.png"),
|
||||
Ci.nsIContentPolicy.TYPE_IMAGE));
|
||||
do_check_true(testPermits(cspObjSpecCompliant,
|
||||
do_check_true(testPermits(cspObj,
|
||||
URI("http://self.com/foo.png"),
|
||||
Ci.nsIContentPolicy.TYPE_IMAGE));
|
||||
do_check_true(testPermits(cspObjSpecCompliant,
|
||||
do_check_true(testPermits(cspObj,
|
||||
URI("http://self.com/foo.js"),
|
||||
Ci.nsIContentPolicy.TYPE_SCRIPT));
|
||||
do_check_false(testPermits(cspObjSpecCompliant,
|
||||
URI("http://bar.com/foo.js"),
|
||||
Ci.nsIContentPolicy.TYPE_SCRIPT));
|
||||
|
||||
cspObjOld.appendPolicy(policy, selfURI, false, false);
|
||||
|
||||
// non-Spec-Compliant policy default-src defaults to 'none'
|
||||
// This means all images are blocked, and so are all scripts (because the
|
||||
// policy is ignored and fails closed).
|
||||
do_check_false(testPermits(cspObjOld,
|
||||
URI("http://bar.com/foo.png"),
|
||||
Ci.nsIContentPolicy.TYPE_IMAGE));
|
||||
do_check_false(testPermits(cspObjOld,
|
||||
URI("http://self.com/foo.png"),
|
||||
Ci.nsIContentPolicy.TYPE_IMAGE));
|
||||
do_check_false(testPermits(cspObjOld,
|
||||
URI("http://self.com/foo.js"),
|
||||
Ci.nsIContentPolicy.TYPE_SCRIPT));
|
||||
do_check_false(testPermits(cspObjOld,
|
||||
do_check_false(testPermits(cspObj,
|
||||
URI("http://bar.com/foo.js"),
|
||||
Ci.nsIContentPolicy.TYPE_SCRIPT));
|
||||
|
||||
@ -955,10 +777,10 @@ test(function test_equals_does_case_insensitive_comparison() {
|
||||
// CSPSource equals ignores case
|
||||
var upperCaseHost = "http://FOO.COM";
|
||||
var lowerCaseHost = "http://foo.com";
|
||||
src1 = CSPSource.fromString(lowerCaseHost);
|
||||
src2 = CSPSource.fromString(lowerCaseHost);
|
||||
var src1 = CSPSource.fromString(lowerCaseHost);
|
||||
var src2 = CSPSource.fromString(lowerCaseHost);
|
||||
do_check_true(src1.equals(src2))
|
||||
src3 = CSPSource.fromString(upperCaseHost);
|
||||
var src3 = CSPSource.fromString(upperCaseHost);
|
||||
do_check_true(src1.equals(src3))
|
||||
|
||||
// CSPHost equals ignores case
|
||||
@ -983,7 +805,7 @@ test(function test_equals_does_case_insensitive_comparison() {
|
||||
|
||||
test(function test_csp_permits_case_insensitive() {
|
||||
var cspr;
|
||||
var SD = CSPRep.SRC_DIRECTIVES_NEW;
|
||||
var SD = CSPRep.SRC_DIRECTIVES;
|
||||
|
||||
// checks directives can be case-insensitive
|
||||
var selfHost = "http://self.com";
|
||||
@ -1042,12 +864,15 @@ function run_test() {
|
||||
httpServer.registerPathHandler("/policy", policyresponder);
|
||||
|
||||
for(let i in tests) {
|
||||
tests[i]();
|
||||
add_task(tests[i]);
|
||||
}
|
||||
|
||||
//teardown
|
||||
httpServer.stop(function() { });
|
||||
do_test_finished();
|
||||
do_register_cleanup(function () {
|
||||
//teardown
|
||||
httpServer.stop(function() { });
|
||||
});
|
||||
|
||||
run_next_test();
|
||||
}
|
||||
|
||||
|
||||
|
@ -21,7 +21,6 @@ support-files =
|
||||
4_result_6.xml
|
||||
|
||||
[test_bug553888.js]
|
||||
[test_bug558431.js]
|
||||
[test_bug737966.js]
|
||||
[test_csputils.js]
|
||||
[test_cspreports.js]
|
||||
|
@ -1,4 +0,0 @@
|
||||
[DEFAULT]
|
||||
|
||||
[test_csp_bug768029.html]
|
||||
[test_csp_bug773891.html]
|
@ -1,20 +0,0 @@
|
||||
/*
|
||||
* Moved this CSS from an inline stylesheet to an external file when we added
|
||||
* inline-style blocking in bug 763879.
|
||||
* This test may hang if the load for this .css file is blocked due to a
|
||||
* malfunction of CSP, but should pass if the style_good test passes.
|
||||
*/
|
||||
|
||||
/* CSS font embedding tests */
|
||||
@font-face {
|
||||
font-family: "arbitrary_good";
|
||||
src: url('file_CSP.sjs?testid=font_good&type=application/octet-stream');
|
||||
}
|
||||
@font-face {
|
||||
font-family: "arbitrary_bad";
|
||||
src: url('http://example.org/tests/content/base/test/xcsp/file_CSP.sjs?testid=font_bad&type=application/octet-stream');
|
||||
}
|
||||
|
||||
.div_arbitrary_good { font-family: "arbitrary_good"; }
|
||||
.div_arbitrary_bad { font-family: "arbitrary_bad"; }
|
||||
|
@ -1,26 +0,0 @@
|
||||
// SJS file for CSP mochitests
|
||||
|
||||
function handleRequest(request, response)
|
||||
{
|
||||
var query = {};
|
||||
request.queryString.split('&').forEach(function (val) {
|
||||
var [name, value] = val.split('=');
|
||||
query[name] = unescape(value);
|
||||
});
|
||||
|
||||
var isPreflight = request.method == "OPTIONS";
|
||||
|
||||
|
||||
//avoid confusing cache behaviors
|
||||
response.setHeader("Cache-Control", "no-cache", false);
|
||||
|
||||
if ("type" in query) {
|
||||
response.setHeader("Content-Type", unescape(query['type']), false);
|
||||
} else {
|
||||
response.setHeader("Content-Type", "text/html", false);
|
||||
}
|
||||
|
||||
if ("content" in query) {
|
||||
response.write(unescape(query['content']));
|
||||
}
|
||||
}
|
@ -1,16 +0,0 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<body>
|
||||
<ol>
|
||||
<li id="inline-script">Inline script (green if allowed, black if blocked)</li>
|
||||
</ol>
|
||||
|
||||
<script>
|
||||
// Use inline script to set a style attribute
|
||||
document.getElementById("inline-script").style.color = "rgb(0, 128, 0)";
|
||||
</script>
|
||||
|
||||
<img src="file_CSP.sjs?testid=img_bad&type=img/png"></img>
|
||||
|
||||
</body>
|
||||
</html>
|
@ -1 +0,0 @@
|
||||
x-content-security-policy-report-only: options eval-script; script-src 'self' ; report-uri /csp_report
|
@ -1,12 +0,0 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>CSP eval script tests</title>
|
||||
<script type="application/javascript"
|
||||
src="file_CSP_evalscript_main.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
Foo.
|
||||
|
||||
</body>
|
||||
</html>
|
@ -1,2 +0,0 @@
|
||||
Cache-Control: no-cache
|
||||
X-Content-Security-Policy: default-src 'self'
|
@ -1,126 +0,0 @@
|
||||
// some javascript for the CSP eval() tests
|
||||
|
||||
function logResult(str, passed) {
|
||||
var elt = document.createElement('div');
|
||||
var color = passed ? "#cfc;" : "#fcc";
|
||||
elt.setAttribute('style', 'background-color:' + color + '; width:100%; border:1px solid black; padding:3px; margin:4px;');
|
||||
elt.innerHTML = str;
|
||||
document.body.appendChild(elt);
|
||||
}
|
||||
|
||||
window._testResults = {};
|
||||
|
||||
// callback for when stuff is allowed by CSP
|
||||
var onevalexecuted = (function(window) {
|
||||
return function(shouldrun, what, data) {
|
||||
window._testResults[what] = "ran";
|
||||
window.parent.scriptRan(shouldrun, what, data);
|
||||
logResult((shouldrun ? "PASS: " : "FAIL: ") + what + " : " + data, shouldrun);
|
||||
};})(window);
|
||||
|
||||
// callback for when stuff is blocked
|
||||
var onevalblocked = (function(window) {
|
||||
return function(shouldrun, what, data) {
|
||||
window._testResults[what] = "blocked";
|
||||
window.parent.scriptBlocked(shouldrun, what, data);
|
||||
logResult((shouldrun ? "FAIL: " : "PASS: ") + what + " : " + data, !shouldrun);
|
||||
};})(window);
|
||||
|
||||
|
||||
// Defer until document is loaded so that we can write the pretty result boxes
|
||||
// out.
|
||||
addEventListener('load', function() {
|
||||
// setTimeout(String) test -- mutate something in the window._testResults
|
||||
// obj, then check it.
|
||||
{
|
||||
var str_setTimeoutWithStringRan = 'onevalexecuted(false, "setTimeout(String)", "setTimeout with a string was enabled.");';
|
||||
function fcn_setTimeoutWithStringCheck() {
|
||||
if (this._testResults["setTimeout(String)"] !== "ran") {
|
||||
onevalblocked(false, "setTimeout(String)",
|
||||
"setTimeout with a string was blocked");
|
||||
}
|
||||
}
|
||||
setTimeout(fcn_setTimeoutWithStringCheck.bind(window), 10);
|
||||
setTimeout(str_setTimeoutWithStringRan, 10);
|
||||
}
|
||||
|
||||
// setTimeout(function) test -- mutate something in the window._testResults
|
||||
// obj, then check it.
|
||||
{
|
||||
function fcn_setTimeoutWithFunctionRan() {
|
||||
onevalexecuted(true, "setTimeout(function)",
|
||||
"setTimeout with a function was enabled.")
|
||||
}
|
||||
function fcn_setTimeoutWithFunctionCheck() {
|
||||
if (this._testResults["setTimeout(function)"] !== "ran") {
|
||||
onevalblocked(true, "setTimeout(function)",
|
||||
"setTimeout with a function was blocked");
|
||||
}
|
||||
}
|
||||
setTimeout(fcn_setTimeoutWithFunctionRan.bind(window), 10);
|
||||
setTimeout(fcn_setTimeoutWithFunctionCheck.bind(window), 10);
|
||||
}
|
||||
|
||||
// eval() test -- should throw exception as per spec
|
||||
try {
|
||||
eval('onevalexecuted(false, "eval(String)", "eval() was enabled.");');
|
||||
} catch (e) {
|
||||
onevalblocked(false, "eval(String)",
|
||||
"eval() was blocked");
|
||||
}
|
||||
|
||||
// eval(foo,bar) test -- should throw exception as per spec
|
||||
try {
|
||||
eval('onevalexecuted(false, "eval(String,scope)", "eval() was enabled.");',1);
|
||||
} catch (e) {
|
||||
onevalblocked(false, "eval(String,object)",
|
||||
"eval() with scope was blocked");
|
||||
}
|
||||
|
||||
// [foo,bar].sort(eval) test -- should throw exception as per spec
|
||||
try {
|
||||
['onevalexecuted(false, "[String, obj].sort(eval)", "eval() was enabled.");',1].sort(eval);
|
||||
} catch (e) {
|
||||
onevalblocked(false, "[String, obj].sort(eval)",
|
||||
"eval() with scope via sort was blocked");
|
||||
}
|
||||
|
||||
// [].sort.call([foo,bar], eval) test -- should throw exception as per spec
|
||||
try {
|
||||
[].sort.call(['onevalexecuted(false, "[String, obj].sort(eval)", "eval() was enabled.");',1], eval);
|
||||
} catch (e) {
|
||||
onevalblocked(false, "[].sort.call([String, obj], eval)",
|
||||
"eval() with scope via sort/call was blocked");
|
||||
}
|
||||
|
||||
// new Function() test -- should throw exception as per spec
|
||||
try {
|
||||
var fcn = new Function('onevalexecuted(false, "new Function(String)", "new Function(String) was enabled.");');
|
||||
fcn();
|
||||
} catch (e) {
|
||||
onevalblocked(false, "new Function(String)",
|
||||
"new Function(String) was blocked.");
|
||||
}
|
||||
|
||||
// setTimeout(eval, 0, str)
|
||||
{
|
||||
// error is not catchable here, instead, we're going to side-effect
|
||||
// 'worked'.
|
||||
var worked = false;
|
||||
|
||||
setTimeout(eval, 0, 'worked = true');
|
||||
setTimeout(function(worked) {
|
||||
if (worked) {
|
||||
onevalexecuted(false, "setTimeout(eval, 0, str)",
|
||||
"setTimeout(eval, 0, string) was enabled.");
|
||||
} else {
|
||||
onevalblocked(false, "setTimeout(eval, 0, str)",
|
||||
"setTimeout(eval, 0, str) was blocked.");
|
||||
}
|
||||
}, 0, worked);
|
||||
}
|
||||
|
||||
}, false);
|
||||
|
||||
|
||||
|
@ -1,12 +0,0 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>CSP eval script tests</title>
|
||||
<script type="application/javascript"
|
||||
src="file_CSP_evalscript_main_getCRMFRequest.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
Foo.
|
||||
|
||||
</body>
|
||||
</html>
|
@ -1,2 +0,0 @@
|
||||
Cache-Control: no-cache
|
||||
X-Content-Security-Policy: default-src 'self'
|
@ -1,48 +0,0 @@
|
||||
// some javascript for the CSP eval() tests
|
||||
|
||||
function logResult(str, passed) {
|
||||
var elt = document.createElement('div');
|
||||
var color = passed ? "#cfc;" : "#fcc";
|
||||
elt.setAttribute('style', 'background-color:' + color + '; width:100%; border:1px solid black; padding:3px; margin:4px;');
|
||||
elt.innerHTML = str;
|
||||
document.body.appendChild(elt);
|
||||
}
|
||||
|
||||
window._testResults = {};
|
||||
|
||||
// callback for when stuff is allowed by CSP
|
||||
var onevalexecuted = (function(window) {
|
||||
return function(shouldrun, what, data) {
|
||||
window._testResults[what] = "ran";
|
||||
window.parent.scriptRan(shouldrun, what, data);
|
||||
logResult((shouldrun ? "PASS: " : "FAIL: ") + what + " : " + data, shouldrun);
|
||||
};})(window);
|
||||
|
||||
// callback for when stuff is blocked
|
||||
var onevalblocked = (function(window) {
|
||||
return function(shouldrun, what, data) {
|
||||
window._testResults[what] = "blocked";
|
||||
window.parent.scriptBlocked(shouldrun, what, data);
|
||||
logResult((shouldrun ? "FAIL: " : "PASS: ") + what + " : " + data, !shouldrun);
|
||||
};})(window);
|
||||
|
||||
|
||||
// Defer until document is loaded so that we can write the pretty result boxes
|
||||
// out.
|
||||
addEventListener('load', function() {
|
||||
// generateCRMFRequest test -- make sure we cannot eval the callback if CSP is in effect
|
||||
try {
|
||||
var script = 'console.log("dynamic script eval\'d in crypto.generateCRMFRequest should be disallowed")';
|
||||
crypto.generateCRMFRequest('CN=0', 0, 0, null, script, 384, null, 'rsa-dual-use');
|
||||
onevalexecuted(false, "crypto.generateCRMFRequest()",
|
||||
"crypto.generateCRMFRequest() should not run!");
|
||||
} catch (e) {
|
||||
onevalblocked(false, "eval(script) inside crypto.generateCRMFRequest",
|
||||
"eval was blocked during crypto.generateCRMFRequest");
|
||||
}
|
||||
|
||||
|
||||
}, false);
|
||||
|
||||
|
||||
|
@ -1,12 +0,0 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>CSP eval script tests: no CSP specified</title>
|
||||
<script type="application/javascript"
|
||||
src="file_CSP_evalscript_no_CSP_at_all.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
Foo. See bug 824652
|
||||
|
||||
</body>
|
||||
</html>
|
@ -1 +0,0 @@
|
||||
Cache-Control: no-cache
|
@ -1,42 +0,0 @@
|
||||
// some javascript for the CSP eval() tests
|
||||
// all of these evals should succeed, as the document loading this script
|
||||
// has script-src 'self' 'unsafe-eval'
|
||||
|
||||
function logResult(str, passed) {
|
||||
var elt = document.createElement('div');
|
||||
var color = passed ? "#cfc;" : "#fcc";
|
||||
elt.setAttribute('style', 'background-color:' + color + '; width:100%; border:1px solid black; padding:3px; margin:4px;');
|
||||
elt.innerHTML = str;
|
||||
document.body.appendChild(elt);
|
||||
}
|
||||
|
||||
// callback for when stuff is allowed by CSP
|
||||
var onevalexecuted = (function(window) {
|
||||
return function(shouldrun, what, data) {
|
||||
window.parent.scriptRan(shouldrun, what, data);
|
||||
logResult((shouldrun ? "PASS: " : "FAIL: ") + what + " : " + data, shouldrun);
|
||||
};})(window);
|
||||
|
||||
// callback for when stuff is blocked
|
||||
var onevalblocked = (function(window) {
|
||||
return function(shouldrun, what, data) {
|
||||
window.parent.scriptBlocked(shouldrun, what, data);
|
||||
logResult((shouldrun ? "FAIL: " : "PASS: ") + what + " : " + data, !shouldrun);
|
||||
};})(window);
|
||||
|
||||
|
||||
// Defer until document is loaded so that we can write the pretty result boxes
|
||||
// out.
|
||||
addEventListener('load', function() {
|
||||
// test that allows crypto.generateCRMFRequest eval to run when there is no CSP at all in place
|
||||
try {
|
||||
var script =
|
||||
'console.log("dynamic script passed to crypto.generateCRMFRequest should execute")';
|
||||
crypto.generateCRMFRequest('CN=0', 0, 0, null, script, 384, null, 'rsa-dual-use');
|
||||
onevalexecuted(true, "eval(script) inside crypto.generateCRMFRequest: no CSP at all",
|
||||
"eval executed during crypto.generateCRMFRequest where no CSP is set at all");
|
||||
} catch (e) {
|
||||
onevalblocked(true, "eval(script) inside crypto.generateCRMFRequest",
|
||||
"eval was blocked during crypto.generateCRMFRequest");
|
||||
}
|
||||
}, false);
|
@ -1,54 +0,0 @@
|
||||
// SJS file for CSP frame ancestor mochitests
|
||||
function handleRequest(request, response)
|
||||
{
|
||||
var query = {};
|
||||
request.queryString.split('&').forEach(function (val) {
|
||||
var [name, value] = val.split('=');
|
||||
query[name] = unescape(value);
|
||||
});
|
||||
|
||||
var isPreflight = request.method == "OPTIONS";
|
||||
|
||||
|
||||
//avoid confusing cache behaviors
|
||||
response.setHeader("Cache-Control", "no-cache", false);
|
||||
|
||||
// grab the desired policy from the query, and then serve a page
|
||||
if (query['csp'])
|
||||
response.setHeader("X-Content-Security-Policy",
|
||||
unescape(query['csp']),
|
||||
false);
|
||||
if (query['scriptedreport']) {
|
||||
// spit back a script that records that the page loaded
|
||||
response.setHeader("Content-Type", "text/javascript", false);
|
||||
if (query['double'])
|
||||
response.write('window.parent.parent.parent.postMessage({call: "frameLoaded", testname: "' + query['scriptedreport'] + '", uri: "window.location.toString()"}, "*");');
|
||||
else
|
||||
response.write('window.parent.parent.postMessage({call: "frameLoaded", testname: "' + query['scriptedreport'] + '", uri: "window.location.toString()"}, "*");');
|
||||
} else if (query['internalframe']) {
|
||||
// spit back an internal iframe (one that might be blocked)
|
||||
response.setHeader("Content-Type", "text/html", false);
|
||||
response.write('<html><head>');
|
||||
if (query['double'])
|
||||
response.write('<script src="file_CSP_frameancestors.sjs?double=1&scriptedreport=' + query['testid'] + '"></script>');
|
||||
else
|
||||
response.write('<script src="file_CSP_frameancestors.sjs?scriptedreport=' + query['testid'] + '"></script>');
|
||||
response.write('</head><body>');
|
||||
response.write(unescape(query['internalframe']));
|
||||
response.write('</body></html>');
|
||||
} else if (query['externalframe']) {
|
||||
// spit back an internal iframe (one that won't be blocked, and probably
|
||||
// has no CSP)
|
||||
response.setHeader("Content-Type", "text/html", false);
|
||||
response.write('<html><head>');
|
||||
response.write('</head><body>');
|
||||
response.write(unescape(query['externalframe']));
|
||||
response.write('</body></html>');
|
||||
} else {
|
||||
// default case: error.
|
||||
response.setHeader("Content-Type", "text/html", false);
|
||||
response.write('<html><body>');
|
||||
response.write("ERROR: not sure what to serve.");
|
||||
response.write('</body></html>');
|
||||
}
|
||||
}
|
@ -1,44 +0,0 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>CSP frame ancestors tests</title>
|
||||
|
||||
<!-- this page shouldn't have a CSP, just the sub-pages. -->
|
||||
<script src='file_CSP_frameancestors_main.js'></script>
|
||||
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- These iframes will get populated by the attached javascript. -->
|
||||
<tt> aa_allow: /* innermost frame allows a */</tt><br/>
|
||||
<iframe id='aa_allow'></iframe><br/>
|
||||
|
||||
<tt> aa_block: /* innermost frame denies a */</tt><br/>
|
||||
<iframe id='aa_block'></iframe><br/>
|
||||
|
||||
<tt> ab_allow: /* innermost frame allows a */</tt><br/>
|
||||
<iframe id='ab_allow'></iframe><br/>
|
||||
|
||||
<tt> ab_block: /* innermost frame denies a */</tt><br/>
|
||||
<iframe id='ab_block'></iframe><br/>
|
||||
|
||||
<tt> aba_allow: /* innermost frame allows b,a */</tt><br/>
|
||||
<iframe id='aba_allow'></iframe><br/>
|
||||
|
||||
<tt> aba_block: /* innermost frame denies b */</tt><br/>
|
||||
<iframe id='aba_block'></iframe><br/>
|
||||
|
||||
<tt> aba2_block: /* innermost frame denies a */</tt><br/>
|
||||
<iframe id='aba2_block'></iframe><br/>
|
||||
|
||||
<tt> abb_allow: /* innermost frame allows b,a */</tt><br/>
|
||||
<iframe id='abb_allow'></iframe><br/>
|
||||
|
||||
<tt> abb_block: /* innermost frame denies b */</tt><br/>
|
||||
<iframe id='abb_block'></iframe><br/>
|
||||
|
||||
<tt> abb2_block: /* innermost frame denies a */</tt><br/>
|
||||
<iframe id='abb2_block'></iframe><br/>
|
||||
|
||||
|
||||
</body>
|
||||
</html>
|
@ -1,65 +0,0 @@
|
||||
// Script to populate the test frames in the frame ancestors mochitest.
|
||||
//
|
||||
function setupFrames() {
|
||||
|
||||
var $ = function(v) { return document.getElementById(v); }
|
||||
var base = {
|
||||
self: '/tests/content/base/test/xcsp/file_CSP_frameancestors.sjs',
|
||||
a: 'http://mochi.test:8888/tests/content/base/test/xcsp/file_CSP_frameancestors.sjs',
|
||||
b: 'http://example.com/tests/content/base/test/xcsp/file_CSP_frameancestors.sjs'
|
||||
};
|
||||
|
||||
var host = { a: 'http://mochi.test:8888', b: 'http://example.com:80' };
|
||||
|
||||
var innerframeuri = null;
|
||||
var elt = null;
|
||||
|
||||
elt = $('aa_allow');
|
||||
elt.src = base.a + "?testid=aa_allow&internalframe=aa_a&csp=" +
|
||||
escape("allow 'none'; frame-ancestors " + host.a + "; script-src 'self'");
|
||||
|
||||
elt = $('aa_block');
|
||||
elt.src = base.a + "?testid=aa_block&internalframe=aa_b&csp=" +
|
||||
escape("allow 'none'; frame-ancestors 'none'; script-src 'self'");
|
||||
|
||||
elt = $('ab_allow');
|
||||
elt.src = base.b + "?testid=ab_allow&internalframe=ab_a&csp=" +
|
||||
escape("allow 'none'; frame-ancestors " + host.a + "; script-src 'self'");
|
||||
|
||||
elt = $('ab_block');
|
||||
elt.src = base.b + "?testid=ab_block&internalframe=ab_b&csp=" +
|
||||
escape("allow 'none'; frame-ancestors 'none'; script-src 'self'");
|
||||
|
||||
/* .... two-level framing */
|
||||
elt = $('aba_allow');
|
||||
innerframeuri = base.a + "?testid=aba_allow&double=1&internalframe=aba_a&csp=" +
|
||||
escape("allow 'none'; frame-ancestors " + host.a + " " + host.b + "; script-src 'self'");
|
||||
elt.src = base.b + "?externalframe=" + escape('<iframe src="' + innerframeuri + '"></iframe>');
|
||||
|
||||
elt = $('aba_block');
|
||||
innerframeuri = base.a + "?testid=aba_allow&double=1&internalframe=aba_b&csp=" +
|
||||
escape("allow 'none'; frame-ancestors " + host.a + "; script-src 'self'");
|
||||
elt.src = base.b + "?externalframe=" + escape('<iframe src="' + innerframeuri + '"></iframe>');
|
||||
|
||||
elt = $('aba2_block');
|
||||
innerframeuri = base.a + "?testid=aba_allow&double=1&internalframe=aba2_b&csp=" +
|
||||
escape("allow 'none'; frame-ancestors " + host.b + "; script-src 'self'");
|
||||
elt.src = base.b + "?externalframe=" + escape('<iframe src="' + innerframeuri + '"></iframe>');
|
||||
|
||||
elt = $('abb_allow');
|
||||
innerframeuri = base.b + "?testid=abb_allow&double=1&internalframe=abb_a&csp=" +
|
||||
escape("allow 'none'; frame-ancestors " + host.a + " " + host.b + "; script-src 'self'");
|
||||
elt.src = base.b + "?externalframe=" + escape('<iframe src="' + innerframeuri + '"></iframe>');
|
||||
|
||||
elt = $('abb_block');
|
||||
innerframeuri = base.b + "?testid=abb_allow&double=1&internalframe=abb_b&csp=" +
|
||||
escape("allow 'none'; frame-ancestors " + host.a + "; script-src 'self'");
|
||||
elt.src = base.b + "?externalframe=" + escape('<iframe src="' + innerframeuri + '"></iframe>');
|
||||
|
||||
elt = $('abb2_block');
|
||||
innerframeuri = base.b + "?testid=abb_allow&double=1&internalframe=abb2_b&csp=" +
|
||||
escape("allow 'none'; frame-ancestors " + host.b + "; script-src 'self'");
|
||||
elt.src = base.b + "?externalframe=" + escape('<iframe src="' + innerframeuri + '"></iframe>');
|
||||
}
|
||||
|
||||
window.addEventListener('load', setupFrames, false);
|
@ -1,20 +0,0 @@
|
||||
<!--
|
||||
-- The original CSP implementation predates the CSP 1.0 spec and didn't
|
||||
-- block inline styles, so when the prefixed X-Content-Security-Policy header is used,
|
||||
-- as it is for this file, inline styles should be allowed.
|
||||
-->
|
||||
<html>
|
||||
<head>
|
||||
<title>CSP inline script tests</title>
|
||||
</head>
|
||||
<body onload="window.parent.scriptRan(false, 'eventattr', 'event attribute in body tag fired')">
|
||||
|
||||
<script type="text/javascript">
|
||||
window.parent.scriptRan(false, "textnode", "text node in a script tag executed.");
|
||||
</script>
|
||||
|
||||
<iframe src='javascript:window.parent.parent.scriptRan(false, "jsuri", "javascript: uri in image tag")'></iframe>
|
||||
|
||||
<a id='anchortoclick' href='javascript:window.parent.scriptRan(false, "jsuri", "javascript: uri in anchor tag ran when clicked.");'>stuff</a>
|
||||
</body>
|
||||
</html>
|
@ -1,2 +0,0 @@
|
||||
X-Content-Security-Policy: allow 'self'
|
||||
Cache-Control: no-cache
|
@ -1,63 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<html>
|
||||
<head>
|
||||
<title>CSP inline script tests</title>
|
||||
<!-- content= "div#linkstylediv { color: #0f0; }" -->
|
||||
<link rel="stylesheet" type="text/css"
|
||||
href='file_CSP.sjs?type=text/css&content=div%23linkstylediv%20%7B%20color%3A%20%230f0%3B%20%7D' />
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<style type="text/css">
|
||||
div#inlinestylediv {
|
||||
color: #00ff00;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div id='linkstylediv'>Link tag (external) stylesheet test (should be green)</div>
|
||||
<div id='attrstylediv' style="color: #00ff00;">Attribute stylesheet test (should be green)</div>
|
||||
<div id='inlinestylediv'>Inline stylesheet test (should be green)</div>
|
||||
|
||||
<!-- tests for SMIL stuff - animations -->
|
||||
<svg xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
width="100%"
|
||||
height="100px">
|
||||
|
||||
<!-- Animates XML attribute, which is mapped into style. -->
|
||||
<text id="xmlTest" x="0" y="15">
|
||||
This should be green since the animation should be allowed by CSP.
|
||||
|
||||
<animate attributeName="fill" attributeType="XML"
|
||||
values="lime;green;lime" dur="2s"
|
||||
repeatCount="indefinite" />
|
||||
</text>
|
||||
|
||||
<!-- Animates override value for CSS property. -->
|
||||
<text id="cssOverrideTest" x="0" y="35">
|
||||
This should be green since the animation should be allowed by CSP.
|
||||
|
||||
<animate attributeName="fill" attributeType="CSS"
|
||||
values="lime;green;lime" dur="2s"
|
||||
repeatCount="indefinite" />
|
||||
</text>
|
||||
|
||||
<!-- Animates override value for CSS property targeted via ID. -->
|
||||
<text id="cssOverrideTestById" x="0" y="55">
|
||||
This should be green since the animation should be allowed by CSP.
|
||||
</text>
|
||||
<animate xlink:href="#cssOverrideTestById"
|
||||
attributeName="fill"
|
||||
values="lime;green;lime"
|
||||
dur="2s" repeatCount="indefinite" />
|
||||
|
||||
<!-- Sets value for CSS property targeted via ID. -->
|
||||
<text id="cssSetTestById" x="0" y="75">
|
||||
This should be green since the <set> should be allowed by CSP.
|
||||
</text>
|
||||
<set xlink:href="#cssSetTestById"
|
||||
attributeName="fill"
|
||||
to="lime" />
|
||||
</svg>
|
||||
</body>
|
||||
</html>
|
@ -1,2 +0,0 @@
|
||||
X-Content-Security-Policy: default-src 'self'
|
||||
Cache-Control: no-cache
|
@ -1,45 +0,0 @@
|
||||
<html>
|
||||
<head>
|
||||
<link rel='stylesheet' type='text/css'
|
||||
href='http://example.org/tests/content/base/test/csp/file_CSP.sjs?testid=style_bad&type=text/css' />
|
||||
<link rel='stylesheet' type='text/css'
|
||||
href='file_CSP.sjs?testid=style_good&type=text/css' />
|
||||
|
||||
<!-- Used to embed inline styles here for testing fonts, but can't do that -->
|
||||
<!-- due to bug 763879 (block inline styles). Moved these to an external, CSS -->
|
||||
<!-- file (file_CSP.css). -->
|
||||
<link rel='stylesheet' type='text/css' href='file_CSP.css' />
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<!-- these should be stopped by CSP. :) -->
|
||||
<img src="http://example.org/tests/content/base/test/csp/file_CSP.sjs?testid=img_bad&type=img/png"> </img>
|
||||
<audio src="http://example.org/tests/content/base/test/csp/file_CSP.sjs?testid=media_bad&type=audio/vorbis"></audio>
|
||||
<script src='http://example.org/tests/content/base/test/csp/file_CSP.sjs?testid=script_bad&type=text/javascript'></script>
|
||||
<iframe src='http://example.org/tests/content/base/test/csp/file_CSP.sjs?testid=frame_bad&content=FAIL'></iframe>
|
||||
<object width="10" height="10">
|
||||
<param name="movie" value="http://example.org/tests/content/base/test/csp/file_CSP.sjs?testid=object_bad&type=application/x-shockwave-flash">
|
||||
<embed src="http://example.org/tests/content/base/test/csp/file_CSP.sjs?testid=object_bad&type=application/x-shockwave-flash"></embed>
|
||||
</object>
|
||||
|
||||
<!-- these should load ok. :) -->
|
||||
<img src="file_CSP.sjs?testid=img_good&type=img/png" />
|
||||
<audio src="file_CSP.sjs?testid=media_good&type=audio/vorbis"></audio>
|
||||
<script src='file_CSP.sjs?testid=script_good&type=text/javascript'></script>
|
||||
<iframe src='file_CSP.sjs?testid=frame_good&content=PASS'></iframe>
|
||||
|
||||
<object width="10" height="10">
|
||||
<param name="movie" value="file_CSP.sjs?testid=object_good&type=application/x-shockwave-flash">
|
||||
<embed src="file_CSP.sjs?testid=object_good&type=application/x-shockwave-flash"></embed>
|
||||
</object>
|
||||
|
||||
<!-- XHR tests... they're taken care of in this script,
|
||||
and since the URI doesn't have any 'testid' values,
|
||||
it will just be ignored by the test framework. -->
|
||||
<script src='file_CSP_main.js'></script>
|
||||
|
||||
<!-- Support elements for the @font-face test -->
|
||||
<div class="div_arbitrary_good">arbitrary good</div>
|
||||
<div class="div_arbitrary_bad">arbitrary_bad</div>
|
||||
</body>
|
||||
</html>
|
@ -1 +0,0 @@
|
||||
X-Content-Security-Policy: default-src 'self'
|
@ -1,16 +0,0 @@
|
||||
// some javascript for the CSP XHR tests
|
||||
//
|
||||
|
||||
try {
|
||||
var xhr_good = new XMLHttpRequest();
|
||||
var xhr_good_uri ="http://mochi.test:8888/tests/content/base/test/csp/file_CSP.sjs?testid=xhr_good";
|
||||
xhr_good.open("GET", xhr_good_uri, true);
|
||||
xhr_good.send(null);
|
||||
} catch(e) {}
|
||||
|
||||
try {
|
||||
var xhr_bad = new XMLHttpRequest();
|
||||
var xhr_bad_uri ="http://example.com/tests/content/base/test/csp/file_CSP.sjs?testid=xhr_bad";
|
||||
xhr_bad.open("GET", xhr_bad_uri, true);
|
||||
xhr_bad.send(null);
|
||||
} catch(e) {}
|
@ -1,6 +0,0 @@
|
||||
<html>
|
||||
<body>
|
||||
<img src="http://example.org/prefixed.jpg"></img>
|
||||
<img src="/unprefixed.jpg"></img>
|
||||
</body>
|
||||
</html>
|
@ -1,2 +0,0 @@
|
||||
X-Content-Security-Policy: default-src 'none' ; img-src http://example.org
|
||||
Content-Security-Policy: default-src 'self'
|
@ -1,25 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=768029
|
||||
-->
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>This is an app for testing</title>
|
||||
|
||||
<link rel="stylesheet" type="text/css"
|
||||
href="file_csp_bug768029.sjs?type=style&origin=same_origin" />
|
||||
<link rel="stylesheet" type="text/css"
|
||||
href="http://example.com/tests/content/base/test/csp/file_csp_bug768029.sjs?type=style&origin=cross_origin" />
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<script src="file_csp_bug768029.sjs?type=script&origin=same_origin"></script>
|
||||
<script src="http://example.com/tests/content/base/test/csp/file_csp_bug768029.sjs?type=script&origin=cross_origin"></script>
|
||||
<img src="file_csp_bug768029.sjs?type=img&origin=same_origin" />
|
||||
<img src="http://example.com/tests/content/base/test/csp/file_csp_bug768029.sjs?type=img&origin=cross_origin" />
|
||||
|
||||
Test for CSP applied to (simulated) app.
|
||||
|
||||
</body>
|
||||
</html>
|
@ -1,29 +0,0 @@
|
||||
function handleRequest(request, response) {
|
||||
|
||||
var query = {};
|
||||
|
||||
request.queryString.split('&').forEach(function(val) {
|
||||
var [name, value] = val.split('=');
|
||||
query[name] = unescape(value);
|
||||
});
|
||||
response.setHeader("Cache-Control", "no-cache", false);
|
||||
|
||||
if ("type" in query) {
|
||||
switch (query.type) {
|
||||
case "script":
|
||||
response.setHeader("Content-Type", "application/javascript");
|
||||
response.write("\n\ndocument.write('<pre>script loaded\\n</pre>');\n\n");
|
||||
return;
|
||||
case "style":
|
||||
response.setHeader("Content-Type", "text/css");
|
||||
response.write("\n\n.cspfoo { color:red; }\n\n");
|
||||
return;
|
||||
case "img":
|
||||
response.setHeader("Content-Type", "image/png");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
response.setHeader("Content-Type", "text/plain");
|
||||
response.write("ohnoes!");
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=773891
|
||||
-->
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>This is an app for csp testing</title>
|
||||
|
||||
<link rel="stylesheet" type="text/css"
|
||||
href="file_csp_bug773891.sjs?type=style&origin=same_origin" />
|
||||
<link rel="stylesheet" type="text/css"
|
||||
href="http://example.com/tests/content/base/test/csp/file_csp_bug773891.sjs?type=style&origin=cross_origin" />
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<script src="file_csp_bug773891.sjs?type=script&origin=same_origin"></script>
|
||||
<script src="http://example.com/tests/content/base/test/csp/file_csp_bug773891.sjs?type=script&origin=cross_origin"></script>
|
||||
<img src="file_csp_bug773891.sjs?type=img&origin=same_origin" />
|
||||
<img src="http://example.com/tests/content/base/test/csp/file_csp_bug773891.sjs?type=img&origin=cross_origin" />
|
||||
|
||||
Test for CSP applied to (simulated) app.
|
||||
|
||||
</body>
|
||||
</html>
|
@ -1,29 +0,0 @@
|
||||
function handleRequest(request, response) {
|
||||
|
||||
var query = {};
|
||||
|
||||
request.queryString.split('&').forEach(function(val) {
|
||||
var [name, value] = val.split('=');
|
||||
query[name] = unescape(value);
|
||||
});
|
||||
response.setHeader("Cache-Control", "no-cache", false);
|
||||
|
||||
if ("type" in query) {
|
||||
switch (query.type) {
|
||||
case "script":
|
||||
response.setHeader("Content-Type", "application/javascript");
|
||||
response.write("\n\ndocument.write('<pre>script loaded\\n</pre>');\n\n");
|
||||
return;
|
||||
case "style":
|
||||
response.setHeader("Content-Type", "text/css");
|
||||
response.write("\n\n.cspfoo { color:red; }\n\n");
|
||||
return;
|
||||
case "img":
|
||||
response.setHeader("Content-Type", "image/png");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
response.setHeader("Content-Type", "text/plain");
|
||||
response.write("ohnoes!");
|
||||
}
|
@ -1,35 +0,0 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>CSP redirect tests</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="container"></div>
|
||||
</body>
|
||||
|
||||
<script>
|
||||
var thisSite = "http://mochi.test:8888";
|
||||
var otherSite = "http://example.com";
|
||||
var page = "/tests/content/base/test/xcsp/file_csp_redirects_page.sjs";
|
||||
|
||||
var tests = { "font-src": thisSite+page+"?testid=font-src&csp=1",
|
||||
"frame-src": thisSite+page+"?testid=frame-src&csp=1",
|
||||
"img-src": thisSite+page+"?testid=img-src&csp=1",
|
||||
"media-src": thisSite+page+"?testid=media-src&csp=1",
|
||||
"object-src": thisSite+page+"?testid=object-src&csp=1",
|
||||
"script-src": thisSite+page+"?testid=script-src&csp=1",
|
||||
"style-src": thisSite+page+"?testid=style-src&csp=1",
|
||||
"worker": thisSite+page+"?testid=worker&csp=1",
|
||||
"xhr-src": thisSite+page+"?testid=xhr-src&csp=1",
|
||||
};
|
||||
|
||||
var container = document.getElementById("container");
|
||||
|
||||
// load each test in its own iframe
|
||||
for (tid in tests) {
|
||||
var i = document.createElement("iframe");
|
||||
i.id = tid;
|
||||
i.src = tests[tid];
|
||||
container.appendChild(i);
|
||||
}
|
||||
</script>
|
||||
</html>
|
@ -1,133 +0,0 @@
|
||||
// SJS file for CSP redirect mochitests
|
||||
// This file serves pages which can optionally specify a Content Security Policy
|
||||
function handleRequest(request, response)
|
||||
{
|
||||
var query = {};
|
||||
request.queryString.split('&').forEach(function (val) {
|
||||
var [name, value] = val.split('=');
|
||||
query[name] = unescape(value);
|
||||
});
|
||||
|
||||
response.setHeader("Cache-Control", "no-cache", false);
|
||||
response.setHeader("Content-Type", "text/html", false);
|
||||
|
||||
var resource = "/tests/content/base/test/csp/file_csp_redirects_resource.sjs";
|
||||
|
||||
// CSP header value
|
||||
if (query["csp"] == 1) {
|
||||
if (query["spec"] == 1) {
|
||||
response.setHeader("Content-Security-Policy", "default-src 'self' ; style-src 'self' 'unsafe-inline'", false);
|
||||
} else {
|
||||
response.setHeader("X-Content-Security-Policy", "allow 'self'", false);
|
||||
}
|
||||
}
|
||||
|
||||
// downloadable font that redirects to another site
|
||||
if (query["testid"] == "font-src") {
|
||||
var resp = '<style type="text/css"> @font-face { font-family:' +
|
||||
'"Redirecting Font"; src: url("' + resource +
|
||||
'?res=font&redir=other&id=font-src-redir")} #test{font-family:' +
|
||||
'"Redirecting Font"}</style></head><body>' +
|
||||
'<div id="test">test</div></body>';
|
||||
response.write(resp);
|
||||
return;
|
||||
}
|
||||
|
||||
if (query["testid"] == "font-src-spec-compliant") {
|
||||
var resp = '<style type="text/css"> @font-face { font-family:' +
|
||||
'"Redirecting Font Spec Compliant"; src: url("' + resource +
|
||||
'?res=font-spec-compliant&redir=other&id=font-src-redir-spec-compliant")} #test{font-family:' +
|
||||
'"Redirecting Font Spec Compliant"}</style></head><body>' +
|
||||
'<div id="test">test</div></body>';
|
||||
response.write(resp);
|
||||
return;
|
||||
}
|
||||
|
||||
// iframe that redirects to another site
|
||||
if (query["testid"] == "frame-src") {
|
||||
response.write('<iframe src="'+resource+'?res=iframe&redir=other&id=frame-src-redir"></iframe>');
|
||||
return;
|
||||
}
|
||||
|
||||
if (query["testid"] == "frame-src-spec-compliant") {
|
||||
response.write('<iframe src="'+resource+'?res=iframe&redir=other&id=frame-src-redir-spec-compliant"></iframe>');
|
||||
return;
|
||||
}
|
||||
|
||||
// image that redirects to another site
|
||||
if (query["testid"] == "img-src") {
|
||||
response.write('<img src="'+resource+'?res=image&redir=other&id=img-src-redir" />');
|
||||
return;
|
||||
}
|
||||
|
||||
if (query["testid"] == "img-src-spec-compliant") {
|
||||
response.write('<img src="'+resource+'?res=image&redir=other&id=img-src-redir-spec-compliant" />');
|
||||
return;
|
||||
}
|
||||
|
||||
// video content that redirects to another site
|
||||
if (query["testid"] == "media-src") {
|
||||
response.write('<video src="'+resource+'?res=media&redir=other&id=media-src-redir"></video>');
|
||||
return;
|
||||
}
|
||||
|
||||
if (query["testid"] == "media-src-spec-compliant") {
|
||||
response.write('<video src="'+resource+'?res=media&redir=other&id=media-src-redir-spec-compliant"></video>');
|
||||
return;
|
||||
}
|
||||
|
||||
// object content that redirects to another site
|
||||
if (query["testid"] == "object-src") {
|
||||
response.write('<object type="text/html" data="'+resource+'?res=object&redir=other&id=object-src-redir"></object>');
|
||||
return;
|
||||
}
|
||||
|
||||
if (query["testid"] == "object-src-spec-compliant") {
|
||||
response.write('<object type="text/html" data="'+resource+'?res=object&redir=other&id=object-src-redir-spec-compliant"></object>');
|
||||
return;
|
||||
}
|
||||
|
||||
// external script that redirects to another site
|
||||
if (query["testid"] == "script-src") {
|
||||
response.write('<script src="'+resource+'?res=script&redir=other&id=script-src-redir"></script>');
|
||||
return;
|
||||
}
|
||||
|
||||
if (query["testid"] == "script-src-spec-compliant") {
|
||||
response.write('<script src="'+resource+'?res=script&redir=other&id=script-src-redir-spec-compliant"></script>');
|
||||
return;
|
||||
}
|
||||
|
||||
// external stylesheet that redirects to another site
|
||||
if (query["testid"] == "style-src") {
|
||||
response.write('<link rel="stylesheet" type="text/css" href="'+resource+'?res=style&redir=other&id=style-src-redir"></script>');
|
||||
return;
|
||||
}
|
||||
|
||||
if (query["testid"] == "style-src-spec-compliant") {
|
||||
response.write('<link rel="stylesheet" type="text/css" href="'+resource+'?res=style&redir=other&id=style-src-redir-spec-compliant"></script>');
|
||||
return;
|
||||
}
|
||||
|
||||
// worker script resource that redirects to another site
|
||||
if (query["testid"] == "worker") {
|
||||
response.write('<script src="'+resource+'?res=worker&redir=other&id=worker-redir"></script>');
|
||||
return;
|
||||
}
|
||||
|
||||
if (query["testid"] == "worker-spec-compliant") {
|
||||
response.write('<script src="'+resource+'?res=worker&redir=other&id=worker-redir-spec-compliant"></script>');
|
||||
return;
|
||||
}
|
||||
|
||||
// script that XHR's to a resource that redirects to another site
|
||||
if (query["testid"] == "xhr-src") {
|
||||
response.write('<script src="'+resource+'?res=xhr"></script>');
|
||||
return;
|
||||
}
|
||||
|
||||
if (query["testid"] == "xhr-src-spec-compliant") {
|
||||
response.write('<script src="'+resource+'?res=xhr-spec-compliant"></script>');
|
||||
return;
|
||||
}
|
||||
}
|
@ -1,128 +0,0 @@
|
||||
// SJS file to serve resources for CSP redirect tests
|
||||
// This file mimics serving resources, e.g. fonts, images, etc., which a CSP
|
||||
// can include. The resource may redirect to a different resource, if specified.
|
||||
function handleRequest(request, response)
|
||||
{
|
||||
var query = {};
|
||||
request.queryString.split('&').forEach(function (val) {
|
||||
var [name, value] = val.split('=');
|
||||
query[name] = unescape(value);
|
||||
});
|
||||
|
||||
var thisSite = "http://mochi.test:8888";
|
||||
var otherSite = "http://example.com";
|
||||
var resource = "/tests/content/base/test/csp/file_csp_redirects_resource.sjs";
|
||||
|
||||
response.setHeader("Cache-Control", "no-cache", false);
|
||||
|
||||
// redirect to a resource on this site
|
||||
if (query["redir"] == "same") {
|
||||
var loc = thisSite+resource+"?res="+query["res"]+"&testid="+query["id"];
|
||||
response.setStatusLine("1.1", 302, "Found");
|
||||
response.setHeader("Location", loc, false);
|
||||
return;
|
||||
}
|
||||
|
||||
// redirect to a resource on a different site
|
||||
else if (query["redir"] == "other") {
|
||||
var loc = otherSite+resource+"?res="+query["res"]+"&testid="+query["id"];
|
||||
response.setStatusLine("1.1", 302, "Found");
|
||||
response.setHeader("Location", loc, false);
|
||||
return;
|
||||
}
|
||||
|
||||
// not a redirect. serve some content.
|
||||
// the content doesn't have to be valid, since we're only checking whether
|
||||
// the request for the content was sent or not.
|
||||
|
||||
// downloadable font
|
||||
if (query["res"] == "font") {
|
||||
response.setHeader("Access-Control-Allow-Origin", "*", false);
|
||||
response.setHeader("Content-Type", "text/plain", false);
|
||||
response.write("font data...");
|
||||
return;
|
||||
}
|
||||
|
||||
if (query["res"] == "font-spec-compliant") {
|
||||
response.setHeader("Access-Control-Allow-Origin", "*", false);
|
||||
response.setHeader("Content-Type", "text/plain", false);
|
||||
response.write("font data...");
|
||||
return;
|
||||
}
|
||||
|
||||
// iframe with arbitrary content
|
||||
if (query["res"] == "iframe") {
|
||||
response.setHeader("Content-Type", "text/html", false);
|
||||
response.write("iframe content...");
|
||||
return;
|
||||
}
|
||||
|
||||
// image
|
||||
if (query["res"] == "image") {
|
||||
response.setHeader("Content-Type", "image/gif", false);
|
||||
response.write("image data...");
|
||||
return;
|
||||
}
|
||||
|
||||
// media content, e.g. Ogg video
|
||||
if (query["res"] == "media") {
|
||||
response.setHeader("Content-Type", "video/ogg", false);
|
||||
response.write("video data...");
|
||||
return;
|
||||
}
|
||||
|
||||
// plugin content, e.g. <object>
|
||||
if (query["res"] == "object") {
|
||||
response.setHeader("Content-Type", "text/html", false);
|
||||
response.write("object data...");
|
||||
return;
|
||||
}
|
||||
|
||||
// script
|
||||
if (query["res"] == "script") {
|
||||
response.setHeader("Content-Type", "application/javascript", false);
|
||||
response.write("some script...");
|
||||
return;
|
||||
}
|
||||
|
||||
// external stylesheet
|
||||
if (query["res"] == "style") {
|
||||
response.setHeader("Content-Type", "text/css", false);
|
||||
response.write("css data...");
|
||||
return;
|
||||
}
|
||||
|
||||
// web worker resource
|
||||
if (query["res"] == "worker") {
|
||||
response.setHeader("Content-Type", "application/javascript", false);
|
||||
response.write("worker script data...");
|
||||
return;
|
||||
}
|
||||
|
||||
// script that invokes XHR
|
||||
if (query["res"] == "xhr") {
|
||||
response.setHeader("Content-Type", "text/html", false);
|
||||
var resp = 'var x = new XMLHttpRequest(); x.open("GET", "' + otherSite +
|
||||
resource+'?res=xhr-resp&testid=xhr-src-redir", false); ' +
|
||||
'x.send(null);';
|
||||
response.write(resp);
|
||||
return;
|
||||
}
|
||||
|
||||
if (query["res"] == "xhr-spec-compliant") {
|
||||
response.setHeader("Content-Type", "text/html", false);
|
||||
var resp = 'var x = new XMLHttpRequest(); x.open("GET", "' + otherSite +
|
||||
resource+'?res=xhr-resp-spec-compliant&testid=xhr-src-redir-spec-compliant", false); ' +
|
||||
'x.send(null);';
|
||||
response.write(resp);
|
||||
return;
|
||||
}
|
||||
|
||||
// response to XHR
|
||||
if (query["res"] == "xhr-resp-spec-compliant") {
|
||||
response.setHeader("Access-Control-Allow-Origin", "*", false);
|
||||
response.setHeader("Content-Type", "text/html", false);
|
||||
response.write('XHR response...');
|
||||
return;
|
||||
}
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
// SJS file for CSP violation report test
|
||||
// https://bugzilla.mozilla.org/show_bug.cgi?id=548193
|
||||
function handleRequest(request, response)
|
||||
{
|
||||
var query = {};
|
||||
request.queryString.split('&').forEach(function (val) {
|
||||
var [name, value] = val.split('=');
|
||||
query[name] = unescape(value);
|
||||
});
|
||||
|
||||
response.setHeader("Content-Type", "text/html", false);
|
||||
|
||||
// avoid confusing cache behaviors
|
||||
response.setHeader("Cache-Control", "no-cache", false);
|
||||
|
||||
// set CSP header
|
||||
response.setHeader("X-Content-Security-Policy",
|
||||
"allow 'self'; report-uri http://mochi.test:8888/csp-report.cgi",
|
||||
false);
|
||||
|
||||
// content which will trigger a violation report
|
||||
response.write('<html><body>');
|
||||
response.write('<img src="http://example.org/tests/content/base/test/file_CSP.sjs?testid=img_bad&type=img/png"> </img>');
|
||||
response.write('</body></html>');
|
||||
}
|
@ -1,2 +0,0 @@
|
||||
Content-Security-Policy: default-src 'self' 'unsafe-inline';
|
||||
X-Content-Security-Policy: allow 'self' 'inline-script';
|
@ -1,15 +0,0 @@
|
||||
<html>
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=717511
|
||||
-->
|
||||
<body>
|
||||
<!-- these should be stopped by CSP after fixing bug 717511. :) -->
|
||||
<img src="http://example.org/tests/content/base/test/file_CSP.sjs?testid=img_bad&type=img/png"> </img>
|
||||
<script src='http://example.org/tests/content/base/test/file_CSP.sjs?testid=script_bad&type=text/javascript'></script>
|
||||
|
||||
<!-- these should load ok after fixing bug 717511. :) -->
|
||||
<img src="file_CSP.sjs?testid=img_good&type=img/png" />
|
||||
<script src='file_CSP.sjs?testid=script_good&type=text/javascript'></script>
|
||||
|
||||
</body>
|
||||
</html>
|
@ -1 +0,0 @@
|
||||
X-Content-Security-Policy: default-src 'self', allow *
|
@ -1,15 +0,0 @@
|
||||
<html>
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=717511
|
||||
-->
|
||||
<body>
|
||||
<!-- these should be stopped by CSP after fixing bug 717511. :) -->
|
||||
<img src="http://example.org/tests/content/base/test/file_CSP.sjs?testid=img2_bad&type=img/png"> </img>
|
||||
<script src='http://example.org/tests/content/base/test/file_CSP.sjs?testid=script2_bad&type=text/javascript'></script>
|
||||
|
||||
<!-- these should load ok after fixing bug 717511. :) -->
|
||||
<img src="file_CSP.sjs?testid=img2_good&type=img/png" />
|
||||
<script src='file_CSP.sjs?testid=script2_good&type=text/javascript'></script>
|
||||
|
||||
</body>
|
||||
</html>
|
@ -1 +0,0 @@
|
||||
X-Content-Security-Policy: default-src 'self' , allow *
|
@ -1,5 +0,0 @@
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=558431
|
||||
-->
|
||||
<iframe id="inner"
|
||||
src="/tests/content/base/test/file_CSP.sjs?content=%3Cdiv%20id%3D%22test%22%3Etest%20558431%3C/div%3E"></iframe>
|
@ -1 +0,0 @@
|
||||
X-Content-Security-Policy: invalid-uri
|
@ -1,38 +0,0 @@
|
||||
// https://bugzilla.mozilla.org/show_bug.cgi?id=650386
|
||||
// This SJS file serves file_redirect_content.html
|
||||
// with a CSP that will trigger a violation and that will report it
|
||||
// to file_redirect_report.sjs
|
||||
//
|
||||
// This handles 301, 302, 303 and 307 redirects. The HTTP status code
|
||||
// returned/type of redirect to do comes from the query string
|
||||
// parameter passed in from the test_bug650386_* files and then also
|
||||
// uses that value in the report-uri parameter of the CSP
|
||||
function handleRequest(request, response) {
|
||||
response.setHeader("Cache-Control", "no-cache", false);
|
||||
|
||||
// this gets used in the CSP as part of the report URI.
|
||||
var redirect = request.queryString;
|
||||
|
||||
if (redirect < 301 || (redirect > 303 && redirect <= 306) || redirect > 307) {
|
||||
// if we somehow got some bogus redirect code here,
|
||||
// do a 302 redirect to the same URL as the report URI
|
||||
// redirects to - this will fail the test.
|
||||
var loc = "http://example.com/some/fake/path";
|
||||
response.setStatusLine("1.1", 302, "Found");
|
||||
response.setHeader("Location", loc, false);
|
||||
return;
|
||||
}
|
||||
|
||||
var csp = "default-src \'self\';report-uri http://mochi.test:8888/tests/content/base/test/csp/file_redirect_report.sjs?" + redirect;
|
||||
|
||||
response.setHeader("X-Content-Security-Policy", csp, false);
|
||||
|
||||
// the actual file content.
|
||||
// this image load will (intentionally) fail due to the CSP policy of default-src: 'self'
|
||||
// specified by the CSP string above.
|
||||
var content = "<!DOCTYPE HTML><html><body><img src = \"http://some.other.domain.example.com\"></body></html>";
|
||||
|
||||
response.write(content);
|
||||
|
||||
return;
|
||||
}
|
@ -1,17 +0,0 @@
|
||||
// https://bugzilla.mozilla.org/show_bug.cgi?id=650386
|
||||
// This SJS file serves as CSP violation report target
|
||||
// and issues a redirect, to make sure the browser does not post to the target
|
||||
// of the redirect, per CSP spec.
|
||||
// This handles 301, 302, 303 and 307 redirects. The HTTP status code
|
||||
// returned/type of redirect to do comes from the query string
|
||||
// parameter
|
||||
function handleRequest(request, response) {
|
||||
response.setHeader("Cache-Control", "no-cache", false);
|
||||
|
||||
var redirect = request.queryString;
|
||||
|
||||
var loc = "http://example.com/some/fake/path";
|
||||
response.setStatusLine("1.1", redirect, "Found");
|
||||
response.setHeader("Location", loc, false);
|
||||
return;
|
||||
}
|
@ -1,13 +0,0 @@
|
||||
<html>
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=702439
|
||||
|
||||
This document is a child frame of a CSP document and the
|
||||
test verifies that it is permitted to run javascript: URLs
|
||||
if the parent has a policy that allows them.
|
||||
-->
|
||||
<body onload="document.getElementById('a').click()">
|
||||
<a id="a" href="javascript:parent.javascript_link_ran = true;
|
||||
parent.checkResult();">click</a>
|
||||
</body>
|
||||
</html>
|
@ -1 +0,0 @@
|
||||
X-Content-Security-Policy: default-src *; options inline-script
|
@ -1,69 +0,0 @@
|
||||
[DEFAULT]
|
||||
support-files =
|
||||
file_CSP.css
|
||||
file_CSP.sjs
|
||||
file_CSP_bug916446.html
|
||||
file_CSP_bug916446.html^headers^
|
||||
file_CSP_evalscript_main.html
|
||||
file_CSP_evalscript_main.html^headers^
|
||||
file_CSP_evalscript_main.js
|
||||
file_CSP_evalscript_main_getCRMFRequest.html
|
||||
file_CSP_evalscript_main_getCRMFRequest.html^headers^
|
||||
file_CSP_evalscript_main_getCRMFRequest.js
|
||||
file_CSP_evalscript_no_CSP_at_all.html
|
||||
file_CSP_evalscript_no_CSP_at_all.html^headers^
|
||||
file_CSP_evalscript_no_CSP_at_all.js
|
||||
file_CSP_frameancestors.sjs
|
||||
file_CSP_frameancestors_main.html
|
||||
file_CSP_frameancestors_main.js
|
||||
file_CSP_inlinescript_main.html
|
||||
file_CSP_inlinescript_main.html^headers^
|
||||
file_CSP_inlinestyle_main.html
|
||||
file_CSP_inlinestyle_main.html^headers^
|
||||
file_CSP_main.html
|
||||
file_CSP_main.html^headers^
|
||||
file_CSP_main.js
|
||||
file_bothCSPheaders.html
|
||||
file_bothCSPheaders.html^headers^
|
||||
file_csp_bug768029.html
|
||||
file_csp_bug768029.sjs
|
||||
file_csp_bug773891.html
|
||||
file_csp_bug773891.sjs
|
||||
file_csp_redirects_main.html
|
||||
file_csp_redirects_page.sjs
|
||||
file_csp_redirects_resource.sjs
|
||||
file_dual_headers_warning.html
|
||||
file_dual_headers_warning.html^headers^
|
||||
file_csp_report.sjs
|
||||
file_policyuri_async_fetch.html
|
||||
file_policyuri_async_fetch.html^headers^
|
||||
file_redirect_content.sjs
|
||||
file_redirect_report.sjs
|
||||
file_subframe_run_js_if_allowed.html
|
||||
file_subframe_run_js_if_allowed.html^headers^
|
||||
file_multi_policy_injection_bypass.html
|
||||
file_multi_policy_injection_bypass.html^headers^
|
||||
file_multi_policy_injection_bypass_2.html
|
||||
file_multi_policy_injection_bypass_2.html^headers^
|
||||
|
||||
[test_CSP.html]
|
||||
[test_CSP_bug916446.html]
|
||||
[test_CSP_evalscript.html]
|
||||
[test_CSP_evalscript_getCRMFRequest.html]
|
||||
skip-if = buildapp == 'b2g' || toolkit == 'android' || e10s # no (deprecated) window.crypto support in multiprocess (bug 824652)
|
||||
[test_CSP_frameancestors.html]
|
||||
skip-if = (buildapp == 'b2g' && (toolkit != 'gonk' || debug)) || toolkit == 'android' # Times out, not sure why (bug 1008445)
|
||||
[test_CSP_inlinescript.html]
|
||||
[test_CSP_inlinestyle.html]
|
||||
[test_bothCSPheaders.html]
|
||||
[test_csp_redirects.html]
|
||||
[test_dual_headers_warning.html]
|
||||
[test_csp_report.html]
|
||||
skip-if = e10s || buildapp == 'b2g' # http-on-opening-request observer not supported in child process (bug 1009632)
|
||||
[test_policyuri_async_fetch.html]
|
||||
[test_301_redirect.html]
|
||||
[test_302_redirect.html]
|
||||
[test_303_redirect.html]
|
||||
[test_307_redirect.html]
|
||||
[test_subframe_run_js_if_allowed.html]
|
||||
[test_multi_policy_injection_bypass.html]
|
@ -1,10 +0,0 @@
|
||||
# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
|
||||
# vim: set filetype=python:
|
||||
# This Source Code Form is subject to the terms of the Mozilla Public
|
||||
# License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
MOCHITEST_MANIFESTS += ['mochitest.ini']
|
||||
|
||||
MOCHITEST_CHROME_MANIFESTS += ['chrome.ini']
|
||||
|
@ -1,73 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=650386
|
||||
Test that CSP violation reports are not sent when a 301 redirect is encountered
|
||||
-->
|
||||
<head>
|
||||
<title>Test for Bug 650386</title>
|
||||
<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
|
||||
</head>
|
||||
<body>
|
||||
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=650386">Mozilla Bug 650386</a>
|
||||
<p id="display"></p>
|
||||
<div id="content" style="display: none">
|
||||
<iframe id = "content_iframe"></iframe>
|
||||
</div>
|
||||
<pre id="test">
|
||||
<script type="application/javascript">
|
||||
|
||||
/** Test for Bug 650386 **/
|
||||
|
||||
// This is used to watch the redirect of the report POST get blocked
|
||||
function examiner() {
|
||||
SpecialPowers.addObserver(this, "csp-on-violate-policy", false);
|
||||
SpecialPowers.addObserver(this, "specialpowers-http-notify-request", false);
|
||||
}
|
||||
|
||||
examiner.prototype = {
|
||||
observe: function(subject, topic, data) {
|
||||
if (topic === "specialpowers-http-notify-request") {
|
||||
// this is used to fail the test - if we see the POST to the target of the redirect
|
||||
// we know this is a fail
|
||||
var uri = data;
|
||||
if (uri == "http://example.com/some/fake/path")
|
||||
window.done(false);
|
||||
}
|
||||
|
||||
if(topic === "csp-on-violate-policy") {
|
||||
// something was blocked, but we are looking specifically for the redirect being blocked
|
||||
if (data == "denied redirect while sending violation report")
|
||||
window.done(true);
|
||||
}
|
||||
},
|
||||
|
||||
// must eventually call this to remove the listener,
|
||||
// or mochitests might get borked.
|
||||
remove: function() {
|
||||
SpecialPowers.removeObserver(this, "csp-on-violate-policy");
|
||||
SpecialPowers.removeObserver(this, "specialpowers-http-notify-request");
|
||||
}
|
||||
}
|
||||
|
||||
window.examiner = new examiner();
|
||||
|
||||
// result == true if we saw the redirect blocked notify, false if we saw the post
|
||||
// to the redirect target go out
|
||||
window.done = function(result) {
|
||||
ok(result, "a 301 redirect when posting violation report should be blocked");
|
||||
|
||||
// clean up observers and finish the test
|
||||
window.examiner.remove();
|
||||
SimpleTest.finish();
|
||||
}
|
||||
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
// save this for last so that our listeners are registered.
|
||||
document.getElementById('content_iframe').src = 'file_redirect_content.sjs?301';
|
||||
</script>
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
@ -1,73 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=650386
|
||||
Test that CSP violation reports are not sent when a 302 redirect is encountered
|
||||
-->
|
||||
<head>
|
||||
<title>Test for Bug 650386</title>
|
||||
<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
|
||||
</head>
|
||||
<body>
|
||||
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=650386">Mozilla Bug 650386</a>
|
||||
<p id="display"></p>
|
||||
<div id="content" style="display: none">
|
||||
<iframe id = "content_iframe"></iframe>
|
||||
</div>
|
||||
<pre id="test">
|
||||
<script type="application/javascript">
|
||||
|
||||
/** Test for Bug 650386 **/
|
||||
|
||||
// This is used to watch the redirect of the report POST get blocked
|
||||
function examiner() {
|
||||
SpecialPowers.addObserver(this, "csp-on-violate-policy", false);
|
||||
SpecialPowers.addObserver(this, "specialpowers-http-notify-request", false);
|
||||
}
|
||||
|
||||
examiner.prototype = {
|
||||
observe: function(subject, topic, data) {
|
||||
if (topic === "specialpowers-http-notify-request") {
|
||||
// this is used to fail the test - if we see the POST to the target of the redirect
|
||||
// we know this is a fail
|
||||
var uri = data;
|
||||
if (uri == "http://example.com/some/fake/path")
|
||||
window.done(false);
|
||||
}
|
||||
|
||||
if(topic === "csp-on-violate-policy") {
|
||||
// something was blocked, but we are looking specifically for the redirect being blocked
|
||||
if (data == "denied redirect while sending violation report")
|
||||
window.done(true);
|
||||
}
|
||||
},
|
||||
|
||||
// must eventually call this to remove the listener,
|
||||
// or mochitests might get borked.
|
||||
remove: function() {
|
||||
SpecialPowers.removeObserver(this, "csp-on-violate-policy");
|
||||
SpecialPowers.removeObserver(this, "specialpowers-http-notify-request");
|
||||
}
|
||||
}
|
||||
|
||||
window.examiner = new examiner();
|
||||
|
||||
// result == true if we saw the redirect blocked notify, false if we saw the post
|
||||
// to the redirect target go out
|
||||
window.done = function(result) {
|
||||
ok(result, "a 302 redirect when posting violation report should be blocked");
|
||||
|
||||
// clean up observers and finish the test
|
||||
window.examiner.remove();
|
||||
SimpleTest.finish();
|
||||
}
|
||||
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
// save this for last so that our listeners are registered.
|
||||
document.getElementById('content_iframe').src = 'file_redirect_content.sjs?302';
|
||||
</script>
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
@ -1,73 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=650386
|
||||
Test that CSP violation reports are not sent when a 303 redirect is encountered
|
||||
-->
|
||||
<head>
|
||||
<title>Test for Bug 650386</title>
|
||||
<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
|
||||
</head>
|
||||
<body>
|
||||
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=650386">Mozilla Bug 650386</a>
|
||||
<p id="display"></p>
|
||||
<div id="content" style="display: none">
|
||||
<iframe id = "content_iframe"></iframe>
|
||||
</div>
|
||||
<pre id="test">
|
||||
<script type="application/javascript">
|
||||
|
||||
/** Test for Bug 650386 **/
|
||||
|
||||
// This is used to watch the redirect of the report POST get blocked
|
||||
function examiner() {
|
||||
SpecialPowers.addObserver(this, "csp-on-violate-policy", false);
|
||||
SpecialPowers.addObserver(this, "specialpowers-http-notify-request", false);
|
||||
}
|
||||
|
||||
examiner.prototype = {
|
||||
observe: function(subject, topic, data) {
|
||||
if (topic === "specialpowers-http-notify-request") {
|
||||
// this is used to fail the test - if we see the POST to the target of the redirect
|
||||
// we know this is a fail
|
||||
var uri = data;
|
||||
if (uri == "http://example.com/some/fake/path")
|
||||
window.done(false);
|
||||
}
|
||||
|
||||
if(topic === "csp-on-violate-policy") {
|
||||
// something was blocked, but we are looking specifically for the redirect being blocked
|
||||
if (data == "denied redirect while sending violation report")
|
||||
window.done(true);
|
||||
}
|
||||
},
|
||||
|
||||
// must eventually call this to remove the listener,
|
||||
// or mochitests might get borked.
|
||||
remove: function() {
|
||||
SpecialPowers.removeObserver(this, "csp-on-violate-policy");
|
||||
SpecialPowers.removeObserver(this, "specialpowers-http-notify-request");
|
||||
}
|
||||
}
|
||||
|
||||
window.examiner = new examiner();
|
||||
|
||||
// result == true if we saw the redirect blocked notify, false if we saw the post
|
||||
// to the redirect target go out
|
||||
window.done = function(result) {
|
||||
ok(result, "a 303 redirect when posting violation report should be blocked");
|
||||
|
||||
// clean up observers and finish the test
|
||||
window.examiner.remove();
|
||||
SimpleTest.finish();
|
||||
}
|
||||
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
// save this for last so that our listeners are registered.
|
||||
document.getElementById('content_iframe').src = 'file_redirect_content.sjs?303';
|
||||
</script>
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
@ -1,73 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=650386
|
||||
Test that CSP violation reports are not sent when a 307 redirect is encountered
|
||||
-->
|
||||
<head>
|
||||
<title>Test for Bug 650386</title>
|
||||
<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
|
||||
</head>
|
||||
<body>
|
||||
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=650386">Mozilla Bug 650386</a>
|
||||
<p id="display"></p>
|
||||
<div id="content" style="display: none">
|
||||
<iframe id = "content_iframe"></iframe>
|
||||
</div>
|
||||
<pre id="test">
|
||||
<script type="application/javascript">
|
||||
|
||||
/** Test for Bug 650386 **/
|
||||
|
||||
// This is used to watch the redirect of the report POST get blocked
|
||||
function examiner() {
|
||||
SpecialPowers.addObserver(this, "csp-on-violate-policy", false);
|
||||
SpecialPowers.addObserver(this, "specialpowers-http-notify-request", false);
|
||||
}
|
||||
|
||||
examiner.prototype = {
|
||||
observe: function(subject, topic, data) {
|
||||
if (topic === "specialpowers-http-notify-request") {
|
||||
// this is used to fail the test - if we see the POST to the target of the redirect
|
||||
// we know this is a fail
|
||||
var uri = data;
|
||||
if (uri == "http://example.com/some/fake/path")
|
||||
window.done(false);
|
||||
}
|
||||
|
||||
if(topic === "csp-on-violate-policy") {
|
||||
// something was blocked, but we are looking specifically for the redirect being blocked
|
||||
if (data == "denied redirect while sending violation report")
|
||||
window.done(true);
|
||||
}
|
||||
},
|
||||
|
||||
// must eventually call this to remove the listener,
|
||||
// or mochitests might get borked.
|
||||
remove: function() {
|
||||
SpecialPowers.removeObserver(this, "csp-on-violate-policy");
|
||||
SpecialPowers.removeObserver(this, "specialpowers-http-notify-request");
|
||||
}
|
||||
}
|
||||
|
||||
window.examiner = new examiner();
|
||||
|
||||
// result == true if we saw the redirect blocked notify, false if we saw the post
|
||||
// to the redirect target go out
|
||||
window.done = function(result) {
|
||||
ok(result, "a 307 redirect when posting violation report should be blocked");
|
||||
|
||||
// clean up observers and finish the test
|
||||
window.examiner.remove();
|
||||
SimpleTest.finish();
|
||||
}
|
||||
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
// save this for last so that our listeners are registered.
|
||||
document.getElementById('content_iframe').src = 'file_redirect_content.sjs?307';
|
||||
</script>
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
@ -1,119 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<title>Test for Content Security Policy Connections</title>
|
||||
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
|
||||
</head>
|
||||
<body>
|
||||
<p id="display"></p>
|
||||
<div id="content" style="display: none">
|
||||
</div>
|
||||
<iframe style="width:200px;height:200px;" id='cspframe'></iframe>
|
||||
<script class="testbody" type="text/javascript">
|
||||
|
||||
// These are test results: -1 means it hasn't run,
|
||||
// true/false is the pass/fail result.
|
||||
window.tests = {
|
||||
img_good: -1,
|
||||
img_bad: -1,
|
||||
style_good: -1,
|
||||
style_bad: -1,
|
||||
frame_good: -1,
|
||||
frame_bad: -1,
|
||||
script_good: -1,
|
||||
script_bad: -1,
|
||||
xhr_good: -1,
|
||||
xhr_bad: -1,
|
||||
media_good: -1,
|
||||
media_bad: -1,
|
||||
font_good: -1,
|
||||
font_bad: -1,
|
||||
object_good: -1,
|
||||
object_bad: -1,
|
||||
};
|
||||
|
||||
// This is used to watch the blocked data bounce off CSP and allowed data
|
||||
// get sent out to the wire.
|
||||
function examiner() {
|
||||
SpecialPowers.addObserver(this, "csp-on-violate-policy", false);
|
||||
SpecialPowers.addObserver(this, "specialpowers-http-notify-request", false);
|
||||
}
|
||||
examiner.prototype = {
|
||||
observe: function(subject, topic, data) {
|
||||
var testpat = new RegExp("testid=([a-z0-9_]+)");
|
||||
|
||||
//_good things better be allowed!
|
||||
//_bad things better be stopped!
|
||||
|
||||
// This is a special observer topic that is proxied from
|
||||
// http-on-modify-request in the parent process to inform us when a URI is
|
||||
// loaded
|
||||
if (topic === "specialpowers-http-notify-request") {
|
||||
var uri = data;
|
||||
if (!testpat.test(uri)) return;
|
||||
var testid = testpat.exec(uri)[1];
|
||||
|
||||
window.testResult(testid,
|
||||
/_good/.test(testid),
|
||||
uri + " allowed by csp");
|
||||
}
|
||||
|
||||
if (topic === "csp-on-violate-policy") {
|
||||
// these were blocked... record that they were blocked
|
||||
var asciiSpec = SpecialPowers.getPrivilegedProps(SpecialPowers.do_QueryInterface(subject, "nsIURI"), "asciiSpec");
|
||||
if (!testpat.test(asciiSpec)) return;
|
||||
var testid = testpat.exec(asciiSpec)[1];
|
||||
window.testResult(testid,
|
||||
/_bad/.test(testid),
|
||||
asciiSpec + " blocked by \"" + data + "\"");
|
||||
}
|
||||
},
|
||||
|
||||
// must eventually call this to remove the listener,
|
||||
// or mochitests might get borked.
|
||||
remove: function() {
|
||||
SpecialPowers.removeObserver(this, "csp-on-violate-policy");
|
||||
SpecialPowers.removeObserver(this, "specialpowers-http-notify-request");
|
||||
}
|
||||
}
|
||||
|
||||
window.examiner = new examiner();
|
||||
|
||||
window.testResult = function(testname, result, msg) {
|
||||
//test already complete.... forget it... remember the first result.
|
||||
if (window.tests[testname] != -1)
|
||||
return;
|
||||
|
||||
window.tests[testname] = result;
|
||||
is(result, true, testname + ' test: ' + msg);
|
||||
|
||||
// if any test is incomplete, keep waiting
|
||||
for (var v in window.tests)
|
||||
if(tests[v] == -1)
|
||||
return;
|
||||
|
||||
// ... otherwise, finish
|
||||
window.examiner.remove();
|
||||
SimpleTest.finish();
|
||||
}
|
||||
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
SpecialPowers.pushPrefEnv(
|
||||
{'set':[["security.csp.speccompliant", true],
|
||||
// This defaults to 0 ("preload none") on mobile (B2G/Android), which
|
||||
// blocks loading the resource until the user interacts with a
|
||||
// corresponding widget, which breaks the media_* tests. We set it
|
||||
// back to the default used by desktop Firefox to get consistent
|
||||
// behavior.
|
||||
["media.preload.default", 2]]},
|
||||
function() {
|
||||
// save this for last so that our listeners are registered.
|
||||
// ... this loads the testbed of good and bad requests.
|
||||
document.getElementById('cspframe').src = 'file_CSP_main.html';
|
||||
});
|
||||
</script>
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
@ -1,114 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<title>Test for Bug 916446</title>
|
||||
<!--
|
||||
test that an invalid report-only policy (a stripped down version of what
|
||||
web.tweetdeck.com was serving) defaults to "default-src 'none'" but only
|
||||
sends reports and is not accidentally enforced
|
||||
-->
|
||||
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
|
||||
</head>
|
||||
<body>
|
||||
<iframe style="width:200px;height:200px;" id='testframe'></iframe>
|
||||
|
||||
<script class="testbody" type="text/javascript">
|
||||
|
||||
// This is used to watch the blocked data bounce off CSP and allowed data
|
||||
// get sent out to the wire.
|
||||
function examiner() {
|
||||
SpecialPowers.addObserver(this, "csp-on-violate-policy", false);
|
||||
SpecialPowers.addObserver(this, "specialpowers-http-notify-request", false);
|
||||
}
|
||||
examiner.prototype = {
|
||||
completedTests: 0,
|
||||
totalTests: 4,
|
||||
|
||||
observe: function(subject, topic, data) {
|
||||
var testpat = new RegExp("testid=([a-z0-9_]+)");
|
||||
|
||||
if (topic === "specialpowers-http-notify-request") {
|
||||
// these things were allowed by CSP
|
||||
var uri = data;
|
||||
if (!testpat.test(uri)) return;
|
||||
var testid = testpat.exec(uri)[1];
|
||||
if (testid === "img_bad") {
|
||||
// img_bad should be *allowed* because the policy is report-only
|
||||
ok(true, "External loads should be allowed because the policy is report-only");
|
||||
this.completedTests++;
|
||||
}
|
||||
}
|
||||
|
||||
if(topic === "csp-on-violate-policy") {
|
||||
// these were blocked
|
||||
try {
|
||||
var asciiSpec = SpecialPowers.getPrivilegedProps(SpecialPowers.do_QueryInterface(subject, "nsIURI"), "asciiSpec");
|
||||
if (!testpat.test(asciiSpec)) return;
|
||||
var testid = testpat.exec(asciiSpec)[1];
|
||||
if (testid === "img_bad") {
|
||||
ok(true, "External loads should trigger a violation report (because the policy should fail closed to \"default-src 'none'\")");
|
||||
this.completedTests++;
|
||||
}
|
||||
} catch (e) {
|
||||
// if that fails, the subject is probably a string
|
||||
violation_msg = SpecialPowers.getPrivilegedProps(SpecialPowers.do_QueryInterface(subject, "nsISupportsCString"), "data");
|
||||
if (/Inline Scripts will not execute/.test(violation_msg)) {
|
||||
ok(true, "Inline scripts should trigger a violation report (because the policy should fail closed to \"default-src 'none'\")");
|
||||
this.completedTests++;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// must eventually call this to remove the listener,
|
||||
// or mochitests might get borked.
|
||||
remove: function() {
|
||||
SpecialPowers.removeObserver(this, "csp-on-violate-policy");
|
||||
SpecialPowers.removeObserver(this, "specialpowers-http-notify-request");
|
||||
}
|
||||
}
|
||||
|
||||
window.examiner = new examiner();
|
||||
|
||||
function checkInlineScriptExecuted() {
|
||||
var green = 'rgb(0, 128, 0)';
|
||||
var black = 'rgb(0, 0, 0)';
|
||||
var that = this;
|
||||
function getElementColorById(id) {
|
||||
return window.getComputedStyle(that.contentDocument.getElementById(id)).color;
|
||||
}
|
||||
if (getElementColorById('inline-script') === green) {
|
||||
ok(true, "Inline scripts should execute (because the policy is report-only)");
|
||||
window.examiner.completedTests++;
|
||||
}
|
||||
|
||||
waitToFinish();
|
||||
}
|
||||
|
||||
function waitToFinish() {
|
||||
setTimeout(function wait() {
|
||||
if (window.examiner.completedTests < window.examiner.totalTests) {
|
||||
waitToFinish();
|
||||
} else {
|
||||
// Cleanup
|
||||
window.examiner.remove();
|
||||
SimpleTest.finish();
|
||||
}
|
||||
}, 10);
|
||||
}
|
||||
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
SpecialPowers.pushPrefEnv(
|
||||
{'set':[["security.csp.speccompliant", false]]},
|
||||
function() {
|
||||
var testframe = document.getElementById('testframe');
|
||||
testframe.src = 'file_CSP_bug916446.html';
|
||||
testframe.addEventListener('load', checkInlineScriptExecuted);
|
||||
}
|
||||
);
|
||||
</script>
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
@ -1,58 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<title>Test for Content Security Policy "no eval" base restriction</title>
|
||||
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
|
||||
</head>
|
||||
<body>
|
||||
<p id="display"></p>
|
||||
<div id="content" style="display: none">
|
||||
</div>
|
||||
<iframe style="width:100%;height:300px;" id='cspframe'></iframe>
|
||||
<script class="testbody" type="text/javascript">
|
||||
|
||||
var evalScriptsThatRan = 0;
|
||||
var evalScriptsBlocked = 0;
|
||||
var evalScriptsTotal = 8;
|
||||
|
||||
// called by scripts that run
|
||||
var scriptRan = function(shouldrun, testname, data) {
|
||||
evalScriptsThatRan++;
|
||||
ok(shouldrun, 'EVAL SCRIPT RAN: ' + testname + '(' + data + ')');
|
||||
checkTestResults();
|
||||
}
|
||||
|
||||
// called when a script is blocked
|
||||
var scriptBlocked = function(shouldrun, testname, data) {
|
||||
evalScriptsBlocked++;
|
||||
ok(!shouldrun, 'EVAL SCRIPT BLOCKED: ' + testname + '(' + data + ')');
|
||||
checkTestResults();
|
||||
}
|
||||
|
||||
|
||||
// Check to see if all the tests have run
|
||||
var checkTestResults = function() {
|
||||
// if any test is incomplete, keep waiting
|
||||
if (evalScriptsTotal - evalScriptsBlocked - evalScriptsThatRan > 0)
|
||||
return;
|
||||
|
||||
// ... otherwise, finish
|
||||
SimpleTest.finish();
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// set up and go
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
SpecialPowers.pushPrefEnv(
|
||||
{'set':[["security.csp.speccompliant", true]]},
|
||||
function() {
|
||||
// save this for last so that our listeners are registered.
|
||||
// ... this loads the testbed of good and bad requests.
|
||||
document.getElementById('cspframe').src = 'file_CSP_evalscript_main.html';
|
||||
});
|
||||
</script>
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
@ -1,61 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<title>Test for Content Security Policy "no eval" in crypto.getCRMFRequest()</title>
|
||||
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
|
||||
</head>
|
||||
<body>
|
||||
<p id="display"></p>
|
||||
<div id="content" style="display: none">
|
||||
</div>
|
||||
<iframe style="width:100%;height:300px;" id='cspframe'></iframe>
|
||||
<iframe style="width:100%;height:300px;" id='cspframe2'></iframe>
|
||||
<script class="testbody" type="text/javascript">
|
||||
|
||||
var path = "/tests/content/base/test/csp/";
|
||||
|
||||
var evalScriptsThatRan = 0;
|
||||
var evalScriptsBlocked = 0;
|
||||
var evalScriptsTotal = 2;
|
||||
|
||||
// called by scripts that run
|
||||
var scriptRan = function(shouldrun, testname, data) {
|
||||
evalScriptsThatRan++;
|
||||
ok(shouldrun, 'EVAL SCRIPT RAN: ' + testname + '(' + data + ')');
|
||||
checkTestResults();
|
||||
}
|
||||
|
||||
// called when a script is blocked
|
||||
var scriptBlocked = function(shouldrun, testname, data) {
|
||||
evalScriptsBlocked++;
|
||||
ok(!shouldrun, 'EVAL SCRIPT BLOCKED: ' + testname + '(' + data + ')');
|
||||
checkTestResults();
|
||||
}
|
||||
|
||||
// Check to see if all the tests have run
|
||||
var checkTestResults = function() {
|
||||
// if any test is incomplete, keep waiting
|
||||
if (evalScriptsTotal - evalScriptsBlocked - evalScriptsThatRan > 0)
|
||||
return;
|
||||
|
||||
// ... otherwise, finish
|
||||
SimpleTest.finish();
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// set up and go
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
SpecialPowers.pushPrefEnv(
|
||||
{'set':[["security.csp.speccompliant", true]]},
|
||||
function() {
|
||||
// save this for last so that our listeners are registered.
|
||||
// ... this loads the testbed of good and bad requests.
|
||||
document.getElementById('cspframe').src = 'file_CSP_evalscript_main_getCRMFRequest.html';
|
||||
document.getElementById('cspframe2').src = 'file_CSP_evalscript_no_CSP_at_all.html';
|
||||
});
|
||||
</script>
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
@ -1,131 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<title>Test for Content Security Policy Frame Ancestors directive</title>
|
||||
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
|
||||
</head>
|
||||
<body>
|
||||
<p id="display"></p>
|
||||
<div id="content" style="display: none">
|
||||
</div>
|
||||
<iframe style="width:100%;height:300px;" id='cspframe'></iframe>
|
||||
<script class="testbody" type="text/javascript">
|
||||
|
||||
// These are test results: -1 means it hasn't run,
|
||||
// true/false is the pass/fail result.
|
||||
var framesThatShouldLoad = {
|
||||
aa_allow: -1, /* innermost frame allows a */
|
||||
//aa_block: -1, /* innermost frame denies a */
|
||||
ab_allow: -1, /* innermost frame allows a */
|
||||
//ab_block: -1, /* innermost frame denies a */
|
||||
aba_allow: -1, /* innermost frame allows b,a */
|
||||
//aba_block: -1, /* innermost frame denies b */
|
||||
//aba2_block: -1, /* innermost frame denies a */
|
||||
abb_allow: -1, /* innermost frame allows b,a */
|
||||
//abb_block: -1, /* innermost frame denies b */
|
||||
//abb2_block: -1, /* innermost frame denies a */
|
||||
};
|
||||
|
||||
var expectedViolationsLeft = 6;
|
||||
|
||||
// This is used to watch the blocked data bounce off CSP and allowed data
|
||||
// get sent out to the wire.
|
||||
function examiner() {
|
||||
SpecialPowers.addObserver(this, "csp-on-violate-policy", false);
|
||||
}
|
||||
examiner.prototype = {
|
||||
observe: function(subject, topic, data) {
|
||||
// subject should be an nsURI, and should be either allowed or blocked.
|
||||
if (!SpecialPowers.can_QI(subject))
|
||||
return;
|
||||
|
||||
if (topic === "csp-on-violate-policy") {
|
||||
//these were blocked... record that they were blocked
|
||||
|
||||
var asciiSpec = subject;
|
||||
// Except CSP prohibits cross-origin URI reporting during frame ancestors
|
||||
// checks so this may not be an nsIURI.
|
||||
try {
|
||||
asciiSpec = SpecialPowers.getPrivilegedProps(SpecialPowers.do_QueryInterface(subject, "nsIURI"), "asciiSpec");
|
||||
} catch (ex) {
|
||||
// was not an nsIURI, so it was probably a cross-origin report.
|
||||
}
|
||||
|
||||
window.frameBlocked(asciiSpec, data);
|
||||
}
|
||||
},
|
||||
|
||||
// must eventually call this to remove the listener,
|
||||
// or mochitests might get borked.
|
||||
remove: function() {
|
||||
SpecialPowers.removeObserver(this, "csp-on-violate-policy");
|
||||
}
|
||||
}
|
||||
|
||||
// called when a frame is loaded
|
||||
// -- if it's not enumerated above, it should not load!
|
||||
var frameLoaded = function(testname, uri) {
|
||||
//test already complete.... forget it... remember the first result.
|
||||
if (window.framesThatShouldLoad[testname] != -1)
|
||||
return;
|
||||
|
||||
if (typeof window.framesThatShouldLoad[testname] === 'undefined') {
|
||||
// uh-oh, we're not expecting this frame to load!
|
||||
ok(false, testname + ' framed site should not have loaded: ' + uri);
|
||||
} else {
|
||||
framesThatShouldLoad[testname] = true;
|
||||
ok(true, testname + ' framed site when allowed by csp (' + uri + ')');
|
||||
}
|
||||
checkTestResults();
|
||||
}
|
||||
|
||||
// called when a frame is blocked
|
||||
// -- we can't determine *which* frame was blocked, but at least we can count them
|
||||
var frameBlocked = function(uri, policy) {
|
||||
ok(true, 'a CSP policy blocked frame from being loaded: ' + policy);
|
||||
expectedViolationsLeft--;
|
||||
checkTestResults();
|
||||
}
|
||||
|
||||
|
||||
// Check to see if all the tests have run
|
||||
var checkTestResults = function() {
|
||||
// if any test is incomplete, keep waiting
|
||||
for (var v in framesThatShouldLoad)
|
||||
if(window.framesThatShouldLoad[v] == -1)
|
||||
return;
|
||||
|
||||
if (window.expectedViolationsLeft > 0)
|
||||
return;
|
||||
|
||||
// ... otherwise, finish
|
||||
window.examiner.remove();
|
||||
SimpleTest.finish();
|
||||
}
|
||||
|
||||
window.addEventListener("message", receiveMessage, false);
|
||||
|
||||
function receiveMessage(event) {
|
||||
if (event.data.call && event.data.call == 'frameLoaded')
|
||||
frameLoaded(event.data.testname, event.data.uri);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// set up and go
|
||||
window.examiner = new examiner();
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
// added this so the tests run even if we don't flip the pref on by default.
|
||||
SpecialPowers.pushPrefEnv(
|
||||
{'set':[["security.csp.speccompliant", true]]},
|
||||
function() {
|
||||
// save this for last so that our listeners are registered.
|
||||
// ... this loads the testbed of good and bad requests.
|
||||
document.getElementById('cspframe').src = 'file_CSP_frameancestors_main.html';
|
||||
});
|
||||
|
||||
</script>
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
@ -1,95 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<title>Test for Content Security Policy Frame Ancestors directive</title>
|
||||
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
|
||||
</head>
|
||||
<body>
|
||||
<p id="display"></p>
|
||||
<div id="content" style="display: none">
|
||||
</div>
|
||||
|
||||
<iframe style="width:100%;height:300px;" id='cspframe'></iframe>
|
||||
<script class="testbody" type="text/javascript">
|
||||
|
||||
var inlineScriptsBlocked = 0;
|
||||
var inlineScriptsTotal = 4;
|
||||
|
||||
// This is used to watch the blocked data bounce off CSP and allowed data
|
||||
// get sent out to the wire.
|
||||
function examiner() {
|
||||
SpecialPowers.addObserver(this, "csp-on-violate-policy", false);
|
||||
}
|
||||
examiner.prototype = {
|
||||
observe: function(subject, topic, data) {
|
||||
// subject should be an nsURI, and should be either allowed or blocked.
|
||||
if (!SpecialPowers.can_QI(subject))
|
||||
return;
|
||||
|
||||
if (topic === "csp-on-violate-policy") {
|
||||
var what = null;
|
||||
try {
|
||||
//these were blocked... record that they were blocked
|
||||
what = SpecialPowers.getPrivilegedProps(SpecialPowers.do_QueryInterface(subject, "nsIURI"), "asciiSpec");
|
||||
} catch(e) {
|
||||
//if that fails, the subject is probably a string
|
||||
what = SpecialPowers.getPrivilegedProps(SpecialPowers.do_QueryInterface(subject, "nsISupportsCString"), "data");
|
||||
}
|
||||
window.scriptBlocked(what, data);
|
||||
}
|
||||
},
|
||||
|
||||
// must eventually call this to remove the listener,
|
||||
// or mochitests might get borked.
|
||||
remove: function() {
|
||||
SpecialPowers.removeObserver(this, "csp-on-violate-policy");
|
||||
}
|
||||
}
|
||||
|
||||
// called when a script is blocked
|
||||
// -- we can't determine *which* frame was blocked, but at least we can count them
|
||||
var scriptBlocked = function(testname, data) {
|
||||
inlineScriptsBlocked++;
|
||||
ok(true, 'INLINE SCRIPT BLOCKED: ' + testname + '(' + data + ')');
|
||||
checkTestResults();
|
||||
}
|
||||
|
||||
// Check to see if all the tests have run
|
||||
var checkTestResults = function() {
|
||||
// if any test is incomplete, keep waiting
|
||||
if (inlineScriptsBlocked < inlineScriptsTotal)
|
||||
return;
|
||||
|
||||
// The other four scripts in the other two pages should be blocked.
|
||||
is(inlineScriptsBlocked, 4, "there should be 4 inline scripts that were blocked");
|
||||
|
||||
// ... otherwise, finish
|
||||
window.examiner.remove();
|
||||
SimpleTest.finish();
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// set up and go
|
||||
window.examiner = new examiner();
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
function clickit() {
|
||||
var cspframe = document.getElementById('cspframe');
|
||||
var a = cspframe.contentDocument.getElementById('anchortoclick');
|
||||
sendMouseEvent({type:'click'}, a, cspframe.contentWindow);
|
||||
}
|
||||
|
||||
SpecialPowers.pushPrefEnv(
|
||||
{'set':[["security.csp.speccompliant", true]]},
|
||||
function() {
|
||||
// save this for last so that our listeners are registered.
|
||||
// ... this loads the testbed of good and bad requests.
|
||||
document.getElementById('cspframe').src = 'file_CSP_inlinescript_main.html';
|
||||
document.getElementById('cspframe').addEventListener('load', clickit, false);
|
||||
});
|
||||
</script>
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
@ -1,65 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<title>Test for Content Security Policy inline stylesheets stuff</title>
|
||||
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
|
||||
</head>
|
||||
<body>
|
||||
<p id="display"></p>
|
||||
<div id="content" style="display: none">
|
||||
</div>
|
||||
|
||||
<iframe style="width:100%;height:300px;" id='cspframe'></iframe>
|
||||
<script class="testbody" type="text/javascript">
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// set up and go
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
var done = 0;
|
||||
|
||||
// Our original CSP implementation does not block inline styles.
|
||||
function checkStyles(evt) {
|
||||
var cspframe = document.getElementById('cspframe');
|
||||
var color;
|
||||
|
||||
// black means the style wasn't applied. green colors are used for styles
|
||||
//expected to be applied. A color is red if a style is erroneously applied
|
||||
color = window.getComputedStyle(cspframe.contentDocument.getElementById('linkstylediv'),null)['color'];
|
||||
ok('rgb(0, 255, 0)' === color, 'External Stylesheet (original CSP implementation) (' + color + ')');
|
||||
color = window.getComputedStyle(cspframe.contentDocument.getElementById('inlinestylediv'),null)['color'];
|
||||
ok('rgb(0, 255, 0)' === color, 'Inline Style TAG (original CSP implementation) (' + color + ')');
|
||||
color = window.getComputedStyle(cspframe.contentDocument.getElementById('attrstylediv'),null)['color'];
|
||||
ok('rgb(0, 255, 0)' === color, 'Style Attribute (original CSP implementation) (' + color + ')');
|
||||
// SMIL tests
|
||||
color = window.getComputedStyle(cspframe.contentDocument.getElementById('xmlTest',null))['fill'];
|
||||
ok('rgb(0, 255, 0)' === color, 'XML Attribute styling (SMIL) (' + color + ')');
|
||||
color = window.getComputedStyle(cspframe.contentDocument.getElementById('cssOverrideTest',null))['fill'];
|
||||
ok('rgb(0, 255, 0)' === color, 'CSS Override styling (SMIL) (' + color + ')');
|
||||
color = window.getComputedStyle(cspframe.contentDocument.getElementById('cssOverrideTestById',null))['fill'];
|
||||
ok('rgb(0, 255, 0)' === color, 'CSS Override styling via ID lookup (SMIL) (' + color + ')');
|
||||
color = window.getComputedStyle(cspframe.contentDocument.getElementById('cssSetTestById',null))['fill'];
|
||||
ok('rgb(0, 255, 0)' === color, 'CSS Set Element styling via ID lookup (SMIL) (' + color + ')');
|
||||
checkIfDone();
|
||||
}
|
||||
|
||||
function checkIfDone() {
|
||||
done++;
|
||||
if (done == 1)
|
||||
SimpleTest.finish();
|
||||
}
|
||||
|
||||
SpecialPowers.pushPrefEnv(
|
||||
{'set':[["security.csp.speccompliant", true]]},
|
||||
function() {
|
||||
// save this for last so that our listeners are registered.
|
||||
// ... this loads the testbed of good and bad requests.
|
||||
document.getElementById('cspframe').src = 'file_CSP_inlinestyle_main.html';
|
||||
document.getElementById('cspframe').addEventListener('load', checkStyles, false);
|
||||
}
|
||||
);
|
||||
</script>
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
@ -1,79 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<title>Test for Correctly Handling Both Pre-1.0 and 1.0 Content Security Policy Headers</title>
|
||||
<!-- When both headers are present, we should ignore the pre-1.0 header and
|
||||
only recognize the 1.0 spec-compliant header. -->
|
||||
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
|
||||
</head>
|
||||
<body>
|
||||
<p id="display"></p>
|
||||
<div id="content" style="display: none">
|
||||
</div>
|
||||
|
||||
<iframe style="width:200px;height:200px;" id='cspframe'></iframe>
|
||||
<script class="testbody" type="text/javascript">
|
||||
|
||||
var prefixedHeaderImgURL = "http://example.org/prefixed.jpg";
|
||||
var unprefixedHeaderImgURL = "http://mochi.test:8888/unprefixed.jpg";
|
||||
var testsRun = 0;
|
||||
var totalTests = 2;
|
||||
|
||||
// This is used to watch the blocked data bounce off CSP and allowed data
|
||||
// get sent out to the wire.
|
||||
function examiner() {
|
||||
SpecialPowers.addObserver(this, "csp-on-violate-policy", false);
|
||||
SpecialPowers.addObserver(this, "specialpowers-http-notify-request", false);
|
||||
}
|
||||
examiner.prototype = {
|
||||
observe: function(subject, topic, data) {
|
||||
if (topic === "specialpowers-http-notify-request") {
|
||||
var allowedUri = data;
|
||||
if (allowedUri == prefixedHeaderImgURL || allowedUri == unprefixedHeaderImgURL) {
|
||||
is(allowedUri, unprefixedHeaderImgURL, "Load was allowed - should be allowed by unprefixed header (blocked by prefixed)");
|
||||
testRan();
|
||||
}
|
||||
}
|
||||
|
||||
if (topic === "csp-on-violate-policy") {
|
||||
// the load was blocked, this is a pass, the Content-Security-Policy
|
||||
// header doesn't allow the load, but the X-Content-Security-Header does
|
||||
var asciiSpec = SpecialPowers.getPrivilegedProps(SpecialPowers.do_QueryInterface(subject, "nsIURI"), "asciiSpec");
|
||||
if (asciiSpec == prefixedHeaderImgURL || asciiSpec == unprefixedHeaderImgURL) {
|
||||
is(asciiSpec, prefixedHeaderImgURL, "Load was blocked - the Content-Security-Policy header doesn't allow the load, the X-Content-Security-Header does but should have been ignored");
|
||||
testRan();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// must eventually call this to remove the listener,
|
||||
// or mochitests might get borked.
|
||||
remove: function() {
|
||||
SpecialPowers.removeObserver(this, "csp-on-violate-policy");
|
||||
SpecialPowers.removeObserver(this, "specialpowers-http-notify-request");
|
||||
}
|
||||
}
|
||||
|
||||
window.examiner = new examiner();
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
function testRan() {
|
||||
testsRun++;
|
||||
if (testsRun == totalTests) {
|
||||
window.examiner.remove();
|
||||
SimpleTest.finish();
|
||||
}
|
||||
}
|
||||
|
||||
SpecialPowers.pushPrefEnv(
|
||||
{'set':[["security.csp.speccompliant", true]]},
|
||||
function loadTestRequests() {
|
||||
var cspframe = document.getElementById('cspframe');
|
||||
cspframe.src = 'file_bothCSPheaders.html';
|
||||
}
|
||||
);
|
||||
</script>
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
@ -1,223 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=768029
|
||||
-->
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Test for CSP on trusted/certified apps -- bug 768029</title>
|
||||
<script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
|
||||
</head>
|
||||
<body>
|
||||
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=768029">Mozilla Bug 768029</a>
|
||||
<p id="display"></p>
|
||||
<div id="content">
|
||||
|
||||
</div>
|
||||
<pre id="test">
|
||||
<script type="application/javascript;version=1.7">
|
||||
|
||||
Components.utils.import("resource://gre/modules/Services.jsm");
|
||||
|
||||
/** Test for Bug 768029 **/
|
||||
|
||||
// Note: we don't have to inspect all the different operations of CSP,
|
||||
// we're just looking for specific differences in behavior that indicate
|
||||
// a default CSP got applied.
|
||||
const DEFAULT_CSP_PRIV = "default-src *; script-src 'self'; style-src 'self' 'unsafe-inline'; object-src 'none'";
|
||||
const DEFAULT_CSP_CERT = "default-src *; script-src 'self'; style-src 'self'; object-src 'none'";
|
||||
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
var gData = [
|
||||
{
|
||||
app: "https://example.com/manifest.webapp",
|
||||
appStatus: Components.interfaces.nsIPrincipal.APP_STATUS_INSTALLED,
|
||||
origin: "https://example.com",
|
||||
uri: "https://example.com/tests/content/base/test/csp/file_csp_bug768029.html",
|
||||
statusString: "installed app",
|
||||
expectedTestResults: {
|
||||
max_tests: 7, /* number of bools below plus one for the status check */
|
||||
cross_origin: { img: true, script: true, style: true },
|
||||
same_origin: { img: true, script: true, style: true },
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
app: "https://example.com/manifest_priv.webapp",
|
||||
appStatus: Components.interfaces.nsIPrincipal.APP_STATUS_PRIVILEGED,
|
||||
origin: "https://example.com",
|
||||
uri: "https://example.com/tests/content/base/test/csp/file_csp_bug768029.html",
|
||||
statusString: "privileged app",
|
||||
expectedTestResults: {
|
||||
max_tests: 7, /* number of bools below plus one for the status check */
|
||||
cross_origin: { img: true, script: false, style: false },
|
||||
same_origin: { img: true, script: true, style: true },
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
app: "https://example.com/manifest_cert.webapp",
|
||||
appStatus: Components.interfaces.nsIPrincipal.APP_STATUS_CERTIFIED,
|
||||
origin: "https://example.com",
|
||||
uri: "https://example.com/tests/content/base/test/csp/file_csp_bug768029.html",
|
||||
statusString: "certified app",
|
||||
expectedTestResults: {
|
||||
max_tests: 7, /* number of bools below plus one for the status check */
|
||||
cross_origin: { img: true, script: false, style: false },
|
||||
same_origin: { img: true, script: true, style: true },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// Observer for watching allowed loads and blocked attempts
|
||||
function ThingyListener(app, iframe) {
|
||||
Services.obs.addObserver(this, "csp-on-violate-policy", false);
|
||||
Services.obs.addObserver(this, "http-on-modify-request", false);
|
||||
dump("added observers\n");
|
||||
// keep track of which app ID this test is monitoring.
|
||||
this._testData = app;
|
||||
this._expectedResults = app.expectedTestResults;
|
||||
this._resultsRecorded = { cross_origin: {}, same_origin: {}};
|
||||
this._iframe = iframe;
|
||||
this._countedTests = 0;
|
||||
}
|
||||
ThingyListener.prototype = {
|
||||
|
||||
observe: function(subject, topic, data) {
|
||||
// make sure to only observe app-generated calls to the helper for this test.
|
||||
var testpat = new RegExp("file_csp_bug768029\\.sjs");
|
||||
|
||||
// used to extract which kind of load this is (img, script, etc).
|
||||
var typepat = new RegExp("type=([\\_a-z0-9]+)");
|
||||
|
||||
// used to identify whether it's cross-origin or same-origin loads
|
||||
// (the applied CSP allows same-origin loads).
|
||||
var originpat = new RegExp("origin=([\\_a-z0-9]+)");
|
||||
|
||||
if (topic === "http-on-modify-request") {
|
||||
// Matching requests on this topic were allowed by the csp
|
||||
var chan = subject.QueryInterface(Components.interfaces.nsIHttpChannel);
|
||||
var uri = chan.URI;
|
||||
// ignore irrelevent URIs
|
||||
if (!testpat.test(uri.asciiSpec)) return;
|
||||
|
||||
var loadType = typepat.exec(uri.asciiSpec)[1];
|
||||
var originType = originpat.exec(uri.asciiSpec)[1];
|
||||
|
||||
// skip duplicate hits to this topic (potentially document loads
|
||||
// may generate duplicate loads.
|
||||
if (this._resultsRecorded[originType] &&
|
||||
this._resultsRecorded[originType][loadType]) {
|
||||
return;
|
||||
}
|
||||
var message = originType + " : " + loadType + " should be " +
|
||||
(this._expectedResults[originType][loadType] ? "allowed" : "blocked");
|
||||
ok(this._expectedResults[originType][loadType] == true, message);
|
||||
this._resultsRecorded[originType][loadType] = true;
|
||||
this._countedTests++;
|
||||
}
|
||||
else if (topic === "csp-on-violate-policy") {
|
||||
// Matching hits on this topic were blocked by the csp
|
||||
var uri = subject.QueryInterface(Components.interfaces.nsIURI);
|
||||
// ignore irrelevent URIs
|
||||
if (!testpat.test(uri.asciiSpec)) return;
|
||||
|
||||
var loadType = typepat.exec(uri.asciiSpec)[1];
|
||||
var originType = originpat.exec(uri.asciiSpec)[1];
|
||||
|
||||
// skip duplicate hits to this topic (potentially document loads
|
||||
// may generate duplicate loads.
|
||||
if (this._resultsRecorded[originType] &&
|
||||
this._resultsRecorded[originType][loadType]) {
|
||||
return;
|
||||
}
|
||||
|
||||
var message = originType + " : " + loadType + " should be " +
|
||||
(this._expectedResults[originType][loadType] ? "allowed" : "blocked");
|
||||
ok(this._expectedResults[originType][loadType] == false, message);
|
||||
this._resultsRecorded[originType][loadType] = true;
|
||||
this._countedTests++;
|
||||
}
|
||||
else {
|
||||
// wrong topic! Nothing to do.
|
||||
return;
|
||||
}
|
||||
|
||||
this._checkForFinish();
|
||||
},
|
||||
|
||||
_checkForFinish: function() {
|
||||
// check to see if there are load tests still pending.
|
||||
// (All requests triggered by the app should hit one of the
|
||||
// two observer topics.)
|
||||
if (this._countedTests == this._expectedResults.max_tests) {
|
||||
Services.obs.removeObserver(this, "csp-on-violate-policy");
|
||||
Services.obs.removeObserver(this, "http-on-modify-request");
|
||||
dump("removed observers\n");
|
||||
checkedCount++;
|
||||
if (checkedCount == checksTodo) {
|
||||
SpecialPowers.removePermission("browser", "https://example.com");
|
||||
SimpleTest.finish();
|
||||
} else {
|
||||
gTestRunner.next();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// verify the status of the app
|
||||
checkAppStatus: function() {
|
||||
var principal = this._iframe.contentDocument.nodePrincipal;
|
||||
if (this._testData.app) {
|
||||
is(principal.appStatus, this._testData.appStatus,
|
||||
"iframe principal's app status doesn't match the expected app status.");
|
||||
this._countedTests++;
|
||||
this._checkForFinish();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var content = document.getElementById('content');
|
||||
var checkedCount = 0; // number of apps checked
|
||||
var checksTodo = gData.length;
|
||||
|
||||
// quick check to make sure we can test apps:
|
||||
is('appStatus' in document.nodePrincipal, true,
|
||||
'appStatus should be present in nsIPrincipal, if not the rest of this test will fail');
|
||||
|
||||
function runTest() {
|
||||
for (var i = 0; i < gData.length; i++) {
|
||||
let data = gData[i];
|
||||
var iframe = document.createElement('iframe');
|
||||
|
||||
// watch for successes and failures
|
||||
var examiner = new ThingyListener(data, iframe);
|
||||
|
||||
iframe.setAttribute('mozapp', data.app);
|
||||
iframe.setAttribute('mozbrowser', 'true');
|
||||
iframe.addEventListener('load', examiner.checkAppStatus.bind(examiner));
|
||||
iframe.src = data.uri;
|
||||
|
||||
content.appendChild(iframe);
|
||||
|
||||
yield undefined;
|
||||
}
|
||||
}
|
||||
|
||||
var gTestRunner = runTest();
|
||||
|
||||
// load the default CSP and pref it on
|
||||
SpecialPowers.addPermission("browser", true, "https://example.com");
|
||||
SpecialPowers.pushPrefEnv({'set': [["dom.mozBrowserFramesEnabled", true],
|
||||
["security.apps.privileged.CSP.default", DEFAULT_CSP_PRIV],
|
||||
["security.apps.certified.CSP.default", DEFAULT_CSP_CERT],
|
||||
["security.mixed_content.block_active_content", false],
|
||||
["security.mixed_content.block_display_content", false]]},
|
||||
function() { gTestRunner.next(); });
|
||||
|
||||
|
||||
</script>
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
@ -1,228 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=768029
|
||||
-->
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Test for CSP on trusted/certified and installed apps -- bug 773891</title>
|
||||
<script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
|
||||
</head>
|
||||
<body>
|
||||
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=773891">Mozilla Bug 773891</a>
|
||||
<p id="display"></p>
|
||||
<div id="content">
|
||||
|
||||
</div>
|
||||
<pre id="test">
|
||||
<script type="application/javascript;version=1.7">
|
||||
|
||||
Components.utils.import("resource://gre/modules/Services.jsm");
|
||||
|
||||
/** Test for Bug 773891 **/
|
||||
|
||||
// Note: we don't have to inspect all the different operations of CSP,
|
||||
// we're just looking for specific differences in behavior that indicate
|
||||
// a default CSP got applied.
|
||||
const DEFAULT_CSP_PRIV = "default-src *; script-src *; style-src 'self' 'unsafe-inline'; object-src 'none'";
|
||||
const DEFAULT_CSP_CERT = "default-src *; script-src *; style-src 'self'; object-src 'none'";
|
||||
|
||||
const MANIFEST_CSP_PRIV = "default-src *; script-src 'self'; object-src 'none'; style-src 'self' 'unsafe-inline'";
|
||||
const MANIFEST_CSP_INST = "default-src *; script-src 'self'; object-src 'none'; style-src 'self' 'unsafe-inline'";
|
||||
const MANIFEST_CSP_CERT = "default-src *; script-src 'self'; object-src 'none'; style-src 'self' 'unsafe-inline'";
|
||||
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
var gData = [
|
||||
|
||||
{
|
||||
app: "https://example.com/manifest_csp_inst.webapp",
|
||||
appStatus: Components.interfaces.nsIPrincipal.APP_STATUS_INSTALLED,
|
||||
csp: MANIFEST_CSP_INST,
|
||||
origin: "https://example.com",
|
||||
uri: "https://example.com/tests/content/base/test/csp/file_csp_bug773891.html",
|
||||
statusString: "installed app",
|
||||
expectedTestResults: {
|
||||
max_tests: 7, /* number of bools below plus one for the status check */
|
||||
cross_origin: { img: true, script: false, style: false },
|
||||
same_origin: { img: true, script: true, style: true },
|
||||
},
|
||||
},
|
||||
{
|
||||
app: "https://example.com/manifest_csp_cert.webapp",
|
||||
appStatus: Components.interfaces.nsIPrincipal.APP_STATUS_CERTIFIED,
|
||||
csp: MANIFEST_CSP_CERT,
|
||||
origin: "https://example.com",
|
||||
uri: "https://example.com/tests/content/base/test/csp/file_csp_bug773891.html",
|
||||
statusString: "certified app",
|
||||
expectedTestResults: {
|
||||
max_tests: 7, /* number of bools below plus one for the status check */
|
||||
cross_origin: { img: true, script: false, style: false },
|
||||
same_origin: { img: true, script: true, style: true },
|
||||
},
|
||||
},
|
||||
{
|
||||
app: "https://example.com/manifest_csp_priv.webapp",
|
||||
appStatus: Components.interfaces.nsIPrincipal.APP_STATUS_PRIVILEGED,
|
||||
csp: MANIFEST_CSP_PRIV,
|
||||
origin: "https://example.com",
|
||||
uri: "https://example.com/tests/content/base/test/csp/file_csp_bug773891.html",
|
||||
statusString: "privileged app",
|
||||
expectedTestResults: {
|
||||
max_tests: 7, /* number of bools below plus one for the status check */
|
||||
cross_origin: { img: true, script: false, style: false },
|
||||
same_origin: { img: true, script: true, style: true },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// Observer for watching allowed loads and blocked attempts
|
||||
function ThingyListener(app, iframe) {
|
||||
Services.obs.addObserver(this, "csp-on-violate-policy", false);
|
||||
Services.obs.addObserver(this, "http-on-modify-request", false);
|
||||
dump("added observers\n");
|
||||
// keep track of which app ID this test is monitoring.
|
||||
this._testData = app;
|
||||
this._expectedResults = app.expectedTestResults;
|
||||
this._resultsRecorded = { cross_origin: {}, same_origin: {}};
|
||||
this._iframe = iframe;
|
||||
this._countedTests = 0;
|
||||
}
|
||||
ThingyListener.prototype = {
|
||||
|
||||
observe: function(subject, topic, data) {
|
||||
// make sure to only observe app-generated calls to the helper for this test.
|
||||
var testpat = new RegExp("file_csp_bug773891\\.sjs");
|
||||
|
||||
// used to extract which kind of load this is (img, script, etc).
|
||||
var typepat = new RegExp("type=([\\_a-z0-9]+)");
|
||||
|
||||
// used to identify whether it's cross-origin or same-origin loads
|
||||
// (the applied CSP allows same-origin loads).
|
||||
var originpat = new RegExp("origin=([\\_a-z0-9]+)");
|
||||
|
||||
if (topic === "http-on-modify-request") {
|
||||
// Matching requests on this topic were allowed by the csp
|
||||
var chan = subject.QueryInterface(Components.interfaces.nsIHttpChannel);
|
||||
var uri = chan.URI;
|
||||
// ignore irrelevent URIs
|
||||
if (!testpat.test(uri.asciiSpec)) return;
|
||||
|
||||
var loadType = typepat.exec(uri.asciiSpec)[1];
|
||||
var originType = originpat.exec(uri.asciiSpec)[1];
|
||||
|
||||
// skip duplicate hits to this topic (potentially document loads
|
||||
// may generate duplicate loads.
|
||||
if (this._resultsRecorded[originType] &&
|
||||
this._resultsRecorded[originType][loadType]) {
|
||||
return;
|
||||
}
|
||||
var message = originType + " : " + loadType + " should be " +
|
||||
(this._expectedResults[originType][loadType] ? "allowed" : "blocked");
|
||||
ok(this._expectedResults[originType][loadType] == true, message);
|
||||
this._resultsRecorded[originType][loadType] = true;
|
||||
this._countedTests++;
|
||||
}
|
||||
else if (topic === "csp-on-violate-policy") {
|
||||
// Matching hits on this topic were blocked by the csp
|
||||
var uri = subject.QueryInterface(Components.interfaces.nsIURI);
|
||||
// ignore irrelevent URIs
|
||||
if (!testpat.test(uri.asciiSpec)) return;
|
||||
|
||||
var loadType = typepat.exec(uri.asciiSpec)[1];
|
||||
var originType = originpat.exec(uri.asciiSpec)[1];
|
||||
|
||||
// skip duplicate hits to this topic (potentially document loads
|
||||
// may generate duplicate loads.
|
||||
if (this._resultsRecorded[originType] &&
|
||||
this._resultsRecorded[originType][loadType]) {
|
||||
return;
|
||||
}
|
||||
|
||||
var message = originType + " : " + loadType + " should be " +
|
||||
(this._expectedResults[originType][loadType] ? "allowed" : "blocked");
|
||||
ok(this._expectedResults[originType][loadType] == false, message);
|
||||
this._resultsRecorded[originType][loadType] = true;
|
||||
this._countedTests++;
|
||||
}
|
||||
else {
|
||||
// wrong topic! Nothing to do.
|
||||
return;
|
||||
}
|
||||
|
||||
this._checkForFinish();
|
||||
},
|
||||
|
||||
_checkForFinish: function() {
|
||||
// check to see if there are load tests still pending.
|
||||
// (All requests triggered by the app should hit one of the
|
||||
// two observer topics.)
|
||||
if (this._countedTests == this._expectedResults.max_tests) {
|
||||
Services.obs.removeObserver(this, "csp-on-violate-policy");
|
||||
Services.obs.removeObserver(this, "http-on-modify-request");
|
||||
dump("removed observers\n");
|
||||
checkedCount++;
|
||||
if (checkedCount == checksTodo) {
|
||||
SpecialPowers.removePermission("browser", "https://example.com");
|
||||
SimpleTest.finish();
|
||||
} else {
|
||||
gTestRunner.next();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// verify the status of the app
|
||||
checkAppStatus: function() {
|
||||
var principal = this._iframe.contentDocument.nodePrincipal;
|
||||
if (this._testData.app) {
|
||||
is(principal.appStatus, this._testData.appStatus,
|
||||
"iframe principal's app status doesn't match the expected app status.");
|
||||
this._countedTests++;
|
||||
this._checkForFinish();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var content = document.getElementById('content');
|
||||
var checkedCount = 0; // number of apps checked
|
||||
var checksTodo = gData.length;
|
||||
|
||||
// quick check to make sure we can test apps:
|
||||
is('appStatus' in document.nodePrincipal, true,
|
||||
'appStatus should be present in nsIPrincipal, if not the rest of this test will fail');
|
||||
|
||||
function runTest() {
|
||||
for (var i = 0; i < gData.length; i++) {
|
||||
let data = gData[i];
|
||||
var iframe = document.createElement('iframe');
|
||||
|
||||
// watch for successes and failures
|
||||
var examiner = new ThingyListener(data, iframe);
|
||||
|
||||
iframe.setAttribute('mozapp', data.app);
|
||||
iframe.setAttribute('mozbrowser', 'true');
|
||||
iframe.addEventListener('load', examiner.checkAppStatus.bind(examiner));
|
||||
iframe.src = data.uri;
|
||||
|
||||
content.appendChild(iframe);
|
||||
|
||||
yield undefined;
|
||||
}
|
||||
}
|
||||
|
||||
var gTestRunner = runTest();
|
||||
|
||||
// load the default CSP and pref it on
|
||||
SpecialPowers.addPermission("browser", true, "https://example.com");
|
||||
|
||||
SpecialPowers.pushPrefEnv({'set': [["dom.mozBrowserFramesEnabled", true],
|
||||
["security.apps.privileged.CSP.default", DEFAULT_CSP_PRIV],
|
||||
["security.apps.certified.CSP.default", DEFAULT_CSP_CERT]]},
|
||||
function() { gTestRunner.next(); });
|
||||
|
||||
|
||||
</script>
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
@ -1,130 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<title>Tests for Content Security Policy during redirects</title>
|
||||
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
|
||||
</head>
|
||||
<body>
|
||||
<p id="display"></p>
|
||||
<div id="content" style="display: none">
|
||||
|
||||
</div>
|
||||
|
||||
<iframe style="width:100%;height:300px;" id="harness"></iframe>
|
||||
<pre id="log"></pre>
|
||||
<script class="testbody" type="text/javascript">
|
||||
|
||||
var path = "/tests/content/base/test/csp/";
|
||||
|
||||
// debugging
|
||||
function log(s) {
|
||||
return;
|
||||
dump("**" + s + "\n");
|
||||
var log = document.getElementById("log");
|
||||
log.textContent = log.textContent+s+"\n";
|
||||
}
|
||||
|
||||
// used to watch if requests are blocked by CSP or allowed through
|
||||
function examiner() {
|
||||
SpecialPowers.addObserver(this, "csp-on-violate-policy", false);
|
||||
SpecialPowers.addObserver(this, "specialpowers-http-notify-request", false);
|
||||
}
|
||||
examiner.prototype = {
|
||||
observe: function(subject, topic, data) {
|
||||
var testpat = new RegExp("testid=([a-z0-9-]+)");
|
||||
var asciiSpec;
|
||||
var testid;
|
||||
|
||||
if (topic === "specialpowers-http-notify-request") {
|
||||
// request was sent
|
||||
var allowedUri = data;
|
||||
if (!testpat.test(allowedUri)) return;
|
||||
testid = testpat.exec(allowedUri)[1];
|
||||
if (testExpectedResults[testid] == "completed") return;
|
||||
log("allowed: "+allowedUri);
|
||||
window.testResult(testid, allowedUri, true);
|
||||
}
|
||||
|
||||
else if (topic === "csp-on-violate-policy") {
|
||||
// request was blocked
|
||||
asciiSpec = SpecialPowers.getPrivilegedProps(SpecialPowers.do_QueryInterface(subject, "nsIURI"), "asciiSpec");
|
||||
if (!testpat.test(asciiSpec)) return;
|
||||
testid = testpat.exec(asciiSpec)[1];
|
||||
// had to add this check because http-on-modify-request can fire after
|
||||
// csp-on-violate-policy, apparently, even though the request does
|
||||
// not hit the wire.
|
||||
if (testExpectedResults[testid] == "completed") return;
|
||||
log("BLOCKED: "+asciiSpec);
|
||||
window.testResult(testid, asciiSpec, false);
|
||||
}
|
||||
},
|
||||
|
||||
remove: function() {
|
||||
SpecialPowers.removeObserver(this, "csp-on-violate-policy");
|
||||
SpecialPowers.removeObserver(this, "specialpowers-http-notify-request");
|
||||
}
|
||||
}
|
||||
window.examiner = new examiner();
|
||||
|
||||
// contains { test_frame_id : expected_result }
|
||||
var testExpectedResults = { "font-src": true,
|
||||
"font-src-redir": false,
|
||||
"frame-src": true,
|
||||
"frame-src-redir": false,
|
||||
"img-src": true,
|
||||
"img-src-redir": false,
|
||||
"media-src": true,
|
||||
"media-src-redir": false,
|
||||
"object-src": true,
|
||||
"object-src-redir": false,
|
||||
"script-src": true,
|
||||
"script-src-redir": false,
|
||||
"style-src": true,
|
||||
"style-src-redir": false,
|
||||
"worker": true,
|
||||
"worker-redir": false,
|
||||
"xhr-src": true,
|
||||
"xhr-src-redir": false,
|
||||
};
|
||||
|
||||
// takes the name of the test, the URL that was tested, and whether the
|
||||
// load occurred
|
||||
var testResult = function(testName, url, result) {
|
||||
log(" testName: "+testName+", result: "+result+", expected: "+testExpectedResults[testName]+"\n");
|
||||
is(result, testExpectedResults[testName], testName+" test: "+url);
|
||||
|
||||
// mark test as completed
|
||||
testExpectedResults[testName] = "completed";
|
||||
|
||||
// don't finish until we've run all the tests
|
||||
for (var t in testExpectedResults) {
|
||||
if (testExpectedResults[t] != "completed") {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
window.examiner.remove();
|
||||
SimpleTest.finish();
|
||||
}
|
||||
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
SpecialPowers.pushPrefEnv(
|
||||
{'set':[["security.csp.speccompliant", true],
|
||||
// This defaults to 0 ("preload none") on mobile (B2G/Android), which
|
||||
// blocks loading the resource until the user interacts with a
|
||||
// corresponding widget, which breaks the media_* tests. We set it
|
||||
// back to the default used by desktop Firefox to get consistent
|
||||
// behavior.
|
||||
["media.preload.default", 2]]},
|
||||
function() {
|
||||
// save this for last so that our listeners are registered.
|
||||
// ... this loads the testbed of good and bad requests.
|
||||
document.getElementById("harness").src = "file_csp_redirects_main.html";
|
||||
});
|
||||
</script>
|
||||
</pre>
|
||||
|
||||
</body>
|
||||
</html>
|
@ -1,108 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=548193
|
||||
-->
|
||||
<head>
|
||||
<title>Test for Bug 548193</title>
|
||||
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
|
||||
</head>
|
||||
<body>
|
||||
<p id="display"></p>
|
||||
<div id="content" style="display: none">
|
||||
</div>
|
||||
|
||||
<iframe style="width:200px;height:200px;" id='cspframe'></iframe>
|
||||
<script class="testbody" type="text/javascript">
|
||||
// This is used to watch requests go out so we can see if the report is
|
||||
// sent correctly
|
||||
function examiner() {
|
||||
SpecialPowers.addObserver(this, "http-on-opening-request", false);
|
||||
}
|
||||
examiner.prototype = {
|
||||
observe: function(subject, topic, data) {
|
||||
// subject should be an nsURI
|
||||
if (!SpecialPowers.can_QI(subject))
|
||||
return;
|
||||
|
||||
const reportURI = "http://mochi.test:8888/csp-report.cgi";
|
||||
|
||||
if (topic === "http-on-opening-request") {
|
||||
var asciiSpec = SpecialPowers.getPrivilegedProps(SpecialPowers.do_QueryInterface(subject, "nsIHttpChannel"), "URI.asciiSpec");
|
||||
if (asciiSpec !== reportURI) return;
|
||||
|
||||
// Verify that the report was properly formatted.
|
||||
// We'll parse the report text as JSON and verify that the properties
|
||||
// have expected values.
|
||||
var reportText = "{}";
|
||||
try {
|
||||
var uploadStream = SpecialPowers.wrap(SpecialPowers.do_QueryInterface(subject, "nsIUploadChannel")).uploadStream;
|
||||
|
||||
if (uploadStream) {
|
||||
// get the bytes from the request body
|
||||
var binstream = SpecialPowers.Cc["@mozilla.org/binaryinputstream;1"]
|
||||
.createInstance(SpecialPowers.Ci.nsIBinaryInputStream);
|
||||
binstream.setInputStream(uploadStream);
|
||||
|
||||
var segments = [];
|
||||
for (var count = uploadStream.available(); count; count = uploadStream.available()) {
|
||||
var data = binstream.readBytes(count);
|
||||
segments.push(data);
|
||||
}
|
||||
|
||||
var reportText = segments.join("");
|
||||
// rewind stream as we are supposed to - there will be an assertion later if we don't.
|
||||
SpecialPowers.do_QueryInterface(uploadStream, "nsISeekableStream").seek(SpecialPowers.Ci.nsISeekableStream.NS_SEEK_SET, 0);
|
||||
}
|
||||
}
|
||||
catch(e) {}
|
||||
|
||||
var reportObj = JSON.parse(reportText);
|
||||
|
||||
// test for the proper values in the report object
|
||||
window.checkResults(reportObj);
|
||||
|
||||
// finish up
|
||||
window.examiner.remove();
|
||||
SimpleTest.finish();
|
||||
}
|
||||
},
|
||||
|
||||
// remove the listener
|
||||
remove: function() {
|
||||
SpecialPowers.removeObserver(this, "http-on-opening-request");
|
||||
}
|
||||
}
|
||||
|
||||
// content file that triggers a violation report
|
||||
var testFile = "file_csp_report.sjs";
|
||||
|
||||
window.checkResults = function(reportObj) {
|
||||
var cspReport = reportObj["csp-report"];
|
||||
// correct violating request
|
||||
is(cspReport["document-uri"],
|
||||
"http://mochi.test:8888/tests/content/base/test/xcsp/" + testFile,
|
||||
"Incorrect violating request");
|
||||
// correct blocked-uri
|
||||
is(cspReport["blocked-uri"],
|
||||
"http://example.org/tests/content/base/test/file_CSP.sjs?testid=img_bad&type=img/png",
|
||||
"Incorrect blocked uri");
|
||||
// correct violated-directive
|
||||
is(cspReport["violated-directive"], "default-src http://mochi.test:8888",
|
||||
"Incorrect violated directive");
|
||||
// not practical to test request-headers as header names and values will
|
||||
// change with the trunk
|
||||
}
|
||||
|
||||
window.examiner = new examiner();
|
||||
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
// load the resource which will generate a CSP violation report
|
||||
document.getElementById("cspframe").src = testFile;
|
||||
|
||||
</script>
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
@ -1,59 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=918397
|
||||
-->
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Test for Bug 918397</title>
|
||||
<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
|
||||
</head>
|
||||
<body>
|
||||
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=918397">Mozilla Bug 918397</a>
|
||||
<p id="display"></p>
|
||||
|
||||
<iframe id="cspframe"></iframe>
|
||||
|
||||
<pre id="test">
|
||||
<script class="testbody" type="text/javascript">
|
||||
// Load locale strings during mochitest
|
||||
var stringBundleService = SpecialPowers.Cc["@mozilla.org/intl/stringbundle;1"]
|
||||
.getService(SpecialPowers.Ci.nsIStringBundleService);
|
||||
var localizer = stringBundleService.createBundle("chrome://global/locale/security/security.properties");
|
||||
var depreHeadersMsg = localizer.GetStringFromName("OldCSPHeaderDeprecated", 0)
|
||||
var dualHeadersMsg = localizer.GetStringFromName("BothCSPHeadersPresent", 0)
|
||||
|
||||
function cleanup() {
|
||||
SpecialPowers.postConsoleSentinel();
|
||||
SimpleTest.finish();
|
||||
}
|
||||
|
||||
// listen on the console before loading the iframe
|
||||
SpecialPowers.registerConsoleListener(function ConsoleMsgListener(aMsg) {
|
||||
// Note: We do not want to see the deprecation warning appear in the console.
|
||||
// This test can only be sure that the deprecation warning does not appear
|
||||
// iff the deprecation warning appears before the dual header warning appears
|
||||
// in the console.
|
||||
if (aMsg.message.indexOf(depreHeadersMsg) > -1) {
|
||||
ok(false, "Deprecated CSP header warning should not be present.");
|
||||
return;
|
||||
} else if (aMsg.message.indexOf(dualHeadersMsg) > -1) {
|
||||
ok(true, "Dual CSP header warning present.");
|
||||
SimpleTest.executeSoon(cleanup);
|
||||
} else {
|
||||
// if some other console message is present, we wait
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
// get ready and test
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
SpecialPowers.pushPrefEnv(
|
||||
{'set': [["security.csp.speccompliant", true]]},
|
||||
function() {
|
||||
document.getElementById('cspframe').src = 'file_dual_headers_warning.html';
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
@ -1,121 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=717511
|
||||
-->
|
||||
<head>
|
||||
<title>Test for Bug 717511</title>
|
||||
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
|
||||
</head>
|
||||
<body>
|
||||
<p id="display"></p>
|
||||
<div id="content" style="display: none">
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
<iframe style="width:200px;height:200px;" id='cspframe'></iframe>
|
||||
<iframe style="width:200px;height:200px;" id='cspframe2'></iframe>
|
||||
<script class="testbody" type="text/javascript">
|
||||
|
||||
var path = "/tests/content/base/test/";
|
||||
|
||||
// These are test results: -1 means it hasn't run,
|
||||
// true/false is the pass/fail result.
|
||||
// This is not exhaustive, just double-checking the 'self' vs * policy conflict in the two HTTP headers.
|
||||
window.tests = {
|
||||
img_good: -1,
|
||||
img_bad: -1,
|
||||
script_good: -1,
|
||||
script_bad: -1,
|
||||
img2_good: -1,
|
||||
img2_bad: -1,
|
||||
script2_good: -1,
|
||||
script2_bad: -1,
|
||||
};
|
||||
|
||||
|
||||
// This is used to watch the blocked data bounce off CSP and allowed data
|
||||
// get sent out to the wire.
|
||||
function examiner() {
|
||||
SpecialPowers.addObserver(this, "csp-on-violate-policy", false);
|
||||
SpecialPowers.addObserver(this, "specialpowers-http-notify-request", false);
|
||||
}
|
||||
examiner.prototype = {
|
||||
observe: function(subject, topic, data) {
|
||||
var testpat = new RegExp("testid=([a-z0-9_]+)");
|
||||
|
||||
//_good things better be allowed!
|
||||
//_bad things better be stopped!
|
||||
|
||||
if (topic === "specialpowers-http-notify-request") {
|
||||
//these things were allowed by CSP
|
||||
var asciiSpec = data;
|
||||
if (!testpat.test(asciiSpec)) return;
|
||||
var testid = testpat.exec(asciiSpec)[1];
|
||||
window.testResult(testid,
|
||||
/_good/.test(testid),
|
||||
asciiSpec + " allowed by csp");
|
||||
|
||||
}
|
||||
|
||||
if(topic === "csp-on-violate-policy") {
|
||||
// subject should be an nsIURI for csp-on-violate-policy
|
||||
if (!SpecialPowers.can_QI(subject)) {
|
||||
return;
|
||||
}
|
||||
|
||||
//these were blocked... record that they were blocked
|
||||
var asciiSpec = SpecialPowers.getPrivilegedProps(
|
||||
SpecialPowers.do_QueryInterface(subject, "nsIURI"),
|
||||
"asciiSpec");
|
||||
if (!testpat.test(asciiSpec)) return;
|
||||
var testid = testpat.exec(asciiSpec)[1];
|
||||
window.testResult(testid,
|
||||
/_bad/.test(testid),
|
||||
asciiSpec + " blocked by \"" + data + "\"");
|
||||
}
|
||||
},
|
||||
|
||||
// must eventually call this to remove the listener,
|
||||
// or mochitests might get borked.
|
||||
remove: function() {
|
||||
SpecialPowers.removeObserver(this, "csp-on-violate-policy");
|
||||
SpecialPowers.removeObserver(this, "specialpowers-http-notify-request");
|
||||
}
|
||||
}
|
||||
|
||||
window.examiner = new examiner();
|
||||
|
||||
window.testResult = function(testname, result, msg) {
|
||||
|
||||
//test already complete.... forget it... remember the first result.
|
||||
if (window.tests[testname] != -1)
|
||||
return;
|
||||
|
||||
window.tests[testname] = result;
|
||||
is(result, true, testname + ' test: ' + msg);
|
||||
|
||||
// if any test is incomplete, keep waiting
|
||||
for (var v in window.tests)
|
||||
if(tests[v] == -1)
|
||||
return;
|
||||
|
||||
// ... otherwise, finish
|
||||
window.examiner.remove();
|
||||
SimpleTest.finish();
|
||||
}
|
||||
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
|
||||
// save this for last so that our listeners are registered.
|
||||
// ... this loads the testbed of good and bad requests.
|
||||
|
||||
document.getElementById('cspframe').src = 'file_multi_policy_injection_bypass.html';
|
||||
document.getElementById('cspframe2').src = 'file_multi_policy_injection_bypass_2.html';
|
||||
|
||||
</script>
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
@ -1,34 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=558431
|
||||
-->
|
||||
<head>
|
||||
<title>Test for Bug 558431</title>
|
||||
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
|
||||
</head>
|
||||
<body>
|
||||
<iframe id="cspframe"></iframe>
|
||||
<script type="text/javascript">
|
||||
// This tests that a policy is still attempted to be fetched
|
||||
// asynchronously (bug 558431) and that a default policy of
|
||||
// |allow 'none'| is applied when the fetching fails.
|
||||
|
||||
var f = document.getElementById("cspframe");
|
||||
// run our test functions when the inner frame is finished loading
|
||||
f.addEventListener('load', function() {
|
||||
var inner = this.contentDocument.getElementById("inner");
|
||||
var test = inner.contentDocument.getElementById("test");
|
||||
// the inner document should not exist because it has an invalid
|
||||
// policy-uri and should have been blocked by the default
|
||||
// |allow 'none'| policy that was applied
|
||||
is(test, null, "test inner document");
|
||||
SimpleTest.finish();
|
||||
}, false);
|
||||
// load the test frame
|
||||
f.src = "file_policyuri_async_fetch.html";
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
@ -1,32 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<!--
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=702439
|
||||
|
||||
This test verifies that child iframes of CSP documents are
|
||||
permitted to execute javascript: URLs assuming the policy
|
||||
allows this.
|
||||
-->
|
||||
<head>
|
||||
<title>Test for Bug 702439</title>
|
||||
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
|
||||
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
|
||||
</head>
|
||||
<body>
|
||||
<script class="testbody" type="text/javascript">
|
||||
var javascript_link_ran = false;
|
||||
|
||||
// check that the script in the child frame's javascript: URL ran
|
||||
function checkResult()
|
||||
{
|
||||
is(javascript_link_ran, true,
|
||||
"javascript URL didn't execute");
|
||||
|
||||
SimpleTest.finish();
|
||||
}
|
||||
|
||||
SimpleTest.waitForExplicitFinish();
|
||||
</script>
|
||||
<iframe id="i" src="file_subframe_run_js_if_allowed.html"></iframe>
|
||||
</body>
|
||||
</html>
|
@ -1576,6 +1576,13 @@ nsHTMLDocument::Open(JSContext* cx,
|
||||
#ifdef DEBUG
|
||||
bool willReparent = mWillReparent;
|
||||
mWillReparent = true;
|
||||
|
||||
nsDocument* templateContentsOwner =
|
||||
static_cast<nsDocument*>(mTemplateContentsOwner.get());
|
||||
|
||||
if (templateContentsOwner) {
|
||||
templateContentsOwner->mWillReparent = true;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Should this pass true for aForceReuseInnerWindow?
|
||||
@ -1585,6 +1592,10 @@ nsHTMLDocument::Open(JSContext* cx,
|
||||
}
|
||||
|
||||
#ifdef DEBUG
|
||||
if (templateContentsOwner) {
|
||||
templateContentsOwner->mWillReparent = willReparent;
|
||||
}
|
||||
|
||||
mWillReparent = willReparent;
|
||||
#endif
|
||||
|
||||
@ -1601,6 +1612,20 @@ nsHTMLDocument::Open(JSContext* cx,
|
||||
if (rv.Failed()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Also reparent the template contents owner document
|
||||
// because its global is set to the same as this document.
|
||||
if (mTemplateContentsOwner) {
|
||||
JS::Rooted<JSObject*> contentsOwnerWrapper(cx,
|
||||
mTemplateContentsOwner->GetWrapper());
|
||||
if (contentsOwnerWrapper) {
|
||||
rv = mozilla::dom::ReparentWrapper(cx, contentsOwnerWrapper);
|
||||
if (rv.Failed()) {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
nsIXPConnect *xpc = nsContentUtils::XPConnect();
|
||||
rv = xpc->RescueOrphansInScope(cx, oldScope->GetGlobalJSObject());
|
||||
if (rv.Failed()) {
|
||||
|
407
content/media/AudioSink.cpp
Normal file
407
content/media/AudioSink.cpp
Normal file
@ -0,0 +1,407 @@
|
||||
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
|
||||
/* vim:set ts=2 sw=2 sts=2 et cindent: */
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
#include "AudioSink.h"
|
||||
#include "MediaDecoderStateMachine.h"
|
||||
#include "AudioStream.h"
|
||||
#include "prenv.h"
|
||||
|
||||
namespace mozilla {
|
||||
|
||||
#ifdef PR_LOGGING
|
||||
extern PRLogModuleInfo* gMediaDecoderLog;
|
||||
#define SINK_LOG(msg, ...) \
|
||||
PR_LOG(gMediaDecoderLog, PR_LOG_DEBUG, ("AudioSink=%p " msg, this, ##__VA_ARGS__))
|
||||
#define SINK_LOG_V(msg, ...) \
|
||||
PR_BEGIN_MACRO \
|
||||
if (!PR_GetEnv("MOZ_QUIET")) { \
|
||||
SINK_LOG(msg, ##__VA_ARGS__); \
|
||||
} \
|
||||
PR_END_MACRO
|
||||
#else
|
||||
#define SINK_LOG(msg, ...)
|
||||
#define SINK_LOG_V(msg, ...)
|
||||
#endif
|
||||
|
||||
AudioSink::AudioSink(MediaDecoderStateMachine* aStateMachine,
|
||||
int64_t aStartTime, AudioInfo aInfo, dom::AudioChannel aChannel)
|
||||
: mStateMachine(aStateMachine)
|
||||
, mStartTime(aStartTime)
|
||||
, mWritten(0)
|
||||
, mInfo(aInfo)
|
||||
, mChannel(aChannel)
|
||||
, mVolume(1.0)
|
||||
, mPlaybackRate(1.0)
|
||||
, mPreservesPitch(false)
|
||||
, mStopAudioThread(false)
|
||||
, mSetVolume(false)
|
||||
, mSetPlaybackRate(false)
|
||||
, mSetPreservesPitch(false)
|
||||
, mPlaying(true)
|
||||
{
|
||||
NS_ASSERTION(mStartTime != -1, "Should have audio start time by now");
|
||||
}
|
||||
|
||||
nsresult
|
||||
AudioSink::Init()
|
||||
{
|
||||
nsresult rv = NS_NewNamedThread("Media Audio",
|
||||
getter_AddRefs(mThread),
|
||||
nullptr,
|
||||
MEDIA_THREAD_STACK_SIZE);
|
||||
if (NS_FAILED(rv)) {
|
||||
return rv;
|
||||
}
|
||||
nsCOMPtr<nsIRunnable> event = NS_NewRunnableMethod(this, &AudioSink::AudioLoop);
|
||||
return mThread->Dispatch(event, NS_DISPATCH_NORMAL);
|
||||
}
|
||||
|
||||
int64_t
|
||||
AudioSink::GetPosition()
|
||||
{
|
||||
if (!mAudioStream) {
|
||||
return 0;
|
||||
}
|
||||
return mAudioStream->GetPosition();
|
||||
}
|
||||
|
||||
void
|
||||
AudioSink::PrepareToShutdown()
|
||||
{
|
||||
AssertCurrentThreadInMonitor();
|
||||
mStopAudioThread = true;
|
||||
if (mAudioStream) {
|
||||
mAudioStream->Cancel();
|
||||
}
|
||||
GetReentrantMonitor().NotifyAll();
|
||||
}
|
||||
|
||||
void
|
||||
AudioSink::Shutdown()
|
||||
{
|
||||
mThread->Shutdown();
|
||||
mThread = nullptr;
|
||||
MOZ_ASSERT(!mAudioStream);
|
||||
}
|
||||
|
||||
void
|
||||
AudioSink::SetVolume(double aVolume)
|
||||
{
|
||||
AssertCurrentThreadInMonitor();
|
||||
mVolume = aVolume;
|
||||
mSetVolume = true;
|
||||
}
|
||||
|
||||
void
|
||||
AudioSink::SetPlaybackRate(double aPlaybackRate)
|
||||
{
|
||||
AssertCurrentThreadInMonitor();
|
||||
NS_ASSERTION(mPlaybackRate != 0, "Don't set the playbackRate to 0 on AudioStream");
|
||||
mPlaybackRate = aPlaybackRate;
|
||||
mSetPlaybackRate = true;
|
||||
}
|
||||
|
||||
void
|
||||
AudioSink::SetPreservesPitch(bool aPreservesPitch)
|
||||
{
|
||||
AssertCurrentThreadInMonitor();
|
||||
mPreservesPitch = aPreservesPitch;
|
||||
mSetPreservesPitch = true;
|
||||
}
|
||||
|
||||
void
|
||||
AudioSink::StartPlayback()
|
||||
{
|
||||
AssertCurrentThreadInMonitor();
|
||||
mPlaying = true;
|
||||
GetReentrantMonitor().NotifyAll();
|
||||
}
|
||||
|
||||
void
|
||||
AudioSink::StopPlayback()
|
||||
{
|
||||
AssertCurrentThreadInMonitor();
|
||||
mPlaying = false;
|
||||
GetReentrantMonitor().NotifyAll();
|
||||
}
|
||||
|
||||
void
|
||||
AudioSink::AudioLoop()
|
||||
{
|
||||
AssertOnAudioThread();
|
||||
SINK_LOG("AudioLoop started");
|
||||
|
||||
if (NS_FAILED(InitializeAudioStream())) {
|
||||
NS_WARNING("Initializing AudioStream failed.");
|
||||
return;
|
||||
}
|
||||
|
||||
while (1) {
|
||||
WaitForAudioToPlay();
|
||||
if (!IsPlaybackContinuing()) {
|
||||
break;
|
||||
}
|
||||
|
||||
// See if there's a gap in the audio. If there is, push silence into the
|
||||
// audio hardware, so we can play across the gap.
|
||||
// Calculate the timestamp of the next chunk of audio in numbers of
|
||||
// samples.
|
||||
NS_ASSERTION(AudioQueue().GetSize() > 0, "Should have data to play");
|
||||
CheckedInt64 sampleTime = UsecsToFrames(AudioQueue().PeekFront()->mTime, mInfo.mRate);
|
||||
|
||||
// Calculate the number of frames that have been pushed onto the audio hardware.
|
||||
CheckedInt64 playedFrames = UsecsToFrames(mStartTime, mInfo.mRate) + mWritten;
|
||||
|
||||
CheckedInt64 missingFrames = sampleTime - playedFrames;
|
||||
if (!missingFrames.isValid() || !sampleTime.isValid()) {
|
||||
NS_WARNING("Int overflow adding in AudioLoop");
|
||||
break;
|
||||
}
|
||||
|
||||
if (missingFrames.value() > 0) {
|
||||
// The next audio chunk begins some time after the end of the last chunk
|
||||
// we pushed to the audio hardware. We must push silence into the audio
|
||||
// hardware so that the next audio chunk begins playback at the correct
|
||||
// time.
|
||||
missingFrames = std::min<int64_t>(UINT32_MAX, missingFrames.value());
|
||||
mWritten += PlaySilence(static_cast<uint32_t>(missingFrames.value()));
|
||||
} else {
|
||||
mWritten += PlayFromAudioQueue();
|
||||
}
|
||||
int64_t endTime = GetEndTime();
|
||||
if (endTime != -1) {
|
||||
mStateMachine->OnAudioEndTimeUpdate(endTime);
|
||||
}
|
||||
}
|
||||
ReentrantMonitorAutoEnter mon(GetReentrantMonitor());
|
||||
if (!mStopAudioThread && AudioQueue().AtEndOfStream()) {
|
||||
Drain();
|
||||
}
|
||||
SINK_LOG("AudioLoop complete");
|
||||
Cleanup();
|
||||
SINK_LOG("AudioLoop exit");
|
||||
}
|
||||
|
||||
nsresult
|
||||
AudioSink::InitializeAudioStream()
|
||||
{
|
||||
// AudioStream initialization can block for extended periods in unusual
|
||||
// circumstances, so we take care to drop the decoder monitor while
|
||||
// initializing.
|
||||
RefPtr<AudioStream> audioStream(new AudioStream());
|
||||
audioStream->Init(mInfo.mChannels, mInfo.mRate,
|
||||
mChannel, AudioStream::HighLatency);
|
||||
// TODO: Check Init's return value and bail on error. Unfortunately this
|
||||
// causes some tests to fail due to playback failing.
|
||||
ReentrantMonitorAutoEnter mon(GetReentrantMonitor());
|
||||
mAudioStream = audioStream;
|
||||
UpdateStreamSettings();
|
||||
|
||||
return NS_OK;
|
||||
}
|
||||
|
||||
void
|
||||
AudioSink::Drain()
|
||||
{
|
||||
MOZ_ASSERT(mPlaying && !mAudioStream->IsPaused());
|
||||
AssertCurrentThreadInMonitor();
|
||||
// If the media was too short to trigger the start of the audio stream,
|
||||
// start it now.
|
||||
mAudioStream->Start();
|
||||
{
|
||||
ReentrantMonitorAutoExit exit(GetReentrantMonitor());
|
||||
mAudioStream->Drain();
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
AudioSink::Cleanup()
|
||||
{
|
||||
// Must hold lock while shutting down and anulling the audio stream to prevent
|
||||
// state machine thread trying to use it while we're destroying it.
|
||||
AssertCurrentThreadInMonitor();
|
||||
mAudioStream->Shutdown();
|
||||
mAudioStream = nullptr;
|
||||
mStateMachine->OnAudioSinkComplete();
|
||||
}
|
||||
|
||||
bool
|
||||
AudioSink::ExpectMoreAudioData()
|
||||
{
|
||||
return AudioQueue().GetSize() == 0 && !AudioQueue().IsFinished();
|
||||
}
|
||||
|
||||
void
|
||||
AudioSink::WaitForAudioToPlay()
|
||||
{
|
||||
// Wait while we're not playing, and we're not shutting down, or we're
|
||||
// playing and we've got no audio to play.
|
||||
ReentrantMonitorAutoEnter mon(GetReentrantMonitor());
|
||||
while (!mStopAudioThread && (!mPlaying || ExpectMoreAudioData())) {
|
||||
if (!mPlaying && !mAudioStream->IsPaused()) {
|
||||
mAudioStream->Pause();
|
||||
}
|
||||
mon.Wait();
|
||||
}
|
||||
}
|
||||
|
||||
bool
|
||||
AudioSink::IsPlaybackContinuing()
|
||||
{
|
||||
ReentrantMonitorAutoEnter mon(GetReentrantMonitor());
|
||||
if (mPlaying && mAudioStream->IsPaused()) {
|
||||
mAudioStream->Resume();
|
||||
}
|
||||
|
||||
// If we're shutting down, captured, or at EOS, break out and exit the audio
|
||||
// thread.
|
||||
if (mStopAudioThread || AudioQueue().AtEndOfStream()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
UpdateStreamSettings();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
uint32_t
|
||||
AudioSink::PlaySilence(uint32_t aFrames)
|
||||
{
|
||||
// Maximum number of bytes we'll allocate and write at once to the audio
|
||||
// hardware when the audio stream contains missing frames and we're
|
||||
// writing silence in order to fill the gap. We limit our silence-writes
|
||||
// to 32KB in order to avoid allocating an impossibly large chunk of
|
||||
// memory if we encounter a large chunk of silence.
|
||||
const uint32_t SILENCE_BYTES_CHUNK = 32 * 1024;
|
||||
|
||||
AssertOnAudioThread();
|
||||
NS_ASSERTION(!mAudioStream->IsPaused(), "Don't play when paused");
|
||||
uint32_t maxFrames = SILENCE_BYTES_CHUNK / mInfo.mChannels / sizeof(AudioDataValue);
|
||||
uint32_t frames = std::min(aFrames, maxFrames);
|
||||
SINK_LOG_V("playing %u frames of silence", aFrames);
|
||||
WriteSilence(frames);
|
||||
return frames;
|
||||
}
|
||||
|
||||
uint32_t
|
||||
AudioSink::PlayFromAudioQueue()
|
||||
{
|
||||
AssertOnAudioThread();
|
||||
NS_ASSERTION(!mAudioStream->IsPaused(), "Don't play when paused");
|
||||
nsAutoPtr<AudioData> audio(AudioQueue().PopFront());
|
||||
{
|
||||
ReentrantMonitorAutoEnter mon(GetReentrantMonitor());
|
||||
NS_WARN_IF_FALSE(mPlaying, "Should be playing");
|
||||
// Awaken the decode loop if it's waiting for space to free up in the
|
||||
// audio queue.
|
||||
GetReentrantMonitor().NotifyAll();
|
||||
}
|
||||
SINK_LOG_V("playing %u frames of audio at time %lld",
|
||||
this, audio->mFrames, audio->mTime);
|
||||
mAudioStream->Write(audio->mAudioData, audio->mFrames);
|
||||
|
||||
StartAudioStreamPlaybackIfNeeded();
|
||||
|
||||
if (audio->mOffset != -1) {
|
||||
mStateMachine->OnPlaybackOffsetUpdate(audio->mOffset);
|
||||
}
|
||||
return audio->mFrames;
|
||||
}
|
||||
|
||||
void
|
||||
AudioSink::UpdateStreamSettings()
|
||||
{
|
||||
AssertCurrentThreadInMonitor();
|
||||
|
||||
bool setVolume = mSetVolume;
|
||||
bool setPlaybackRate = mSetPlaybackRate;
|
||||
bool setPreservesPitch = mSetPreservesPitch;
|
||||
double volume = mVolume;
|
||||
double playbackRate = mPlaybackRate;
|
||||
bool preservesPitch = mPreservesPitch;
|
||||
|
||||
mSetVolume = false;
|
||||
mSetPlaybackRate = false;
|
||||
mSetPreservesPitch = false;
|
||||
|
||||
{
|
||||
ReentrantMonitorAutoExit exit(GetReentrantMonitor());
|
||||
if (setVolume) {
|
||||
mAudioStream->SetVolume(volume);
|
||||
}
|
||||
|
||||
if (setPlaybackRate &&
|
||||
NS_FAILED(mAudioStream->SetPlaybackRate(playbackRate))) {
|
||||
NS_WARNING("Setting the playback rate failed in AudioSink.");
|
||||
}
|
||||
|
||||
if (setPreservesPitch &&
|
||||
NS_FAILED(mAudioStream->SetPreservesPitch(preservesPitch))) {
|
||||
NS_WARNING("Setting the pitch preservation failed in AudioSink.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
AudioSink::StartAudioStreamPlaybackIfNeeded()
|
||||
{
|
||||
// This value has been chosen empirically.
|
||||
const uint32_t MIN_WRITE_BEFORE_START_USECS = 200000;
|
||||
|
||||
// We want to have enough data in the buffer to start the stream.
|
||||
if (static_cast<double>(mAudioStream->GetWritten()) / mAudioStream->GetRate() >=
|
||||
static_cast<double>(MIN_WRITE_BEFORE_START_USECS) / USECS_PER_S) {
|
||||
mAudioStream->Start();
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
AudioSink::WriteSilence(uint32_t aFrames)
|
||||
{
|
||||
uint32_t numSamples = aFrames * mInfo.mChannels;
|
||||
nsAutoTArray<AudioDataValue, 1000> buf;
|
||||
buf.SetLength(numSamples);
|
||||
memset(buf.Elements(), 0, numSamples * sizeof(AudioDataValue));
|
||||
mAudioStream->Write(buf.Elements(), aFrames);
|
||||
|
||||
StartAudioStreamPlaybackIfNeeded();
|
||||
}
|
||||
|
||||
int64_t
|
||||
AudioSink::GetEndTime()
|
||||
{
|
||||
CheckedInt64 playedUsecs = FramesToUsecs(mWritten, mInfo.mRate) + mStartTime;
|
||||
if (!playedUsecs.isValid()) {
|
||||
NS_WARNING("Int overflow calculating audio end time");
|
||||
return -1;
|
||||
}
|
||||
return playedUsecs.value();
|
||||
}
|
||||
|
||||
MediaQueue<AudioData>&
|
||||
AudioSink::AudioQueue()
|
||||
{
|
||||
return mStateMachine->AudioQueue();
|
||||
}
|
||||
|
||||
ReentrantMonitor&
|
||||
AudioSink::GetReentrantMonitor()
|
||||
{
|
||||
return mStateMachine->mDecoder->GetReentrantMonitor();
|
||||
}
|
||||
|
||||
void
|
||||
AudioSink::AssertCurrentThreadInMonitor()
|
||||
{
|
||||
return mStateMachine->AssertCurrentThreadInMonitor();
|
||||
}
|
||||
|
||||
void
|
||||
AudioSink::AssertOnAudioThread()
|
||||
{
|
||||
MOZ_ASSERT(IsCurrentThread(mThread));
|
||||
}
|
||||
|
||||
} // namespace mozilla
|
138
content/media/AudioSink.h
Normal file
138
content/media/AudioSink.h
Normal file
@ -0,0 +1,138 @@
|
||||
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
|
||||
/* vim:set ts=2 sw=2 sts=2 et cindent: */
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
#if !defined(AudioSink_h__)
|
||||
#define AudioSink_h__
|
||||
|
||||
#include "nsISupportsImpl.h"
|
||||
#include "MediaDecoderReader.h"
|
||||
#include "mozilla/dom/AudioChannelBinding.h"
|
||||
|
||||
namespace mozilla {
|
||||
|
||||
class AudioAvailableEventManager;
|
||||
class AudioStream;
|
||||
class MediaDecoderStateMachine;
|
||||
|
||||
class AudioSink {
|
||||
public:
|
||||
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(AudioSink)
|
||||
|
||||
AudioSink(MediaDecoderStateMachine* aStateMachine,
|
||||
int64_t aStartTime, AudioInfo aInfo, dom::AudioChannel aChannel);
|
||||
|
||||
nsresult Init();
|
||||
|
||||
int64_t GetPosition();
|
||||
|
||||
// Tell the AudioSink to stop processing and initiate shutdown. Must be
|
||||
// called with the decoder monitor held.
|
||||
void PrepareToShutdown();
|
||||
|
||||
// Shut down the AudioSink's resources. The decoder monitor must not be
|
||||
// held during this call, as it may block processing thread event queues.
|
||||
void Shutdown();
|
||||
|
||||
void SetVolume(double aVolume);
|
||||
void SetPlaybackRate(double aPlaybackRate);
|
||||
void SetPreservesPitch(bool aPreservesPitch);
|
||||
|
||||
void StartPlayback();
|
||||
void StopPlayback();
|
||||
|
||||
private:
|
||||
~AudioSink() {}
|
||||
|
||||
// The main loop for the audio thread. Sent to the thread as
|
||||
// an nsRunnableMethod. This continually does blocking writes to
|
||||
// to audio stream to play audio data.
|
||||
void AudioLoop();
|
||||
|
||||
// Allocate and initialize mAudioStream. Returns NS_OK on success.
|
||||
nsresult InitializeAudioStream();
|
||||
|
||||
void Drain();
|
||||
|
||||
void Cleanup();
|
||||
|
||||
bool ExpectMoreAudioData();
|
||||
|
||||
// Wait on the decoder monitor until playback is ready or the sink is told to shut down.
|
||||
void WaitForAudioToPlay();
|
||||
|
||||
// Check if the sink has been told to shut down, resuming mAudioStream if
|
||||
// not. Returns true if processing should continue, false if AudioLoop
|
||||
// should shutdown.
|
||||
bool IsPlaybackContinuing();
|
||||
|
||||
// Write aFrames of audio frames of silence to the audio hardware. Returns
|
||||
// the number of frames actually written. The write size is capped at
|
||||
// SILENCE_BYTES_CHUNK (32kB), so must be called in a loop to write the
|
||||
// desired number of frames. This ensures that the playback position
|
||||
// advances smoothly, and guarantees that we don't try to allocate an
|
||||
// impossibly large chunk of memory in order to play back silence. Called
|
||||
// on the audio thread.
|
||||
uint32_t PlaySilence(uint32_t aFrames);
|
||||
|
||||
// Pops an audio chunk from the front of the audio queue, and pushes its
|
||||
// audio data to the audio hardware. Called on the audio thread.
|
||||
uint32_t PlayFromAudioQueue();
|
||||
|
||||
void UpdateStreamSettings();
|
||||
|
||||
// If we have already written enough frames to the AudioStream, start the
|
||||
// playback.
|
||||
void StartAudioStreamPlaybackIfNeeded();
|
||||
void WriteSilence(uint32_t aFrames);
|
||||
|
||||
int64_t GetEndTime();
|
||||
|
||||
MediaQueue<AudioData>& AudioQueue();
|
||||
|
||||
ReentrantMonitor& GetReentrantMonitor();
|
||||
void AssertCurrentThreadInMonitor();
|
||||
void AssertOnAudioThread();
|
||||
|
||||
nsRefPtr<MediaDecoderStateMachine> mStateMachine;
|
||||
|
||||
// Thread for pushing audio onto the audio hardware.
|
||||
// The "audio push thread".
|
||||
nsCOMPtr<nsIThread> mThread;
|
||||
|
||||
// The audio stream resource. Used on the state machine, and audio threads.
|
||||
// This is created and destroyed on the audio thread, while holding the
|
||||
// decoder monitor, so if this is used off the audio thread, you must
|
||||
// first acquire the decoder monitor and check that it is non-null.
|
||||
RefPtr<AudioStream> mAudioStream;
|
||||
|
||||
// The presentation time of the first audio frame that was played in
|
||||
// microseconds. We can add this to the audio stream position to determine
|
||||
// the current audio time. Accessed on audio and state machine thread.
|
||||
// Synchronized by decoder monitor.
|
||||
int64_t mStartTime;
|
||||
|
||||
// PCM frames written to the stream so far.
|
||||
int64_t mWritten;
|
||||
|
||||
AudioInfo mInfo;
|
||||
|
||||
dom::AudioChannel mChannel;
|
||||
|
||||
double mVolume;
|
||||
double mPlaybackRate;
|
||||
bool mPreservesPitch;
|
||||
|
||||
bool mStopAudioThread;
|
||||
|
||||
bool mSetVolume;
|
||||
bool mSetPlaybackRate;
|
||||
bool mSetPreservesPitch;
|
||||
|
||||
bool mPlaying;
|
||||
};
|
||||
|
||||
} // namespace mozilla
|
||||
|
||||
#endif
|
@ -51,6 +51,88 @@ double AudioStream::sVolumeScale;
|
||||
uint32_t AudioStream::sCubebLatency;
|
||||
bool AudioStream::sCubebLatencyPrefSet;
|
||||
|
||||
|
||||
/**
|
||||
* Keep a list of frames sent to the audio engine in each DataCallback along
|
||||
* with the playback rate at the moment. Since the playback rate and number of
|
||||
* underrun frames can vary in each callback. We need to keep the whole history
|
||||
* in order to calculate the playback position of the audio engine correctly.
|
||||
*/
|
||||
class FrameHistory {
|
||||
struct Chunk {
|
||||
uint32_t servicedFrames;
|
||||
uint32_t totalFrames;
|
||||
int rate;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
static T FramesToUs(uint32_t frames, int rate) {
|
||||
return static_cast<T>(frames) * USECS_PER_S / rate;
|
||||
}
|
||||
public:
|
||||
FrameHistory()
|
||||
: mBaseOffset(0), mBasePosition(0) {}
|
||||
|
||||
void Append(uint32_t aServiced, uint32_t aUnderrun, int aRate) {
|
||||
/* In most case where playback rate stays the same and we don't underrun
|
||||
* frames, we are able to merge chunks to avoid lose of precision to add up
|
||||
* in compressing chunks into |mBaseOffset| and |mBasePosition|.
|
||||
*/
|
||||
if (!mChunks.IsEmpty()) {
|
||||
Chunk& c = mChunks.LastElement();
|
||||
// 2 chunks (c1 and c2) can be merged when rate is the same and
|
||||
// adjacent frames are zero. That is, underrun frames in c1 are zero
|
||||
// or serviced frames in c2 are zero.
|
||||
if (c.rate == aRate &&
|
||||
(c.servicedFrames == c.totalFrames ||
|
||||
aServiced == 0)) {
|
||||
c.servicedFrames += aServiced;
|
||||
c.totalFrames += aServiced + aUnderrun;
|
||||
return;
|
||||
}
|
||||
}
|
||||
Chunk* p = mChunks.AppendElement();
|
||||
p->servicedFrames = aServiced;
|
||||
p->totalFrames = aServiced + aUnderrun;
|
||||
p->rate = aRate;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param frames The playback position in frames of the audio engine.
|
||||
* @return The playback position in microseconds of the audio engine,
|
||||
* adjusted by playback rate changes and underrun frames.
|
||||
*/
|
||||
int64_t GetPosition(int64_t frames) {
|
||||
// playback position should not go backward.
|
||||
MOZ_ASSERT(frames >= mBaseOffset);
|
||||
while (true) {
|
||||
if (mChunks.IsEmpty()) {
|
||||
return mBasePosition;
|
||||
}
|
||||
const Chunk& c = mChunks[0];
|
||||
if (frames <= mBaseOffset + c.totalFrames) {
|
||||
uint32_t delta = frames - mBaseOffset;
|
||||
delta = std::min(delta, c.servicedFrames);
|
||||
return static_cast<int64_t>(mBasePosition) +
|
||||
FramesToUs<int64_t>(delta, c.rate);
|
||||
}
|
||||
// Since the playback position of the audio engine will not go backward,
|
||||
// we are able to compress chunks so that |mChunks| won't grow unlimitedly.
|
||||
// Note that we lose precision in converting integers into floats and
|
||||
// inaccuracy will accumulate over time. However, for a 24hr long,
|
||||
// sample rate = 44.1k file, the error will be less than 1 microsecond
|
||||
// after playing 24 hours. So we are fine with that.
|
||||
mBaseOffset += c.totalFrames;
|
||||
mBasePosition += FramesToUs<double>(c.servicedFrames, c.rate);
|
||||
mChunks.RemoveElementAt(0);
|
||||
}
|
||||
}
|
||||
private:
|
||||
nsAutoTArray<Chunk, 7> mChunks;
|
||||
int64_t mBaseOffset;
|
||||
double mBasePosition;
|
||||
};
|
||||
|
||||
/*static*/ void AudioStream::PrefChanged(const char* aPref, void* aClosure)
|
||||
{
|
||||
if (strcmp(aPref, PREF_VOLUME_SCALE) == 0) {
|
||||
@ -163,10 +245,6 @@ AudioStream::AudioStream()
|
||||
, mAudioClock(MOZ_THIS_IN_INITIALIZER_LIST())
|
||||
, mLatencyRequest(HighLatency)
|
||||
, mReadPoint(0)
|
||||
, mWrittenFramesPast(0)
|
||||
, mLostFramesPast(0)
|
||||
, mWrittenFramesLast(0)
|
||||
, mLostFramesLast(0)
|
||||
, mDumpFile(nullptr)
|
||||
, mVolume(1.0)
|
||||
, mBytesPerFrame(0)
|
||||
@ -663,6 +741,14 @@ AudioStream::SetVolume(double aVolume)
|
||||
mVolume = aVolume;
|
||||
}
|
||||
|
||||
void
|
||||
AudioStream::Cancel()
|
||||
{
|
||||
MonitorAutoLock mon(mMonitor);
|
||||
mState = ERRORED;
|
||||
mon.NotifyAll();
|
||||
}
|
||||
|
||||
void
|
||||
AudioStream::Drain()
|
||||
{
|
||||
@ -773,19 +859,13 @@ AudioStream::GetPosition()
|
||||
int64_t
|
||||
AudioStream::GetPositionInFrames()
|
||||
{
|
||||
MonitorAutoLock mon(mMonitor);
|
||||
return mAudioClock.GetPositionInFrames();
|
||||
}
|
||||
#ifdef _MSC_VER
|
||||
#pragma optimize("", on)
|
||||
#endif
|
||||
|
||||
int64_t
|
||||
AudioStream::GetPositionInFramesInternal()
|
||||
{
|
||||
MonitorAutoLock mon(mMonitor);
|
||||
return GetPositionInFramesUnlocked();
|
||||
}
|
||||
|
||||
int64_t
|
||||
AudioStream::GetPositionInFramesUnlocked()
|
||||
{
|
||||
@ -803,32 +883,7 @@ AudioStream::GetPositionInFramesUnlocked()
|
||||
}
|
||||
}
|
||||
|
||||
// Adjust the reported position by the number of silent frames written
|
||||
// during stream underruns.
|
||||
// Since frames sent to DataCallback is not consumed by the backend immediately,
|
||||
// it will be an over adjustment if we return |position - mLostFramesPast - mLostFramesLast|.
|
||||
// On the other hand, we need to keep the whole history of frames sent to DataCallback
|
||||
// in order to adjust position correctly which will require more storage.
|
||||
// We choose a simple way to store the history where |mWrittenFramesPast| and
|
||||
// |mLostFramesPast| are the sum of frames from 1th to |N-1|th callbacks, and
|
||||
// |mWrittenFramesLast| and |mLostFramesLast| represent the frames sent in last callback.
|
||||
// When |position| lies in
|
||||
// [mWrittenFramesPast+mLostFramesPast, mWrittenFramesPast+mLostFramesPast+mWrittenFramesLast+mLostFramesLast],
|
||||
// we will be able to adjust position precisely which should be the major case.
|
||||
// If |position| falls in [0, mWrittenFramesPast+mLostFramesPast), there will be an
|
||||
// error in the adjustment. However that is fine as long as we can ensure the
|
||||
// adjusted position is mono-increasing to avoid audio clock going backward.
|
||||
uint64_t adjustedPosition = 0;
|
||||
if (position <= mWrittenFramesPast) {
|
||||
adjustedPosition = position;
|
||||
} else if (position <= mWrittenFramesPast + mLostFramesPast) {
|
||||
adjustedPosition = mWrittenFramesPast;
|
||||
} else if (position <= mWrittenFramesPast + mLostFramesPast + mWrittenFramesLast) {
|
||||
adjustedPosition = position - mLostFramesPast;
|
||||
} else {
|
||||
adjustedPosition = mWrittenFramesPast + mWrittenFramesLast;
|
||||
}
|
||||
return std::min<uint64_t>(adjustedPosition, INT64_MAX);
|
||||
return std::min<uint64_t>(position, INT64_MAX);
|
||||
}
|
||||
|
||||
int64_t
|
||||
@ -933,7 +988,7 @@ AudioStream::GetTimeStretched(void* aBuffer, long aFrames, int64_t &aTimeMs)
|
||||
|
||||
uint8_t* wpos = reinterpret_cast<uint8_t*>(aBuffer);
|
||||
double playbackRate = static_cast<double>(mInRate) / mOutRate;
|
||||
uint32_t toPopBytes = FramesToBytes(ceil(aFrames / playbackRate));
|
||||
uint32_t toPopBytes = FramesToBytes(ceil(aFrames * playbackRate));
|
||||
uint32_t available = 0;
|
||||
bool lowOnBufferedData = false;
|
||||
do {
|
||||
@ -973,9 +1028,6 @@ AudioStream::DataCallback(void* aBuffer, long aFrames)
|
||||
uint32_t servicedFrames = 0;
|
||||
int64_t insertTime;
|
||||
|
||||
mWrittenFramesPast += mWrittenFramesLast;
|
||||
mLostFramesPast += mLostFramesLast;
|
||||
|
||||
// NOTE: wasapi (others?) can call us back *after* stop()/Shutdown() (mState == SHUTDOWN)
|
||||
// Bug 996162
|
||||
|
||||
@ -1039,10 +1091,11 @@ AudioStream::DataCallback(void* aBuffer, long aFrames)
|
||||
}
|
||||
|
||||
underrunFrames = aFrames - servicedFrames;
|
||||
mWrittenFramesLast = servicedFrames;
|
||||
mLostFramesLast = underrunFrames;
|
||||
|
||||
// Always send audible frames first, and silent frames later.
|
||||
// Otherwise it will break the assumption of FrameHistory.
|
||||
if (mState != DRAINING) {
|
||||
mAudioClock.UpdateFrameHistory(servicedFrames, underrunFrames);
|
||||
uint8_t* rpos = static_cast<uint8_t*>(aBuffer) + FramesToBytes(aFrames - underrunFrames);
|
||||
memset(rpos, 0, FramesToBytes(underrunFrames));
|
||||
if (underrunFrames) {
|
||||
@ -1050,6 +1103,8 @@ AudioStream::DataCallback(void* aBuffer, long aFrames)
|
||||
("AudioStream %p lost %d frames", this, underrunFrames));
|
||||
}
|
||||
servicedFrames += underrunFrames;
|
||||
} else {
|
||||
mAudioClock.UpdateFrameHistory(servicedFrames, 0);
|
||||
}
|
||||
|
||||
WriteDumpFile(mDumpFile, this, aFrames, aBuffer);
|
||||
@ -1069,7 +1124,6 @@ AudioStream::DataCallback(void* aBuffer, long aFrames)
|
||||
(latency * 1000) / mOutRate, now);
|
||||
}
|
||||
|
||||
mAudioClock.UpdateWritePosition(servicedFrames);
|
||||
return servicedFrames;
|
||||
}
|
||||
|
||||
@ -1088,94 +1142,42 @@ AudioStream::StateCallback(cubeb_state aState)
|
||||
|
||||
AudioClock::AudioClock(AudioStream* aStream)
|
||||
:mAudioStream(aStream),
|
||||
mOldOutRate(0),
|
||||
mBasePosition(0),
|
||||
mBaseOffset(0),
|
||||
mOldBaseOffset(0),
|
||||
mOldBasePosition(0),
|
||||
mPlaybackRateChangeOffset(0),
|
||||
mPreviousPosition(0),
|
||||
mWritten(0),
|
||||
mOutRate(0),
|
||||
mInRate(0),
|
||||
mPreservesPitch(true),
|
||||
mCompensatingLatency(false)
|
||||
mFrameHistory(new FrameHistory())
|
||||
{}
|
||||
|
||||
void AudioClock::Init()
|
||||
{
|
||||
mOutRate = mAudioStream->GetRate();
|
||||
mInRate = mAudioStream->GetRate();
|
||||
mOldOutRate = mOutRate;
|
||||
}
|
||||
|
||||
void AudioClock::UpdateWritePosition(uint32_t aCount)
|
||||
void AudioClock::UpdateFrameHistory(uint32_t aServiced, uint32_t aUnderrun)
|
||||
{
|
||||
mWritten += aCount;
|
||||
mFrameHistory->Append(aServiced, aUnderrun, mOutRate);
|
||||
}
|
||||
|
||||
uint64_t AudioClock::GetPositionUnlocked()
|
||||
int64_t AudioClock::GetPositionUnlocked() const
|
||||
{
|
||||
// GetPositionInFramesUnlocked() asserts it owns the monitor
|
||||
int64_t position = mAudioStream->GetPositionInFramesUnlocked();
|
||||
int64_t diffOffset;
|
||||
NS_ASSERTION(position < 0 || (mInRate != 0 && mOutRate != 0), "AudioClock not initialized.");
|
||||
if (position >= 0) {
|
||||
if (position < mPlaybackRateChangeOffset) {
|
||||
// See if we are still playing frames pushed with the old playback rate in
|
||||
// the backend. If we are, use the old output rate to compute the
|
||||
// position.
|
||||
mCompensatingLatency = true;
|
||||
diffOffset = position - mOldBaseOffset;
|
||||
position = static_cast<uint64_t>(mOldBasePosition +
|
||||
static_cast<float>(USECS_PER_S * diffOffset) / mOldOutRate);
|
||||
mPreviousPosition = position;
|
||||
return position;
|
||||
}
|
||||
|
||||
if (mCompensatingLatency) {
|
||||
diffOffset = position - mPlaybackRateChangeOffset;
|
||||
mCompensatingLatency = false;
|
||||
mBasePosition = mPreviousPosition;
|
||||
} else {
|
||||
diffOffset = position - mPlaybackRateChangeOffset;
|
||||
}
|
||||
position = static_cast<uint64_t>(mBasePosition +
|
||||
(static_cast<float>(USECS_PER_S * diffOffset) / mOutRate));
|
||||
return position;
|
||||
}
|
||||
return UINT64_MAX;
|
||||
int64_t frames = mAudioStream->GetPositionInFramesUnlocked();
|
||||
NS_ASSERTION(frames < 0 || (mInRate != 0 && mOutRate != 0), "AudioClock not initialized.");
|
||||
return frames >= 0 ? mFrameHistory->GetPosition(frames) : -1;
|
||||
}
|
||||
|
||||
uint64_t AudioClock::GetPositionInFrames()
|
||||
int64_t AudioClock::GetPositionInFrames() const
|
||||
{
|
||||
return (GetPositionUnlocked() * mOutRate) / USECS_PER_S;
|
||||
return (GetPositionUnlocked() * mInRate) / USECS_PER_S;
|
||||
}
|
||||
|
||||
void AudioClock::SetPlaybackRateUnlocked(double aPlaybackRate)
|
||||
{
|
||||
// GetPositionInFramesUnlocked() asserts it owns the monitor
|
||||
int64_t position = mAudioStream->GetPositionInFramesUnlocked();
|
||||
if (position > mPlaybackRateChangeOffset) {
|
||||
mOldBasePosition = mBasePosition;
|
||||
mBasePosition = GetPositionUnlocked();
|
||||
mOldBaseOffset = mPlaybackRateChangeOffset;
|
||||
mBaseOffset = position;
|
||||
mPlaybackRateChangeOffset = mWritten;
|
||||
mOldOutRate = mOutRate;
|
||||
mOutRate = static_cast<int>(mInRate / aPlaybackRate);
|
||||
} else {
|
||||
// The playbackRate has been changed before the end of the latency
|
||||
// compensation phase. We don't update the mOld* variable. That way, the
|
||||
// last playbackRate set is taken into account.
|
||||
mBasePosition = GetPositionUnlocked();
|
||||
mBaseOffset = position;
|
||||
mPlaybackRateChangeOffset = mWritten;
|
||||
mOutRate = static_cast<int>(mInRate / aPlaybackRate);
|
||||
}
|
||||
mOutRate = static_cast<int>(mInRate / aPlaybackRate);
|
||||
}
|
||||
|
||||
double AudioClock::GetPlaybackRate()
|
||||
double AudioClock::GetPlaybackRate() const
|
||||
{
|
||||
return static_cast<double>(mInRate) / mOutRate;
|
||||
}
|
||||
@ -1185,7 +1187,7 @@ void AudioClock::SetPreservesPitch(bool aPreservesPitch)
|
||||
mPreservesPitch = aPreservesPitch;
|
||||
}
|
||||
|
||||
bool AudioClock::GetPreservesPitch()
|
||||
bool AudioClock::GetPreservesPitch() const
|
||||
{
|
||||
return mPreservesPitch;
|
||||
}
|
||||
|
@ -32,6 +32,7 @@ class SoundTouch;
|
||||
namespace mozilla {
|
||||
|
||||
class AudioStream;
|
||||
class FrameHistory;
|
||||
|
||||
class AudioClock
|
||||
{
|
||||
@ -42,15 +43,15 @@ public:
|
||||
void Init();
|
||||
// Update the number of samples that has been written in the audio backend.
|
||||
// Called on the state machine thread.
|
||||
void UpdateWritePosition(uint32_t aCount);
|
||||
void UpdateFrameHistory(uint32_t aServiced, uint32_t aUnderrun);
|
||||
// Get the read position of the stream, in microseconds.
|
||||
// Called on the state machine thead.
|
||||
// Assumes the AudioStream lock is held and thus calls Unlocked versions
|
||||
// of AudioStream funcs.
|
||||
uint64_t GetPositionUnlocked();
|
||||
int64_t GetPositionUnlocked() const;
|
||||
// Get the read position of the stream, in frames.
|
||||
// Called on the state machine thead.
|
||||
uint64_t GetPositionInFrames();
|
||||
int64_t GetPositionInFrames() const;
|
||||
// Set the playback rate.
|
||||
// Called on the audio thread.
|
||||
// Assumes the AudioStream lock is held and thus calls Unlocked versions
|
||||
@ -58,46 +59,25 @@ public:
|
||||
void SetPlaybackRateUnlocked(double aPlaybackRate);
|
||||
// Get the current playback rate.
|
||||
// Called on the audio thread.
|
||||
double GetPlaybackRate();
|
||||
double GetPlaybackRate() const;
|
||||
// Set if we are preserving the pitch.
|
||||
// Called on the audio thread.
|
||||
void SetPreservesPitch(bool aPreservesPitch);
|
||||
// Get the current pitch preservation state.
|
||||
// Called on the audio thread.
|
||||
bool GetPreservesPitch();
|
||||
bool GetPreservesPitch() const;
|
||||
private:
|
||||
// This AudioStream holds a strong reference to this AudioClock. This
|
||||
// pointer is garanteed to always be valid.
|
||||
AudioStream* mAudioStream;
|
||||
// The old output rate, to compensate audio latency for the period inbetween
|
||||
// the moment resampled buffers are pushed to the hardware and the moment the
|
||||
// clock should take the new rate into account for A/V sync.
|
||||
int mOldOutRate;
|
||||
// Position at which the last playback rate change occured
|
||||
int64_t mBasePosition;
|
||||
// Offset, in frames, at which the last playback rate change occured
|
||||
int64_t mBaseOffset;
|
||||
// Old base offset (number of samples), used when changing rate to compute the
|
||||
// position in the stream.
|
||||
int64_t mOldBaseOffset;
|
||||
// Old base position (number of microseconds), when changing rate. This is the
|
||||
// time in the media, not wall clock position.
|
||||
int64_t mOldBasePosition;
|
||||
// Write position at which the playbackRate change occured.
|
||||
int64_t mPlaybackRateChangeOffset;
|
||||
// The previous position reached in the media, used when compensating
|
||||
// latency, to have the position at which the playbackRate change occured.
|
||||
int64_t mPreviousPosition;
|
||||
// Number of samples effectivelly written in backend, i.e. write position.
|
||||
int64_t mWritten;
|
||||
AudioStream* const mAudioStream;
|
||||
// Output rate in Hz (characteristic of the playback rate)
|
||||
int mOutRate;
|
||||
// Input rate in Hz (characteristic of the media being played)
|
||||
int mInRate;
|
||||
// True if the we are timestretching, false if we are resampling.
|
||||
bool mPreservesPitch;
|
||||
// True if we are playing at the old playbackRate after it has been changed.
|
||||
bool mCompensatingLatency;
|
||||
// The history of frames sent to the audio engine in each Datacallback.
|
||||
const nsAutoPtr<FrameHistory> mFrameHistory;
|
||||
};
|
||||
|
||||
class CircularByteBuffer
|
||||
@ -249,6 +229,9 @@ public:
|
||||
// Block until buffered audio data has been consumed.
|
||||
void Drain();
|
||||
|
||||
// Break any blocking operation and set the stream to shutdown.
|
||||
void Cancel();
|
||||
|
||||
// Start the stream.
|
||||
void Start();
|
||||
|
||||
@ -270,11 +253,6 @@ public:
|
||||
// was opened, of the audio hardware. Thread-safe.
|
||||
int64_t GetPositionInFrames();
|
||||
|
||||
// Return the position, measured in audio framed played since the stream was
|
||||
// opened, of the audio hardware, not adjusted for the changes of playback
|
||||
// rate.
|
||||
int64_t GetPositionInFramesInternal();
|
||||
|
||||
// Returns true when the audio stream is paused.
|
||||
bool IsPaused();
|
||||
|
||||
@ -293,7 +271,9 @@ public:
|
||||
protected:
|
||||
friend class AudioClock;
|
||||
|
||||
// Shared implementation of underflow adjusted position calculation.
|
||||
// Return the position, measured in audio frames played since the stream was
|
||||
// opened, of the audio hardware, not adjusted for the changes of playback
|
||||
// rate or underrun frames.
|
||||
// Caller must own the monitor.
|
||||
int64_t GetPositionInFramesUnlocked();
|
||||
|
||||
@ -372,15 +352,6 @@ private:
|
||||
};
|
||||
nsAutoTArray<Inserts, 8> mInserts;
|
||||
|
||||
// Suppose we have received DataCallback for N times, |mWrittenFramesPast|
|
||||
// and |mLostFramesPast| are the sum of frames written to the backend from
|
||||
// 1st to |N-1|th DataCallbacks.
|
||||
uint64_t mWrittenFramesPast; // non-silent frames
|
||||
uint64_t mLostFramesPast; // silent frames
|
||||
// Frames written to the backend in Nth DataCallback.
|
||||
uint64_t mWrittenFramesLast; // non-silent frames
|
||||
uint64_t mLostFramesLast; // silent frames
|
||||
|
||||
// Output file for dumping audio
|
||||
FILE* mDumpFile;
|
||||
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user