Bug 1165162 - Introduce a helper for converting from origin strings to a principal. rpending=Yoshi

I didn't end up needing this in bug, but I think it's handy to have around.
This commit is contained in:
Bobby Holley 2015-05-18 11:10:46 -07:00
parent fdd2d33fa4
commit f25a3264ea
2 changed files with 37 additions and 0 deletions

View File

@ -3,9 +3,16 @@ const Ci = Components.interfaces;
const Cu = Components.utils;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/BrowserUtils.jsm");
var ssm = Services.scriptSecurityManager;
function makeURI(uri) { return Services.io.newURI(uri, null, null); }
function checkThrows(f) {
var threw = false;
try { f(); } catch (e) { threw = true }
do_check_true(threw);
}
function checkCrossOrigin(a, b) {
do_check_false(a.equals(b));
do_check_false(a.equalsConsideringDomain(b));
@ -22,6 +29,11 @@ function checkOriginAttributes(prin, appId, inBrowser, suffix) {
do_check_eq(prin.originAttributes.appId, appId || 0);
do_check_eq(prin.originAttributes.inBrowser, inBrowser || false);
do_check_eq(prin.originSuffix, suffix || '');
if (!prin.isNullPrincipal && !prin.origin.startsWith('[')) {
do_check_true(BrowserUtils.principalFromOrigin(prin.origin).equals(prin));
} else {
checkThrows(() => BrowserUtils.principalFromOrigin(prin.origin));
}
}
function run_test() {

View File

@ -10,6 +10,7 @@ this.EXPORTED_SYMBOLS = [ "BrowserUtils" ];
const {interfaces: Ci, utils: Cu, classes: Cc} = Components;
Cu.import("resource://gre/modules/Services.jsm");
Cu.importGlobalProperties(['URL']);
this.BrowserUtils = {
@ -93,6 +94,30 @@ this.BrowserUtils = {
return Services.io.newURI(aCPOWURI.spec, aCPOWURI.originCharset, null);
},
// Creates a codebase principal from a canonical origin string. This is the
// the inverse operation of .origin on a codebase principal.
principalFromOrigin: function(aOriginString) {
if (aOriginString.startsWith('[')) {
throw new Error("principalFromOrigin does not support System and Expanded principals");
}
if (aOriginString.startsWith("moz-nullprincipal:")) {
throw new Error("principalFromOrigin does not support nsNullPrincipal");
}
var parts = aOriginString.split('!');
if (parts.length > 2) {
throw new Error("bad origin string: " + aOriginString);
}
var uri = Services.io.newURI(parts[0], null, null);
var attrs = {};
// Parse the parameters string into a dictionary.
(parts[1] || "").split("&").map((x) => x.split('=')).forEach((x) => attrs[x[0]] = x[1]);
return Services.scriptSecurityManager.createCodebasePrincipal(uri, attrs);
},
/**
* For a given DOM element, returns its position in "screen"
* coordinates. In a content process, the coordinates returned will