Bug 1561435 - Format extensions/, a=automatic-formatting

# ignore-this-changeset

Differential Revision: https://phabricator.services.mozilla.com/D35902

--HG--
extra : source : 31cb194f2a6651332aa71a41c0f06a29daf8a186
This commit is contained in:
Victor Porof 2019-07-05 10:46:07 +02:00
parent 5065489a4e
commit 5af464dcc4
39 changed files with 2736 additions and 1206 deletions

View file

@ -45,7 +45,6 @@ module.exports = {
"overrides": [{ "overrides": [{
"files": [ "files": [
"devtools/**", "devtools/**",
"extensions/**",
"gfx/**", "gfx/**",
"gradle/**", "gradle/**",
"hal/**", "hal/**",

View file

@ -40,7 +40,6 @@ toolkit/components/telemetry/datareporting-prefs.js
toolkit/components/telemetry/healthreport-prefs.js toolkit/components/telemetry/healthreport-prefs.js
# Ignore all top-level directories for now. # Ignore all top-level directories for now.
extensions/**
gfx/** gfx/**
gradle/** gradle/**
hal/** hal/**

View file

@ -1,10 +1,16 @@
function addPerm(aURI, aName) { function addPerm(aURI, aName) {
Services.perms.add(Services.io.newURI(aURI), aName, Services.perms.ALLOW_ACTION); Services.perms.add(
Services.io.newURI(aURI),
aName,
Services.perms.ALLOW_ACTION
);
} }
function hasPerm(aURI, aName) { function hasPerm(aURI, aName) {
return Services.perms.testPermission(Services.io.newURI(aURI), aName) return (
== Services.perms.ALLOW_ACTION; Services.perms.testPermission(Services.io.newURI(aURI), aName) ==
Services.perms.ALLOW_ACTION
);
} }
add_task(async function() { add_task(async function() {
@ -24,13 +30,18 @@ add_task(async function() {
// Then zero is correct. // Then zero is correct.
} }
let safeProcessCount = keepAliveCount + 2; let safeProcessCount = keepAliveCount + 2;
info("dom.ipc.keepProcessesAlive.web is " + keepAliveCount + ", boosting " + info(
"process count temporarily to " + safeProcessCount); "dom.ipc.keepProcessesAlive.web is " +
keepAliveCount +
", boosting " +
"process count temporarily to " +
safeProcessCount
);
await SpecialPowers.pushPrefEnv({ await SpecialPowers.pushPrefEnv({
set: [ set: [
["dom.ipc.processCount", safeProcessCount], ["dom.ipc.processCount", safeProcessCount],
["dom.ipc.processCount.web", safeProcessCount] ["dom.ipc.processCount.web", safeProcessCount],
] ],
}); });
addPerm("http://example.com", "perm1"); addPerm("http://example.com", "perm1");
@ -40,131 +51,284 @@ add_task(async function() {
// NOTE: This permission is a preload permission, so it should be avaliable in the content process from startup. // NOTE: This permission is a preload permission, so it should be avaliable in the content process from startup.
addPerm("https://somerandomwebsite.com", "document"); addPerm("https://somerandomwebsite.com", "document");
await BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" }, async function(aBrowser) { await BrowserTestUtils.withNewTab(
await ContentTask.spawn(aBrowser, null, async function() { { gBrowser, url: "about:blank" },
// Before the load http URIs shouldn't have been sent down yet async function(aBrowser) {
is(Services.perms.testPermission(Services.io.newURI("http://example.com"), await ContentTask.spawn(aBrowser, null, async function() {
"perm1"), // Before the load http URIs shouldn't have been sent down yet
Services.perms.UNKNOWN_ACTION, "perm1-1"); is(
is(Services.perms.testPermission(Services.io.newURI("http://foo.bar.example.com"), Services.perms.testPermission(
"perm2"), Services.io.newURI("http://example.com"),
Services.perms.UNKNOWN_ACTION, "perm2-1"); "perm1"
is(Services.perms.testPermission(Services.io.newURI("about:home"), ),
"perm3"), Services.perms.UNKNOWN_ACTION,
Services.perms.ALLOW_ACTION, "perm3-1"); "perm1-1"
is(Services.perms.testPermission(Services.io.newURI("https://example.com"), );
"perm4"), is(
Services.perms.UNKNOWN_ACTION, "perm4-1"); Services.perms.testPermission(
is(Services.perms.testPermission(Services.io.newURI("https://somerandomwebsite.com"), Services.io.newURI("http://foo.bar.example.com"),
"document"), "perm2"
Services.perms.ALLOW_ACTION, "document-1"); ),
Services.perms.UNKNOWN_ACTION,
"perm2-1"
);
is(
Services.perms.testPermission(
Services.io.newURI("about:home"),
"perm3"
),
Services.perms.ALLOW_ACTION,
"perm3-1"
);
is(
Services.perms.testPermission(
Services.io.newURI("https://example.com"),
"perm4"
),
Services.perms.UNKNOWN_ACTION,
"perm4-1"
);
is(
Services.perms.testPermission(
Services.io.newURI("https://somerandomwebsite.com"),
"document"
),
Services.perms.ALLOW_ACTION,
"document-1"
);
// Perform a load of example.com // Perform a load of example.com
await new Promise(resolve => { await new Promise(resolve => {
let iframe = content.document.createElement('iframe'); let iframe = content.document.createElement("iframe");
iframe.setAttribute('src', 'http://example.com'); iframe.setAttribute("src", "http://example.com");
iframe.onload = resolve; iframe.onload = resolve;
content.document.body.appendChild(iframe); content.document.body.appendChild(iframe);
});
// After the load finishes, we should know about example.com, but not foo.bar.example.com
is(
Services.perms.testPermission(
Services.io.newURI("http://example.com"),
"perm1"
),
Services.perms.ALLOW_ACTION,
"perm1-2"
);
is(
Services.perms.testPermission(
Services.io.newURI("http://foo.bar.example.com"),
"perm2"
),
Services.perms.UNKNOWN_ACTION,
"perm2-2"
);
is(
Services.perms.testPermission(
Services.io.newURI("about:home"),
"perm3"
),
Services.perms.ALLOW_ACTION,
"perm3-2"
);
is(
Services.perms.testPermission(
Services.io.newURI("https://example.com"),
"perm4"
),
Services.perms.UNKNOWN_ACTION,
"perm4-2"
);
is(
Services.perms.testPermission(
Services.io.newURI("https://somerandomwebsite.com"),
"document"
),
Services.perms.ALLOW_ACTION,
"document-2"
);
}); });
// After the load finishes, we should know about example.com, but not foo.bar.example.com addPerm("http://example.com", "newperm1");
is(Services.perms.testPermission(Services.io.newURI("http://example.com"), addPerm("http://foo.bar.example.com", "newperm2");
"perm1"), addPerm("about:home", "newperm3");
Services.perms.ALLOW_ACTION, "perm1-2"); addPerm("https://example.com", "newperm4");
is(Services.perms.testPermission(Services.io.newURI("http://foo.bar.example.com"), addPerm("https://someotherrandomwebsite.com", "document");
"perm2"),
Services.perms.UNKNOWN_ACTION, "perm2-2");
is(Services.perms.testPermission(Services.io.newURI("about:home"),
"perm3"),
Services.perms.ALLOW_ACTION, "perm3-2");
is(Services.perms.testPermission(Services.io.newURI("https://example.com"),
"perm4"),
Services.perms.UNKNOWN_ACTION, "perm4-2");
is(Services.perms.testPermission(Services.io.newURI("https://somerandomwebsite.com"),
"document"),
Services.perms.ALLOW_ACTION, "document-2");
});
addPerm("http://example.com", "newperm1"); await ContentTask.spawn(aBrowser, null, async function() {
addPerm("http://foo.bar.example.com", "newperm2"); // The new permissions should be avaliable, but only for
addPerm("about:home", "newperm3"); // http://example.com, and about:home
addPerm("https://example.com", "newperm4"); is(
addPerm("https://someotherrandomwebsite.com", "document"); Services.perms.testPermission(
Services.io.newURI("http://example.com"),
"perm1"
),
Services.perms.ALLOW_ACTION,
"perm1-3"
);
is(
Services.perms.testPermission(
Services.io.newURI("http://example.com"),
"newperm1"
),
Services.perms.ALLOW_ACTION,
"newperm1-3"
);
is(
Services.perms.testPermission(
Services.io.newURI("http://foo.bar.example.com"),
"perm2"
),
Services.perms.UNKNOWN_ACTION,
"perm2-3"
);
is(
Services.perms.testPermission(
Services.io.newURI("http://foo.bar.example.com"),
"newperm2"
),
Services.perms.UNKNOWN_ACTION,
"newperm2-3"
);
is(
Services.perms.testPermission(
Services.io.newURI("about:home"),
"perm3"
),
Services.perms.ALLOW_ACTION,
"perm3-3"
);
is(
Services.perms.testPermission(
Services.io.newURI("about:home"),
"newperm3"
),
Services.perms.ALLOW_ACTION,
"newperm3-3"
);
is(
Services.perms.testPermission(
Services.io.newURI("https://example.com"),
"perm4"
),
Services.perms.UNKNOWN_ACTION,
"perm4-3"
);
is(
Services.perms.testPermission(
Services.io.newURI("https://example.com"),
"newperm4"
),
Services.perms.UNKNOWN_ACTION,
"newperm4-3"
);
is(
Services.perms.testPermission(
Services.io.newURI("https://somerandomwebsite.com"),
"document"
),
Services.perms.ALLOW_ACTION,
"document-3"
);
is(
Services.perms.testPermission(
Services.io.newURI("https://someotherrandomwebsite.com"),
"document"
),
Services.perms.ALLOW_ACTION,
"otherdocument-3"
);
await ContentTask.spawn(aBrowser, null, async function() { // Loading a subdomain now, on https
// The new permissions should be avaliable, but only for await new Promise(resolve => {
// http://example.com, and about:home let iframe = content.document.createElement("iframe");
is(Services.perms.testPermission(Services.io.newURI("http://example.com"), iframe.setAttribute("src", "https://sub1.test1.example.com");
"perm1"), iframe.onload = resolve;
Services.perms.ALLOW_ACTION, "perm1-3"); content.document.body.appendChild(iframe);
is(Services.perms.testPermission(Services.io.newURI("http://example.com"), });
"newperm1"),
Services.perms.ALLOW_ACTION, "newperm1-3");
is(Services.perms.testPermission(Services.io.newURI("http://foo.bar.example.com"),
"perm2"),
Services.perms.UNKNOWN_ACTION, "perm2-3");
is(Services.perms.testPermission(Services.io.newURI("http://foo.bar.example.com"),
"newperm2"),
Services.perms.UNKNOWN_ACTION, "newperm2-3");
is(Services.perms.testPermission(Services.io.newURI("about:home"),
"perm3"),
Services.perms.ALLOW_ACTION, "perm3-3");
is(Services.perms.testPermission(Services.io.newURI("about:home"),
"newperm3"),
Services.perms.ALLOW_ACTION, "newperm3-3");
is(Services.perms.testPermission(Services.io.newURI("https://example.com"),
"perm4"),
Services.perms.UNKNOWN_ACTION, "perm4-3");
is(Services.perms.testPermission(Services.io.newURI("https://example.com"),
"newperm4"),
Services.perms.UNKNOWN_ACTION, "newperm4-3");
is(Services.perms.testPermission(Services.io.newURI("https://somerandomwebsite.com"),
"document"),
Services.perms.ALLOW_ACTION, "document-3");
is(Services.perms.testPermission(Services.io.newURI("https://someotherrandomwebsite.com"),
"document"),
Services.perms.ALLOW_ACTION, "otherdocument-3");
// Loading a subdomain now, on https // Now that the https subdomain has loaded, we want to make sure that the
await new Promise(resolve => { // permissions are also avaliable for its parent domain, https://example.com!
let iframe = content.document.createElement('iframe'); is(
iframe.setAttribute('src', 'https://sub1.test1.example.com'); Services.perms.testPermission(
iframe.onload = resolve; Services.io.newURI("http://example.com"),
content.document.body.appendChild(iframe); "perm1"
),
Services.perms.ALLOW_ACTION,
"perm1-4"
);
is(
Services.perms.testPermission(
Services.io.newURI("http://example.com"),
"newperm1"
),
Services.perms.ALLOW_ACTION,
"newperm1-4"
);
is(
Services.perms.testPermission(
Services.io.newURI("http://foo.bar.example.com"),
"perm2"
),
Services.perms.UNKNOWN_ACTION,
"perm2-4"
);
is(
Services.perms.testPermission(
Services.io.newURI("http://foo.bar.example.com"),
"newperm2"
),
Services.perms.UNKNOWN_ACTION,
"newperm2-4"
);
is(
Services.perms.testPermission(
Services.io.newURI("about:home"),
"perm3"
),
Services.perms.ALLOW_ACTION,
"perm3-4"
);
is(
Services.perms.testPermission(
Services.io.newURI("about:home"),
"newperm3"
),
Services.perms.ALLOW_ACTION,
"newperm3-4"
);
is(
Services.perms.testPermission(
Services.io.newURI("https://example.com"),
"perm4"
),
Services.perms.ALLOW_ACTION,
"perm4-4"
);
is(
Services.perms.testPermission(
Services.io.newURI("https://example.com"),
"newperm4"
),
Services.perms.ALLOW_ACTION,
"newperm4-4"
);
is(
Services.perms.testPermission(
Services.io.newURI("https://somerandomwebsite.com"),
"document"
),
Services.perms.ALLOW_ACTION,
"document-4"
);
is(
Services.perms.testPermission(
Services.io.newURI("https://someotherrandomwebsite.com"),
"document"
),
Services.perms.ALLOW_ACTION,
"otherdocument-4"
);
}); });
}
// Now that the https subdomain has loaded, we want to make sure that the );
// permissions are also avaliable for its parent domain, https://example.com!
is(Services.perms.testPermission(Services.io.newURI("http://example.com"),
"perm1"),
Services.perms.ALLOW_ACTION, "perm1-4");
is(Services.perms.testPermission(Services.io.newURI("http://example.com"),
"newperm1"),
Services.perms.ALLOW_ACTION, "newperm1-4");
is(Services.perms.testPermission(Services.io.newURI("http://foo.bar.example.com"),
"perm2"),
Services.perms.UNKNOWN_ACTION, "perm2-4");
is(Services.perms.testPermission(Services.io.newURI("http://foo.bar.example.com"),
"newperm2"),
Services.perms.UNKNOWN_ACTION, "newperm2-4");
is(Services.perms.testPermission(Services.io.newURI("about:home"),
"perm3"),
Services.perms.ALLOW_ACTION, "perm3-4");
is(Services.perms.testPermission(Services.io.newURI("about:home"),
"newperm3"),
Services.perms.ALLOW_ACTION, "newperm3-4");
is(Services.perms.testPermission(Services.io.newURI("https://example.com"),
"perm4"),
Services.perms.ALLOW_ACTION, "perm4-4");
is(Services.perms.testPermission(Services.io.newURI("https://example.com"),
"newperm4"),
Services.perms.ALLOW_ACTION, "newperm4-4");
is(Services.perms.testPermission(Services.io.newURI("https://somerandomwebsite.com"),
"document"),
Services.perms.ALLOW_ACTION, "document-4");
is(Services.perms.testPermission(Services.io.newURI("https://someotherrandomwebsite.com"),
"document"),
Services.perms.ALLOW_ACTION, "otherdocument-4");
});
});
}); });

View file

@ -1,19 +1,27 @@
add_task(async function() { add_task(async function() {
// Add a permission for example.com, start a new content process, and make // Add a permission for example.com, start a new content process, and make
// sure that the permission has been sent down. // sure that the permission has been sent down.
Services.perms.add(Services.io.newURI("http://example.com"), Services.perms.add(
"viewsourceTestingPerm", Services.io.newURI("http://example.com"),
Services.perms.ALLOW_ACTION); "viewsourceTestingPerm",
Services.perms.ALLOW_ACTION
);
let tab = await BrowserTestUtils.openNewForegroundTab(gBrowser, let tab = await BrowserTestUtils.openNewForegroundTab(
"view-source:http://example.com", gBrowser,
/* waitForLoad */ true, "view-source:http://example.com",
/* waitForStateStop */ false, /* waitForLoad */ true,
/* forceNewProcess */ true); /* waitForStateStop */ false,
/* forceNewProcess */ true
);
await ContentTask.spawn(tab.linkedBrowser, null, async function() { await ContentTask.spawn(tab.linkedBrowser, null, async function() {
is(Services.perms.testPermission(Services.io.newURI("http://example.com"), is(
"viewsourceTestingPerm"), Services.perms.testPermission(
Services.perms.ALLOW_ACTION); Services.io.newURI("http://example.com"),
"viewsourceTestingPerm"
),
Services.perms.ALLOW_ACTION
);
}); });
BrowserTestUtils.removeTab(tab); BrowserTestUtils.removeTab(tab);
}); });

View file

@ -2,8 +2,8 @@
* http://creativecommons.org/publicdomain/zero/1.0/ * http://creativecommons.org/publicdomain/zero/1.0/
*/ */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); var { NetUtil } = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
// Helper to step a generator function and catch a StopIteration exception. // Helper to step a generator function and catch a StopIteration exception.
function do_run_generator(generator) { function do_run_generator(generator) {
@ -30,4 +30,3 @@ function do_count_enumerator(enumerator) {
} }
return i; return i;
} }

View file

@ -4,22 +4,22 @@
var pm; var pm;
// Create a principal based on the { origin, originAttributes }. // Create a principal based on the { origin, originAttributes }.
function createPrincipal(aOrigin, aOriginAttributes) function createPrincipal(aOrigin, aOriginAttributes) {
{ return Services.scriptSecurityManager.createCodebasePrincipal(
return Services.scriptSecurityManager.createCodebasePrincipal(NetUtil.newURI(aOrigin), aOriginAttributes); NetUtil.newURI(aOrigin),
aOriginAttributes
);
} }
// Return the data required by 'clear-origin-attributes-data' notification. // Return the data required by 'clear-origin-attributes-data' notification.
function getData(aPattern) function getData(aPattern) {
{
return JSON.stringify(aPattern); return JSON.stringify(aPattern);
} }
// Use aEntries to create principals, add permissions to them and check that they have them. // Use aEntries to create principals, add permissions to them and check that they have them.
// Then, it is notifying 'clear-origin-attributes-data' with the given aData and check if the permissions // Then, it is notifying 'clear-origin-attributes-data' with the given aData and check if the permissions
// of principals[i] matches the permission in aResults[i]. // of principals[i] matches the permission in aResults[i].
function test(aEntries, aData, aResults) function test(aEntries, aData, aResults) {
{
let principals = []; let principals = [];
for (entry of aEntries) { for (entry of aEntries) {
@ -27,40 +27,68 @@ function test(aEntries, aData, aResults)
} }
for (principal of principals) { for (principal of principals) {
Assert.equal(pm.testPermissionFromPrincipal(principal, "test/clear-origin"), pm.UNKNOWN_ACTION); Assert.equal(
pm.addFromPrincipal(principal, "test/clear-origin", pm.ALLOW_ACTION, pm.EXPIRE_NEVER, 0); pm.testPermissionFromPrincipal(principal, "test/clear-origin"),
Assert.equal(pm.testPermissionFromPrincipal(principal, "test/clear-origin"), pm.ALLOW_ACTION); pm.UNKNOWN_ACTION
);
pm.addFromPrincipal(
principal,
"test/clear-origin",
pm.ALLOW_ACTION,
pm.EXPIRE_NEVER,
0
);
Assert.equal(
pm.testPermissionFromPrincipal(principal, "test/clear-origin"),
pm.ALLOW_ACTION
);
} }
Services.obs.notifyObservers(null, 'clear-origin-attributes-data', aData); Services.obs.notifyObservers(null, "clear-origin-attributes-data", aData);
var length = aEntries.length; var length = aEntries.length;
for (let i=0; i<length; ++i) { for (let i = 0; i < length; ++i) {
Assert.equal(pm.testPermissionFromPrincipal(principals[i], 'test/clear-origin'), aResults[i]); Assert.equal(
pm.testPermissionFromPrincipal(principals[i], "test/clear-origin"),
aResults[i]
);
// Remove allowed actions. // Remove allowed actions.
if (aResults[i] == pm.ALLOW_ACTION) { if (aResults[i] == pm.ALLOW_ACTION) {
pm.removeFromPrincipal(principals[i], 'test/clear-origin'); pm.removeFromPrincipal(principals[i], "test/clear-origin");
} }
} }
} }
function run_test() function run_test() {
{
do_get_profile(); do_get_profile();
pm = Cc["@mozilla.org/permissionmanager;1"] pm = Cc["@mozilla.org/permissionmanager;1"].getService(
.getService(Ci.nsIPermissionManager); Ci.nsIPermissionManager
);
let entries = [ let entries = [
{ origin: 'http://example.com', originAttributes: {} }, { origin: "http://example.com", originAttributes: {} },
{ origin: 'http://example.com', originAttributes: { inIsolatedMozBrowser: true } }, {
origin: "http://example.com",
originAttributes: { inIsolatedMozBrowser: true },
},
]; ];
// In that case, all permissions should be removed. // In that case, all permissions should be removed.
test(entries, getData({}), [ pm.UNKNOWN_ACTION, pm.UNKNOWN_ACTION, pm.ALLOW_ACTION, pm.ALLOW_ACTION ]); test(entries, getData({}), [
pm.UNKNOWN_ACTION,
pm.UNKNOWN_ACTION,
pm.ALLOW_ACTION,
pm.ALLOW_ACTION,
]);
// In that case, only the permissions related to a browserElement should be removed. // In that case, only the permissions related to a browserElement should be removed.
// All the other permissions should stay. // All the other permissions should stay.
test(entries, getData({ inIsolatedMozBrowser: true}), [ pm.ALLOW_ACTION, pm.UNKNOWN_ACTION, pm.ALLOW_ACTION, pm.ALLOW_ACTION ]); test(entries, getData({ inIsolatedMozBrowser: true }), [
pm.ALLOW_ACTION,
pm.UNKNOWN_ACTION,
pm.ALLOW_ACTION,
pm.ALLOW_ACTION,
]);
} }

View file

@ -5,33 +5,65 @@ function run_test() {
let uri = Services.io.newURI("https://example.org"); let uri = Services.io.newURI("https://example.org");
// Check that without a pref the default return value is UNKNOWN. // Check that without a pref the default return value is UNKNOWN.
Assert.equal(Services.perms.testPermission(uri, "camera"), Services.perms.UNKNOWN_ACTION); Assert.equal(
Services.perms.testPermission(uri, "camera"),
Services.perms.UNKNOWN_ACTION
);
// Check that the default return value changed after setting the pref. // Check that the default return value changed after setting the pref.
Services.prefs.setIntPref("permissions.default.camera", Services.perms.DENY_ACTION); Services.prefs.setIntPref(
Assert.equal(Services.perms.testPermission(uri, "camera"), Services.perms.DENY_ACTION); "permissions.default.camera",
Services.perms.DENY_ACTION
);
Assert.equal(
Services.perms.testPermission(uri, "camera"),
Services.perms.DENY_ACTION
);
// Check that functions that do not directly return a permission value still // Check that functions that do not directly return a permission value still
// consider the permission as being set to its default. // consider the permission as being set to its default.
Assert.equal(null, Services.perms.getPermissionObjectForURI(uri, "camera", false)); Assert.equal(
null,
Services.perms.getPermissionObjectForURI(uri, "camera", false)
);
// Check that other permissions still return UNKNOWN. // Check that other permissions still return UNKNOWN.
Assert.equal(Services.perms.testPermission(uri, "geo"), Services.perms.UNKNOWN_ACTION); Assert.equal(
Services.perms.testPermission(uri, "geo"),
Services.perms.UNKNOWN_ACTION
);
// Check that the default return value changed after changing the pref. // Check that the default return value changed after changing the pref.
Services.prefs.setIntPref("permissions.default.camera", Services.perms.ALLOW_ACTION); Services.prefs.setIntPref(
Assert.equal(Services.perms.testPermission(uri, "camera"), Services.perms.ALLOW_ACTION); "permissions.default.camera",
Services.perms.ALLOW_ACTION
);
Assert.equal(
Services.perms.testPermission(uri, "camera"),
Services.perms.ALLOW_ACTION
);
// Check that the preference is ignored if there is a value. // Check that the preference is ignored if there is a value.
Services.perms.add(uri, "camera", Services.perms.DENY_ACTION); Services.perms.add(uri, "camera", Services.perms.DENY_ACTION);
Assert.equal(Services.perms.testPermission(uri, "camera"), Services.perms.DENY_ACTION); Assert.equal(
Assert.ok(Services.perms.getPermissionObjectForURI(uri, "camera", false) != null); Services.perms.testPermission(uri, "camera"),
Services.perms.DENY_ACTION
);
Assert.ok(
Services.perms.getPermissionObjectForURI(uri, "camera", false) != null
);
// The preference should be honored again, after resetting the permissions. // The preference should be honored again, after resetting the permissions.
Services.perms.removeAll(); Services.perms.removeAll();
Assert.equal(Services.perms.testPermission(uri, "camera"), Services.perms.ALLOW_ACTION); Assert.equal(
Services.perms.testPermission(uri, "camera"),
Services.perms.ALLOW_ACTION
);
// Should be UNKNOWN after clearing the pref. // Should be UNKNOWN after clearing the pref.
Services.prefs.clearUserPref("permissions.default.camera"); Services.prefs.clearUserPref("permissions.default.camera");
Assert.equal(Services.perms.testPermission(uri, "camera"), Services.perms.UNKNOWN_ACTION); Assert.equal(
Services.perms.testPermission(uri, "camera"),
Services.perms.UNKNOWN_ACTION
);
} }

View file

@ -23,63 +23,120 @@ add_task(async function do_test() {
file.append("test_default_permissions"); file.append("test_default_permissions");
// write our test data to it. // write our test data to it.
let ostream = Cc["@mozilla.org/network/file-output-stream;1"]. let ostream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(
createInstance(Ci.nsIFileOutputStream); Ci.nsIFileOutputStream
);
ostream.init(file, -1, 0o666, 0); ostream.init(file, -1, 0o666, 0);
let conv = Cc["@mozilla.org/intl/converter-output-stream;1"]. let conv = Cc["@mozilla.org/intl/converter-output-stream;1"].createInstance(
createInstance(Ci.nsIConverterOutputStream); Ci.nsIConverterOutputStream
);
conv.init(ostream, "UTF-8"); conv.init(ostream, "UTF-8");
conv.writeString("# this is a comment\n"); conv.writeString("# this is a comment\n");
conv.writeString("\n"); // a blank line! conv.writeString("\n"); // a blank line!
conv.writeString("host\t" + TEST_PERMISSION + "\t1\t" + TEST_ORIGIN.host + "\n"); conv.writeString(
conv.writeString("host\t" + TEST_PERMISSION + "\t1\t" + TEST_ORIGIN_2.host + "\n"); "host\t" + TEST_PERMISSION + "\t1\t" + TEST_ORIGIN.host + "\n"
conv.writeString("origin\t" + TEST_PERMISSION + "\t1\t" + TEST_ORIGIN_3.spec + "\n"); );
conv.writeString("origin\t" + TEST_PERMISSION + "\t1\t" + TEST_ORIGIN.spec + "^inBrowser=1\n"); conv.writeString(
"host\t" + TEST_PERMISSION + "\t1\t" + TEST_ORIGIN_2.host + "\n"
);
conv.writeString(
"origin\t" + TEST_PERMISSION + "\t1\t" + TEST_ORIGIN_3.spec + "\n"
);
conv.writeString(
"origin\t" + TEST_PERMISSION + "\t1\t" + TEST_ORIGIN.spec + "^inBrowser=1\n"
);
ostream.close(); ostream.close();
// Set the preference used by the permission manager so the file is read. // Set the preference used by the permission manager so the file is read.
Services.prefs.setCharPref("permissions.manager.defaultsUrl", "file://" + file.path); Services.prefs.setCharPref(
"permissions.manager.defaultsUrl",
"file://" + file.path
);
// This will force the permission-manager to reload the data. // This will force the permission-manager to reload the data.
Services.obs.notifyObservers(null, "testonly-reload-permissions-from-disk"); Services.obs.notifyObservers(null, "testonly-reload-permissions-from-disk");
let pm = Cc["@mozilla.org/permissionmanager;1"]. let pm = Cc["@mozilla.org/permissionmanager;1"].getService(
getService(Ci.nsIPermissionManager); Ci.nsIPermissionManager
);
// test the default permission was applied. // test the default permission was applied.
let principal = Services.scriptSecurityManager.createCodebasePrincipal(TEST_ORIGIN, {}); let principal = Services.scriptSecurityManager.createCodebasePrincipal(
let principalHttps = Services.scriptSecurityManager.createCodebasePrincipal(TEST_ORIGIN_HTTPS, {}); TEST_ORIGIN,
let principal2 = Services.scriptSecurityManager.createCodebasePrincipal(TEST_ORIGIN_2, {}); {}
let principal3 = Services.scriptSecurityManager.createCodebasePrincipal(TEST_ORIGIN_3, {}); );
let principalHttps = Services.scriptSecurityManager.createCodebasePrincipal(
TEST_ORIGIN_HTTPS,
{}
);
let principal2 = Services.scriptSecurityManager.createCodebasePrincipal(
TEST_ORIGIN_2,
{}
);
let principal3 = Services.scriptSecurityManager.createCodebasePrincipal(
TEST_ORIGIN_3,
{}
);
let attrs = {inIsolatedMozBrowser: true}; let attrs = { inIsolatedMozBrowser: true };
let principal4 = Services.scriptSecurityManager.createCodebasePrincipal(TEST_ORIGIN, attrs); let principal4 = Services.scriptSecurityManager.createCodebasePrincipal(
let principal5 = Services.scriptSecurityManager.createCodebasePrincipal(TEST_ORIGIN_3, attrs); TEST_ORIGIN,
attrs
);
let principal5 = Services.scriptSecurityManager.createCodebasePrincipal(
TEST_ORIGIN_3,
attrs
);
attrs = {userContextId: 1}; attrs = { userContextId: 1 };
let principal6 = Services.scriptSecurityManager.createCodebasePrincipal(TEST_ORIGIN, attrs); let principal6 = Services.scriptSecurityManager.createCodebasePrincipal(
attrs = {firstPartyDomain: "cnn.com"}; TEST_ORIGIN,
let principal7 = Services.scriptSecurityManager.createCodebasePrincipal(TEST_ORIGIN, attrs); attrs
attrs = {userContextId: 1, firstPartyDomain: "cnn.com"}; );
let principal8 = Services.scriptSecurityManager.createCodebasePrincipal(TEST_ORIGIN, attrs); attrs = { firstPartyDomain: "cnn.com" };
let principal7 = Services.scriptSecurityManager.createCodebasePrincipal(
TEST_ORIGIN,
attrs
);
attrs = { userContextId: 1, firstPartyDomain: "cnn.com" };
let principal8 = Services.scriptSecurityManager.createCodebasePrincipal(
TEST_ORIGIN,
attrs
);
Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)); Ci.nsIPermissionManager.ALLOW_ACTION,
Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)
pm.testPermissionFromPrincipal(principalHttps, TEST_PERMISSION)); );
Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal3, TEST_PERMISSION)); Ci.nsIPermissionManager.ALLOW_ACTION,
Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, pm.testPermissionFromPrincipal(principalHttps, TEST_PERMISSION)
pm.testPermissionFromPrincipal(principal4, TEST_PERMISSION)); );
Assert.equal(
Ci.nsIPermissionManager.ALLOW_ACTION,
pm.testPermissionFromPrincipal(principal3, TEST_PERMISSION)
);
Assert.equal(
Ci.nsIPermissionManager.ALLOW_ACTION,
pm.testPermissionFromPrincipal(principal4, TEST_PERMISSION)
);
// Didn't add // Didn't add
Assert.equal(Ci.nsIPermissionManager.UNKNOWN_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal5, TEST_PERMISSION)); Ci.nsIPermissionManager.UNKNOWN_ACTION,
pm.testPermissionFromPrincipal(principal5, TEST_PERMISSION)
);
// the permission should exist in the enumerator. // the permission should exist in the enumerator.
Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, findCapabilityViaEnum(TEST_ORIGIN)); Assert.equal(
Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, findCapabilityViaEnum(TEST_ORIGIN_3)); Ci.nsIPermissionManager.ALLOW_ACTION,
findCapabilityViaEnum(TEST_ORIGIN)
);
Assert.equal(
Ci.nsIPermissionManager.ALLOW_ACTION,
findCapabilityViaEnum(TEST_ORIGIN_3)
);
// but should not have been written to the DB // but should not have been written to the DB
await checkCapabilityViaDB(null); await checkCapabilityViaDB(null);
@ -87,29 +144,45 @@ add_task(async function do_test() {
// remove all should not throw and the default should remain // remove all should not throw and the default should remain
pm.removeAll(); pm.removeAll();
Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)); Ci.nsIPermissionManager.ALLOW_ACTION,
Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)
pm.testPermissionFromPrincipal(principal3, TEST_PERMISSION)); );
Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal4, TEST_PERMISSION)); Ci.nsIPermissionManager.ALLOW_ACTION,
pm.testPermissionFromPrincipal(principal3, TEST_PERMISSION)
);
Assert.equal(
Ci.nsIPermissionManager.ALLOW_ACTION,
pm.testPermissionFromPrincipal(principal4, TEST_PERMISSION)
);
// make sure principals with userContextId use the same permissions // make sure principals with userContextId use the same permissions
Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal6, TEST_PERMISSION)); Ci.nsIPermissionManager.ALLOW_ACTION,
pm.testPermissionFromPrincipal(principal6, TEST_PERMISSION)
);
// make sure principals with a firstPartyDomain use different permissions // make sure principals with a firstPartyDomain use different permissions
Assert.equal(Ci.nsIPermissionManager.UNKNOWN_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal7, TEST_PERMISSION)); Ci.nsIPermissionManager.UNKNOWN_ACTION,
Assert.equal(Ci.nsIPermissionManager.UNKNOWN_ACTION, pm.testPermissionFromPrincipal(principal7, TEST_PERMISSION)
pm.testPermissionFromPrincipal(principal8, TEST_PERMISSION)); );
Assert.equal(
Ci.nsIPermissionManager.UNKNOWN_ACTION,
pm.testPermissionFromPrincipal(principal8, TEST_PERMISSION)
);
// Asking for this permission to be removed should result in that permission // Asking for this permission to be removed should result in that permission
// having UNKNOWN_ACTION // having UNKNOWN_ACTION
pm.removeFromPrincipal(principal, TEST_PERMISSION); pm.removeFromPrincipal(principal, TEST_PERMISSION);
Assert.equal(Ci.nsIPermissionManager.UNKNOWN_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)); Ci.nsIPermissionManager.UNKNOWN_ACTION,
pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)
);
// make sure principals with userContextId or firstPartyDomain use the same permissions // make sure principals with userContextId or firstPartyDomain use the same permissions
Assert.equal(Ci.nsIPermissionManager.UNKNOWN_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal6, TEST_PERMISSION)); Ci.nsIPermissionManager.UNKNOWN_ACTION,
pm.testPermissionFromPrincipal(principal6, TEST_PERMISSION)
);
// and we should have this UNKNOWN_ACTION reflected in the DB // and we should have this UNKNOWN_ACTION reflected in the DB
await checkCapabilityViaDB(Ci.nsIPermissionManager.UNKNOWN_ACTION); await checkCapabilityViaDB(Ci.nsIPermissionManager.UNKNOWN_ACTION);
// but the permission should *not* appear in the enumerator. // but the permission should *not* appear in the enumerator.
@ -118,51 +191,83 @@ add_task(async function do_test() {
// and a subsequent RemoveAll should restore the default // and a subsequent RemoveAll should restore the default
pm.removeAll(); pm.removeAll();
Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)); Ci.nsIPermissionManager.ALLOW_ACTION,
pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)
);
// make sure principals with userContextId use the same permissions // make sure principals with userContextId use the same permissions
Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal6, TEST_PERMISSION)); Ci.nsIPermissionManager.ALLOW_ACTION,
pm.testPermissionFromPrincipal(principal6, TEST_PERMISSION)
);
// make sure principals with firstPartyDomain use different permissions // make sure principals with firstPartyDomain use different permissions
Assert.equal(Ci.nsIPermissionManager.UNKNOWN_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal7, TEST_PERMISSION)); Ci.nsIPermissionManager.UNKNOWN_ACTION,
Assert.equal(Ci.nsIPermissionManager.UNKNOWN_ACTION, pm.testPermissionFromPrincipal(principal7, TEST_PERMISSION)
pm.testPermissionFromPrincipal(principal8, TEST_PERMISSION)); );
Assert.equal(
Ci.nsIPermissionManager.UNKNOWN_ACTION,
pm.testPermissionFromPrincipal(principal8, TEST_PERMISSION)
);
// and allow it to again be seen in the enumerator. // and allow it to again be seen in the enumerator.
Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, findCapabilityViaEnum()); Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, findCapabilityViaEnum());
// now explicitly add a permission - this too should override the default. // now explicitly add a permission - this too should override the default.
pm.addFromPrincipal(principal, TEST_PERMISSION, Ci.nsIPermissionManager.DENY_ACTION); pm.addFromPrincipal(
principal,
TEST_PERMISSION,
Ci.nsIPermissionManager.DENY_ACTION
);
// it should be reflected in a permission check, in the enumerator and the DB // it should be reflected in a permission check, in the enumerator and the DB
Assert.equal(Ci.nsIPermissionManager.DENY_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)); Ci.nsIPermissionManager.DENY_ACTION,
pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)
);
// make sure principals with userContextId use the same permissions // make sure principals with userContextId use the same permissions
Assert.equal(Ci.nsIPermissionManager.DENY_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal6, TEST_PERMISSION)); Ci.nsIPermissionManager.DENY_ACTION,
pm.testPermissionFromPrincipal(principal6, TEST_PERMISSION)
);
// make sure principals with firstPartyDomain use different permissions // make sure principals with firstPartyDomain use different permissions
Assert.equal(Ci.nsIPermissionManager.UNKNOWN_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal7, TEST_PERMISSION)); Ci.nsIPermissionManager.UNKNOWN_ACTION,
Assert.equal(Ci.nsIPermissionManager.UNKNOWN_ACTION, pm.testPermissionFromPrincipal(principal7, TEST_PERMISSION)
pm.testPermissionFromPrincipal(principal8, TEST_PERMISSION)); );
Assert.equal(
Ci.nsIPermissionManager.UNKNOWN_ACTION,
pm.testPermissionFromPrincipal(principal8, TEST_PERMISSION)
);
Assert.equal(Ci.nsIPermissionManager.DENY_ACTION, findCapabilityViaEnum()); Assert.equal(Ci.nsIPermissionManager.DENY_ACTION, findCapabilityViaEnum());
await checkCapabilityViaDB(Ci.nsIPermissionManager.DENY_ACTION); await checkCapabilityViaDB(Ci.nsIPermissionManager.DENY_ACTION);
// explicitly add a different permission - in this case we are no longer // explicitly add a different permission - in this case we are no longer
// replacing the default, but instead replacing the replacement! // replacing the default, but instead replacing the replacement!
pm.addFromPrincipal(principal, TEST_PERMISSION, Ci.nsIPermissionManager.PROMPT_ACTION); pm.addFromPrincipal(
principal,
TEST_PERMISSION,
Ci.nsIPermissionManager.PROMPT_ACTION
);
// it should be reflected in a permission check, in the enumerator and the DB // it should be reflected in a permission check, in the enumerator and the DB
Assert.equal(Ci.nsIPermissionManager.PROMPT_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)); Ci.nsIPermissionManager.PROMPT_ACTION,
pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)
);
// make sure principals with userContextId use the same permissions // make sure principals with userContextId use the same permissions
Assert.equal(Ci.nsIPermissionManager.PROMPT_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal6, TEST_PERMISSION)); Ci.nsIPermissionManager.PROMPT_ACTION,
pm.testPermissionFromPrincipal(principal6, TEST_PERMISSION)
);
// make sure principals with firstPartyDomain use different permissions // make sure principals with firstPartyDomain use different permissions
Assert.equal(Ci.nsIPermissionManager.UNKNOWN_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal7, TEST_PERMISSION)); Ci.nsIPermissionManager.UNKNOWN_ACTION,
Assert.equal(Ci.nsIPermissionManager.UNKNOWN_ACTION, pm.testPermissionFromPrincipal(principal7, TEST_PERMISSION)
pm.testPermissionFromPrincipal(principal8, TEST_PERMISSION)); );
Assert.equal(
Ci.nsIPermissionManager.UNKNOWN_ACTION,
pm.testPermissionFromPrincipal(principal8, TEST_PERMISSION)
);
Assert.equal(Ci.nsIPermissionManager.PROMPT_ACTION, findCapabilityViaEnum()); Assert.equal(Ci.nsIPermissionManager.PROMPT_ACTION, findCapabilityViaEnum());
await checkCapabilityViaDB(Ci.nsIPermissionManager.PROMPT_ACTION); await checkCapabilityViaDB(Ci.nsIPermissionManager.PROMPT_ACTION);
@ -171,16 +276,26 @@ add_task(async function do_test() {
pm.removeAll(); // ensure only defaults are there. pm.removeAll(); // ensure only defaults are there.
// default for both principals is allow. // default for both principals is allow.
Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)); Ci.nsIPermissionManager.ALLOW_ACTION,
Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)
pm.testPermissionFromPrincipal(principal2, TEST_PERMISSION)); );
Assert.equal(
Ci.nsIPermissionManager.ALLOW_ACTION,
pm.testPermissionFromPrincipal(principal2, TEST_PERMISSION)
);
// Add a default override for TEST_ORIGIN_2 - this one should *not* be // Add a default override for TEST_ORIGIN_2 - this one should *not* be
// restored in removeAllSince() // restored in removeAllSince()
pm.addFromPrincipal(principal2, TEST_PERMISSION, Ci.nsIPermissionManager.DENY_ACTION); pm.addFromPrincipal(
Assert.equal(Ci.nsIPermissionManager.DENY_ACTION, principal2,
pm.testPermissionFromPrincipal(principal2, TEST_PERMISSION)); TEST_PERMISSION,
Ci.nsIPermissionManager.DENY_ACTION
);
Assert.equal(
Ci.nsIPermissionManager.DENY_ACTION,
pm.testPermissionFromPrincipal(principal2, TEST_PERMISSION)
);
await promiseTimeout(20); await promiseTimeout(20);
let since = Number(Date.now()); let since = Number(Date.now());
@ -188,21 +303,31 @@ add_task(async function do_test() {
// explicitly add a permission which overrides the default for the first // explicitly add a permission which overrides the default for the first
// principal - this one *should* be removed by removeAllSince. // principal - this one *should* be removed by removeAllSince.
pm.addFromPrincipal(principal, TEST_PERMISSION, Ci.nsIPermissionManager.DENY_ACTION); pm.addFromPrincipal(
Assert.equal(Ci.nsIPermissionManager.DENY_ACTION, principal,
pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)); TEST_PERMISSION,
Ci.nsIPermissionManager.DENY_ACTION
);
Assert.equal(
Ci.nsIPermissionManager.DENY_ACTION,
pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)
);
// do a removeAllSince. // do a removeAllSince.
pm.removeAllSince(since); pm.removeAllSince(since);
// the default for the first principal should re-appear as we modified it // the default for the first principal should re-appear as we modified it
// later then |since| // later then |since|
Assert.equal(Ci.nsIPermissionManager.ALLOW_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)); Ci.nsIPermissionManager.ALLOW_ACTION,
pm.testPermissionFromPrincipal(principal, TEST_PERMISSION)
);
// but the permission for principal2 should remain as we added that before |since|. // but the permission for principal2 should remain as we added that before |since|.
Assert.equal(Ci.nsIPermissionManager.DENY_ACTION, Assert.equal(
pm.testPermissionFromPrincipal(principal2, TEST_PERMISSION)); Ci.nsIPermissionManager.DENY_ACTION,
pm.testPermissionFromPrincipal(principal2, TEST_PERMISSION)
);
// remove the temp file we created. // remove the temp file we created.
file.remove(false); file.remove(false);
@ -214,8 +339,7 @@ add_task(async function do_test() {
function findCapabilityViaEnum(origin = TEST_ORIGIN, type = TEST_PERMISSION) { function findCapabilityViaEnum(origin = TEST_ORIGIN, type = TEST_PERMISSION) {
let result = undefined; let result = undefined;
for (let perm of Services.perms.enumerator) { for (let perm of Services.perms.enumerator) {
if (perm.matchesURI(origin, true) && if (perm.matchesURI(origin, true) && perm.type == type) {
perm.type == type) {
if (result !== undefined) { if (result !== undefined) {
// we've already found one previously - that's bad! // we've already found one previously - that's bad!
do_throw("enumerator found multiple entries"); do_throw("enumerator found multiple entries");
@ -231,7 +355,11 @@ function findCapabilityViaEnum(origin = TEST_ORIGIN, type = TEST_PERMISSION) {
// distinct possibility exists that our checking of the DB will happen before // distinct possibility exists that our checking of the DB will happen before
// the permission manager update has completed - so we just retry a few times. // the permission manager update has completed - so we just retry a few times.
// Returns a promise. // Returns a promise.
function checkCapabilityViaDB(expected, origin = TEST_ORIGIN, type = TEST_PERMISSION) { function checkCapabilityViaDB(
expected,
origin = TEST_ORIGIN,
type = TEST_PERMISSION
) {
return new Promise(resolve => { return new Promise(resolve => {
let count = 0; let count = 0;
let max = 20; let max = 20;
@ -246,13 +374,17 @@ function checkCapabilityViaDB(expected, origin = TEST_ORIGIN, type = TEST_PERMIS
// value isn't correct - see if we've retried enough // value isn't correct - see if we've retried enough
if (count++ == max) { if (count++ == max) {
// the do_check_eq() below will fail - which is what we want. // the do_check_eq() below will fail - which is what we want.
Assert.equal(got, expected, "The database wasn't updated with the expected value"); Assert.equal(
got,
expected,
"The database wasn't updated with the expected value"
);
resolve(); resolve();
return; return;
} }
// we can retry... // we can retry...
do_timeout(100, do_check); do_timeout(100, do_check);
} };
do_check(); do_check();
}); });
} }
@ -261,19 +393,24 @@ function checkCapabilityViaDB(expected, origin = TEST_ORIGIN, type = TEST_PERMIS
// value (ie, the "capability" in nsIPermission parlance) or null if it can't // value (ie, the "capability" in nsIPermission parlance) or null if it can't
// be found. // be found.
function findCapabilityViaDB(origin = TEST_ORIGIN, type = TEST_PERMISSION) { function findCapabilityViaDB(origin = TEST_ORIGIN, type = TEST_PERMISSION) {
let principal = Services.scriptSecurityManager.createCodebasePrincipal(origin, {}); let principal = Services.scriptSecurityManager.createCodebasePrincipal(
origin,
{}
);
let originStr = principal.origin; let originStr = principal.origin;
let file = Services.dirsvc.get("ProfD", Ci.nsIFile); let file = Services.dirsvc.get("ProfD", Ci.nsIFile);
file.append("permissions.sqlite"); file.append("permissions.sqlite");
let storage = Cc["@mozilla.org/storage/service;1"] let storage = Cc["@mozilla.org/storage/service;1"].getService(
.getService(Ci.mozIStorageService); Ci.mozIStorageService
);
let connection = storage.openDatabase(file); let connection = storage.openDatabase(file);
let query = connection.createStatement( let query = connection.createStatement(
"SELECT permission FROM moz_perms WHERE origin = :origin AND type = :type"); "SELECT permission FROM moz_perms WHERE origin = :origin AND type = :type"
);
query.bindByName("origin", originStr); query.bindByName("origin", originStr);
query.bindByName("type", type); query.bindByName("type", type);
@ -284,7 +421,7 @@ function findCapabilityViaDB(origin = TEST_ORIGIN, type = TEST_PERMISSION) {
let result = query.getInt32(0); let result = query.getInt32(0);
if (query.executeStep()) { if (query.executeStep()) {
// this is bad - we never expect more than 1 row here. // this is bad - we never expect more than 1 row here.
do_throw("More than 1 row found!") do_throw("More than 1 row found!");
} }
return result; return result;
} }

View file

@ -10,8 +10,7 @@ function run_test() {
test_generator.next(); test_generator.next();
} }
function continue_test() function continue_test() {
{
do_run_generator(test_generator); do_run_generator(test_generator);
} }
@ -21,62 +20,181 @@ function* do_run_test() {
let pm = Services.perms; let pm = Services.perms;
let permURI = NetUtil.newURI("http://example.com"); let permURI = NetUtil.newURI("http://example.com");
let principal = Services.scriptSecurityManager.createCodebasePrincipal(permURI, {}); let principal = Services.scriptSecurityManager.createCodebasePrincipal(
permURI,
{}
);
let now = Number(Date.now()); let now = Number(Date.now());
// add a permission with *now* expiration // add a permission with *now* expiration
pm.addFromPrincipal(principal, "test/expiration-perm-exp", 1, pm.EXPIRE_TIME, now); pm.addFromPrincipal(
pm.addFromPrincipal(principal, "test/expiration-session-exp", 1, pm.EXPIRE_SESSION, now); principal,
"test/expiration-perm-exp",
1,
pm.EXPIRE_TIME,
now
);
pm.addFromPrincipal(
principal,
"test/expiration-session-exp",
1,
pm.EXPIRE_SESSION,
now
);
// add a permission with future expiration (100 milliseconds) // add a permission with future expiration (100 milliseconds)
pm.addFromPrincipal(principal, "test/expiration-perm-exp2", 1, pm.EXPIRE_TIME, now + 100); pm.addFromPrincipal(
pm.addFromPrincipal(principal, "test/expiration-session-exp2", 1, pm.EXPIRE_SESSION, now + 100); principal,
"test/expiration-perm-exp2",
1,
pm.EXPIRE_TIME,
now + 100
);
pm.addFromPrincipal(
principal,
"test/expiration-session-exp2",
1,
pm.EXPIRE_SESSION,
now + 100
);
// add a permission with future expiration (1000 seconds) // add a permission with future expiration (1000 seconds)
pm.addFromPrincipal(principal, "test/expiration-perm-exp3", 1, pm.EXPIRE_TIME, now + 1e6); pm.addFromPrincipal(
pm.addFromPrincipal(principal, "test/expiration-session-exp3", 1, pm.EXPIRE_SESSION, now + 1e6); principal,
"test/expiration-perm-exp3",
1,
pm.EXPIRE_TIME,
now + 1e6
);
pm.addFromPrincipal(
principal,
"test/expiration-session-exp3",
1,
pm.EXPIRE_SESSION,
now + 1e6
);
// add a permission without expiration // add a permission without expiration
pm.addFromPrincipal(principal, "test/expiration-perm-nexp", 1, pm.EXPIRE_NEVER, 0); pm.addFromPrincipal(
principal,
"test/expiration-perm-nexp",
1,
pm.EXPIRE_NEVER,
0
);
// add a permission for renewal // add a permission for renewal
pm.addFromPrincipal(principal, "test/expiration-perm-renewable", 1, pm.EXPIRE_TIME, now + 100); pm.addFromPrincipal(
pm.addFromPrincipal(principal, "test/expiration-session-renewable", 1, pm.EXPIRE_SESSION, now + 100); principal,
"test/expiration-perm-renewable",
1,
pm.EXPIRE_TIME,
now + 100
);
pm.addFromPrincipal(
principal,
"test/expiration-session-renewable",
1,
pm.EXPIRE_SESSION,
now + 100
);
// And immediately renew them with longer timeouts // And immediately renew them with longer timeouts
pm.updateExpireTime(principal, "test/expiration-perm-renewable", true, now + 100, now + 1e6); pm.updateExpireTime(
pm.updateExpireTime(principal, "test/expiration-session-renewable", true, now + 1e6, now + 100); principal,
"test/expiration-perm-renewable",
true,
now + 100,
now + 1e6
);
pm.updateExpireTime(
principal,
"test/expiration-session-renewable",
true,
now + 1e6,
now + 100
);
// check that the second two haven't expired yet // check that the second two haven't expired yet
Assert.equal(1, pm.testPermissionFromPrincipal(principal, "test/expiration-perm-exp3")); Assert.equal(
Assert.equal(1, pm.testPermissionFromPrincipal(principal, "test/expiration-session-exp3")); 1,
Assert.equal(1, pm.testPermissionFromPrincipal(principal, "test/expiration-perm-nexp")); pm.testPermissionFromPrincipal(principal, "test/expiration-perm-exp3")
Assert.equal(1, pm.testPermissionFromPrincipal(principal, "test/expiration-perm-renewable")); );
Assert.equal(1, pm.testPermissionFromPrincipal(principal, "test/expiration-session-renewable")); Assert.equal(
1,
pm.testPermissionFromPrincipal(principal, "test/expiration-session-exp3")
);
Assert.equal(
1,
pm.testPermissionFromPrincipal(principal, "test/expiration-perm-nexp")
);
Assert.equal(
1,
pm.testPermissionFromPrincipal(principal, "test/expiration-perm-renewable")
);
Assert.equal(
1,
pm.testPermissionFromPrincipal(
principal,
"test/expiration-session-renewable"
)
);
// ... and the first one has // ... and the first one has
do_timeout(10, continue_test); do_timeout(10, continue_test);
yield; yield;
Assert.equal(0, pm.testPermissionFromPrincipal(principal, "test/expiration-perm-exp")); Assert.equal(
Assert.equal(0, pm.testPermissionFromPrincipal(principal, "test/expiration-session-exp")); 0,
pm.testPermissionFromPrincipal(principal, "test/expiration-perm-exp")
);
Assert.equal(
0,
pm.testPermissionFromPrincipal(principal, "test/expiration-session-exp")
);
// ... and that the short-term one will // ... and that the short-term one will
do_timeout(200, continue_test); do_timeout(200, continue_test);
yield; yield;
Assert.equal(0, pm.testPermissionFromPrincipal(principal, "test/expiration-perm-exp2")); Assert.equal(
Assert.equal(0, pm.testPermissionFromPrincipal(principal, "test/expiration-session-exp2")); 0,
pm.testPermissionFromPrincipal(principal, "test/expiration-perm-exp2")
);
Assert.equal(
0,
pm.testPermissionFromPrincipal(principal, "test/expiration-session-exp2")
);
// Check that .getPermission returns a matching result // Check that .getPermission returns a matching result
Assert.equal(null, pm.getPermissionObject(principal, "test/expiration-perm-exp", false)); Assert.equal(
Assert.equal(null, pm.getPermissionObject(principal, "test/expiration-session-exp", false)); null,
Assert.equal(null, pm.getPermissionObject(principal, "test/expiration-perm-exp2", false)); pm.getPermissionObject(principal, "test/expiration-perm-exp", false)
Assert.equal(null, pm.getPermissionObject(principal, "test/expiration-session-exp2", false)); );
Assert.equal(
null,
pm.getPermissionObject(principal, "test/expiration-session-exp", false)
);
Assert.equal(
null,
pm.getPermissionObject(principal, "test/expiration-perm-exp2", false)
);
Assert.equal(
null,
pm.getPermissionObject(principal, "test/expiration-session-exp2", false)
);
// Check that the renewable permissions actually got renewed // Check that the renewable permissions actually got renewed
Assert.equal(1, pm.testPermissionFromPrincipal(principal, "test/expiration-perm-renewable")); Assert.equal(
Assert.equal(1, pm.testPermissionFromPrincipal(principal, "test/expiration-session-renewable")); 1,
pm.testPermissionFromPrincipal(principal, "test/expiration-perm-renewable")
);
Assert.equal(
1,
pm.testPermissionFromPrincipal(
principal,
"test/expiration-session-renewable"
)
);
do_finish_generator_test(test_generator); do_finish_generator_test(test_generator);
} }

View file

@ -2,8 +2,9 @@
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
function check_enumerator(uri, permissions) { function check_enumerator(uri, permissions) {
let pm = Cc["@mozilla.org/permissionmanager;1"] let pm = Cc["@mozilla.org/permissionmanager;1"].getService(
.getService(Ci.nsIPermissionManager); Ci.nsIPermissionManager
);
let enumerator = pm.getAllForURI(uri); let enumerator = pm.getAllForURI(uri);
for ([type, capability] of permissions) { for ([type, capability] of permissions) {
@ -18,61 +19,55 @@ function check_enumerator(uri, permissions) {
} }
function run_test() { function run_test() {
let pm = Cc["@mozilla.org/permissionmanager;1"] let pm = Cc["@mozilla.org/permissionmanager;1"].getService(
.getService(Ci.nsIPermissionManager); Ci.nsIPermissionManager
);
let uri = NetUtil.newURI("http://example.com"); let uri = NetUtil.newURI("http://example.com");
let sub = NetUtil.newURI("http://sub.example.com"); let sub = NetUtil.newURI("http://sub.example.com");
check_enumerator(uri, [ ]); check_enumerator(uri, []);
pm.add(uri, "test/getallforuri", pm.ALLOW_ACTION); pm.add(uri, "test/getallforuri", pm.ALLOW_ACTION);
check_enumerator(uri, [ check_enumerator(uri, [["test/getallforuri", pm.ALLOW_ACTION]]);
[ "test/getallforuri", pm.ALLOW_ACTION ]
]);
// check that uris are matched exactly // check that uris are matched exactly
check_enumerator(sub, [ ]); check_enumerator(sub, []);
pm.add(sub, "test/getallforuri", pm.PROMPT_ACTION); pm.add(sub, "test/getallforuri", pm.PROMPT_ACTION);
pm.add(sub, "test/getallforuri2", pm.DENY_ACTION); pm.add(sub, "test/getallforuri2", pm.DENY_ACTION);
check_enumerator(sub, [ check_enumerator(sub, [
[ "test/getallforuri", pm.PROMPT_ACTION ], ["test/getallforuri", pm.PROMPT_ACTION],
[ "test/getallforuri2", pm.DENY_ACTION ] ["test/getallforuri2", pm.DENY_ACTION],
]); ]);
// check that the original uri list has not changed // check that the original uri list has not changed
check_enumerator(uri, [ check_enumerator(uri, [["test/getallforuri", pm.ALLOW_ACTION]]);
[ "test/getallforuri", pm.ALLOW_ACTION ]
]);
// check that UNKNOWN_ACTION permissions are ignored // check that UNKNOWN_ACTION permissions are ignored
pm.add(uri, "test/getallforuri2", pm.UNKNOWN_ACTION); pm.add(uri, "test/getallforuri2", pm.UNKNOWN_ACTION);
pm.add(uri, "test/getallforuri3", pm.DENY_ACTION); pm.add(uri, "test/getallforuri3", pm.DENY_ACTION);
check_enumerator(uri, [ check_enumerator(uri, [
[ "test/getallforuri", pm.ALLOW_ACTION ], ["test/getallforuri", pm.ALLOW_ACTION],
[ "test/getallforuri3", pm.DENY_ACTION ] ["test/getallforuri3", pm.DENY_ACTION],
]); ]);
// check that permission updates are reflected // check that permission updates are reflected
pm.add(uri, "test/getallforuri", pm.PROMPT_ACTION); pm.add(uri, "test/getallforuri", pm.PROMPT_ACTION);
check_enumerator(uri, [ check_enumerator(uri, [
[ "test/getallforuri", pm.PROMPT_ACTION ], ["test/getallforuri", pm.PROMPT_ACTION],
[ "test/getallforuri3", pm.DENY_ACTION ] ["test/getallforuri3", pm.DENY_ACTION],
]); ]);
// check that permission removals are reflected // check that permission removals are reflected
pm.remove(uri, "test/getallforuri"); pm.remove(uri, "test/getallforuri");
check_enumerator(uri, [ check_enumerator(uri, [["test/getallforuri3", pm.DENY_ACTION]]);
[ "test/getallforuri3", pm.DENY_ACTION ]
]);
pm.removeAll(); pm.removeAll();
check_enumerator(uri, [ ]); check_enumerator(uri, []);
check_enumerator(sub, [ ]); check_enumerator(sub, []);
} }

View file

@ -2,8 +2,9 @@
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
function check_enumerator(prefix, permissions) { function check_enumerator(prefix, permissions) {
let pm = Cc["@mozilla.org/permissionmanager;1"] let pm = Cc["@mozilla.org/permissionmanager;1"].getService(
.getService(Ci.nsIPermissionManager); Ci.nsIPermissionManager
);
let array = pm.getAllWithTypePrefix(prefix); let array = pm.getAllWithTypePrefix(prefix);
for (let [uri, type, capability] of permissions) { for (let [uri, type, capability] of permissions) {
@ -18,52 +19,52 @@ function check_enumerator(prefix, permissions) {
} }
function run_test() { function run_test() {
let pm = Cc["@mozilla.org/permissionmanager;1"] let pm = Cc["@mozilla.org/permissionmanager;1"].getService(
.getService(Ci.nsIPermissionManager); Ci.nsIPermissionManager
);
let uri = NetUtil.newURI("http://example.com"); let uri = NetUtil.newURI("http://example.com");
let sub = NetUtil.newURI("http://sub.example.com"); let sub = NetUtil.newURI("http://sub.example.com");
check_enumerator("test/", [ ]); check_enumerator("test/", []);
pm.add(uri, "test/getallwithtypeprefix", pm.ALLOW_ACTION); pm.add(uri, "test/getallwithtypeprefix", pm.ALLOW_ACTION);
pm.add(sub, "other-test/getallwithtypeprefix", pm.PROMPT_ACTION); pm.add(sub, "other-test/getallwithtypeprefix", pm.PROMPT_ACTION);
check_enumerator("test/", [ check_enumerator("test/", [
[ uri, "test/getallwithtypeprefix", pm.ALLOW_ACTION ], [uri, "test/getallwithtypeprefix", pm.ALLOW_ACTION],
]); ]);
pm.add(sub, "test/getallwithtypeprefix", pm.PROMPT_ACTION); pm.add(sub, "test/getallwithtypeprefix", pm.PROMPT_ACTION);
check_enumerator("test/", [ check_enumerator("test/", [
[ sub, "test/getallwithtypeprefix", pm.PROMPT_ACTION ], [sub, "test/getallwithtypeprefix", pm.PROMPT_ACTION],
[ uri, "test/getallwithtypeprefix", pm.ALLOW_ACTION ], [uri, "test/getallwithtypeprefix", pm.ALLOW_ACTION],
]); ]);
check_enumerator("test/getallwithtypeprefix", [ check_enumerator("test/getallwithtypeprefix", [
[ sub, "test/getallwithtypeprefix", pm.PROMPT_ACTION ], [sub, "test/getallwithtypeprefix", pm.PROMPT_ACTION],
[ uri, "test/getallwithtypeprefix", pm.ALLOW_ACTION ], [uri, "test/getallwithtypeprefix", pm.ALLOW_ACTION],
]); ]);
// check that UNKNOWN_ACTION permissions are ignored // check that UNKNOWN_ACTION permissions are ignored
pm.add(uri, "test/getallwithtypeprefix2", pm.UNKNOWN_ACTION); pm.add(uri, "test/getallwithtypeprefix2", pm.UNKNOWN_ACTION);
check_enumerator("test/", [ check_enumerator("test/", [
[ sub, "test/getallwithtypeprefix", pm.PROMPT_ACTION ], [sub, "test/getallwithtypeprefix", pm.PROMPT_ACTION],
[ uri, "test/getallwithtypeprefix", pm.ALLOW_ACTION ], [uri, "test/getallwithtypeprefix", pm.ALLOW_ACTION],
]); ]);
// check that permission updates are reflected // check that permission updates are reflected
pm.add(uri, "test/getallwithtypeprefix", pm.PROMPT_ACTION); pm.add(uri, "test/getallwithtypeprefix", pm.PROMPT_ACTION);
check_enumerator("test/", [ check_enumerator("test/", [
[ sub, "test/getallwithtypeprefix", pm.PROMPT_ACTION ], [sub, "test/getallwithtypeprefix", pm.PROMPT_ACTION],
[ uri, "test/getallwithtypeprefix", pm.PROMPT_ACTION ], [uri, "test/getallwithtypeprefix", pm.PROMPT_ACTION],
]); ]);
// check that permission removals are reflected // check that permission removals are reflected
pm.remove(uri, "test/getallwithtypeprefix"); pm.remove(uri, "test/getallwithtypeprefix");
check_enumerator("test/", [ check_enumerator("test/", [
[ sub, "test/getallwithtypeprefix", pm.PROMPT_ACTION ], [sub, "test/getallwithtypeprefix", pm.PROMPT_ACTION],
]); ]);
pm.removeAll(); pm.removeAll();
check_enumerator("test/", [ ]); check_enumerator("test/", []);
} }

View file

@ -2,23 +2,28 @@
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
function getPrincipalFromURI(aURI) { function getPrincipalFromURI(aURI) {
let ssm = Cc["@mozilla.org/scriptsecuritymanager;1"] let ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(
.getService(Ci.nsIScriptSecurityManager); Ci.nsIScriptSecurityManager
);
let uri = NetUtil.newURI(aURI); let uri = NetUtil.newURI(aURI);
return ssm.createCodebasePrincipal(uri, {}); return ssm.createCodebasePrincipal(uri, {});
} }
function getSystemPrincipal() { function getSystemPrincipal() {
return Cc["@mozilla.org/scriptsecuritymanager;1"] return Cc["@mozilla.org/scriptsecuritymanager;1"]
.getService(Ci.nsIScriptSecurityManager) .getService(Ci.nsIScriptSecurityManager)
.getSystemPrincipal(); .getSystemPrincipal();
} }
function run_test() { function run_test() {
var pm = Cc["@mozilla.org/permissionmanager;1"]. var pm = Cc["@mozilla.org/permissionmanager;1"].getService(
getService(Ci.nsIPermissionManager); Ci.nsIPermissionManager
);
Assert.equal(null, pm.getPermissionObject(getSystemPrincipal(), "test/pobject", false)); Assert.equal(
null,
pm.getPermissionObject(getSystemPrincipal(), "test/pobject", false)
);
let principal = getPrincipalFromURI("http://example.com"); let principal = getPrincipalFromURI("http://example.com");
let subPrincipal = getPrincipalFromURI("http://sub.example.com"); let subPrincipal = getPrincipalFromURI("http://sub.example.com");
@ -53,7 +58,12 @@ function run_test() {
Assert.ok(subPerm != null); Assert.ok(subPerm != null);
Assert.equal(subPerm.principal.origin, "http://example.com"); Assert.equal(subPerm.principal.origin, "http://example.com");
pm.addFromPrincipal(principal, "test/pobject", pm.DENY_ACTION, pm.EXPIRE_SESSION); pm.addFromPrincipal(
principal,
"test/pobject",
pm.DENY_ACTION,
pm.EXPIRE_SESSION
);
// make sure permission objects are not dynamic // make sure permission objects are not dynamic
Assert.equal(rootPerm.capability, pm.ALLOW_ACTION); Assert.equal(rootPerm.capability, pm.ALLOW_ACTION);

View file

@ -2,8 +2,9 @@
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
function getPrincipalFromDomain(aDomain) { function getPrincipalFromDomain(aDomain) {
let ssm = Cc["@mozilla.org/scriptsecuritymanager;1"] let ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(
.getService(Ci.nsIScriptSecurityManager); Ci.nsIScriptSecurityManager
);
let uri = NetUtil.newURI("http://" + aDomain); let uri = NetUtil.newURI("http://" + aDomain);
return ssm.createCodebasePrincipal(uri, {}); return ssm.createCodebasePrincipal(uri, {});
} }
@ -11,7 +12,7 @@ function getPrincipalFromDomain(aDomain) {
function run_test() { function run_test() {
let profile = do_get_profile(); let profile = do_get_profile();
let pm = Services.perms; let pm = Services.perms;
let perm = 'test-idn'; let perm = "test-idn";
// We create three principal linked to IDN. // We create three principal linked to IDN.
// One with just a domain, one with a subdomain and one with the TLD // One with just a domain, one with a subdomain and one with the TLD
@ -26,24 +27,52 @@ function run_test() {
pm.addFromPrincipal(tldPrincipal, perm, pm.ALLOW_ACTION, 0, 0); pm.addFromPrincipal(tldPrincipal, perm, pm.ALLOW_ACTION, 0, 0);
// They should obviously be there now.. // They should obviously be there now..
Assert.equal(pm.testPermissionFromPrincipal(mainDomainPrincipal, perm), pm.ALLOW_ACTION); Assert.equal(
Assert.equal(pm.testPermissionFromPrincipal(subDomainPrincipal, perm), pm.ALLOW_ACTION); pm.testPermissionFromPrincipal(mainDomainPrincipal, perm),
Assert.equal(pm.testPermissionFromPrincipal(tldPrincipal, perm), pm.ALLOW_ACTION); pm.ALLOW_ACTION
);
Assert.equal(
pm.testPermissionFromPrincipal(subDomainPrincipal, perm),
pm.ALLOW_ACTION
);
Assert.equal(
pm.testPermissionFromPrincipal(tldPrincipal, perm),
pm.ALLOW_ACTION
);
// We do the same thing with the puny-encoded versions of the IDN. // We do the same thing with the puny-encoded versions of the IDN.
let punyMainDomainPrincipal = getPrincipalFromDomain('xn--f-xgav.com'); let punyMainDomainPrincipal = getPrincipalFromDomain("xn--f-xgav.com");
let punySubDomainPrincipal = getPrincipalFromDomain('xn--f-xgaa.xn--br-jia.com'); let punySubDomainPrincipal = getPrincipalFromDomain(
let punyTldPrincipal = getPrincipalFromDomain('xn--f-xgav.xn--br-jia.xn--cm-8ja'); "xn--f-xgaa.xn--br-jia.com"
);
let punyTldPrincipal = getPrincipalFromDomain(
"xn--f-xgav.xn--br-jia.xn--cm-8ja"
);
// Those principals should have the permission granted too. // Those principals should have the permission granted too.
Assert.equal(pm.testPermissionFromPrincipal(punyMainDomainPrincipal, perm), pm.ALLOW_ACTION); Assert.equal(
Assert.equal(pm.testPermissionFromPrincipal(punySubDomainPrincipal, perm), pm.ALLOW_ACTION); pm.testPermissionFromPrincipal(punyMainDomainPrincipal, perm),
Assert.equal(pm.testPermissionFromPrincipal(punyTldPrincipal, perm), pm.ALLOW_ACTION); pm.ALLOW_ACTION
);
Assert.equal(
pm.testPermissionFromPrincipal(punySubDomainPrincipal, perm),
pm.ALLOW_ACTION
);
Assert.equal(
pm.testPermissionFromPrincipal(punyTldPrincipal, perm),
pm.ALLOW_ACTION
);
// However, those two principals shouldn't be allowed because they are like // However, those two principals shouldn't be allowed because they are like
// the IDN but without the UT8-8 characters. // the IDN but without the UT8-8 characters.
let witnessPrincipal = getPrincipalFromDomain("foo.com"); let witnessPrincipal = getPrincipalFromDomain("foo.com");
Assert.equal(pm.testPermissionFromPrincipal(witnessPrincipal, perm), pm.UNKNOWN_ACTION); Assert.equal(
pm.testPermissionFromPrincipal(witnessPrincipal, perm),
pm.UNKNOWN_ACTION
);
witnessPrincipal = getPrincipalFromDomain("foo.bar.com"); witnessPrincipal = getPrincipalFromDomain("foo.bar.com");
Assert.equal(pm.testPermissionFromPrincipal(witnessPrincipal, perm), pm.UNKNOWN_ACTION); Assert.equal(
pm.testPermissionFromPrincipal(witnessPrincipal, perm),
pm.UNKNOWN_ACTION
);
} }

View file

@ -10,8 +10,9 @@ function run_test() {
var file = dir.clone(); var file = dir.clone();
file.append("permissions.sqlite"); file.append("permissions.sqlite");
var storage = Cc["@mozilla.org/storage/service;1"] var storage = Cc["@mozilla.org/storage/service;1"].getService(
.getService(Ci.mozIStorageService); Ci.mozIStorageService
);
// Create database. // Create database.
var connection = storage.openDatabase(file); var connection = storage.openDatabase(file);
@ -19,8 +20,7 @@ function run_test() {
Assert.ok(file.exists()); Assert.ok(file.exists());
connection.schemaVersion = 3; connection.schemaVersion = 3;
connection.executeSimpleSQL( connection.executeSimpleSQL("DROP TABLE moz_hosts");
"DROP TABLE moz_hosts");
connection.executeSimpleSQL( connection.executeSimpleSQL(
"CREATE TABLE moz_hosts (" + "CREATE TABLE moz_hosts (" +
" id INTEGER PRIMARY KEY" + " id INTEGER PRIMARY KEY" +
@ -31,82 +31,192 @@ function run_test() {
",expireTime INTEGER" + ",expireTime INTEGER" +
",appId INTEGER" + ",appId INTEGER" +
",isInBrowserElement INTEGER" + ",isInBrowserElement INTEGER" +
")"); ")"
);
// Now we can inject garbadge in the database. // Now we can inject garbadge in the database.
var garbadge = [ var garbadge = [
// Regular entry. // Regular entry.
{ host: '42', type: '0', permission: 1, expireType: 0, expireTime: 0, {
isInBrowserElement: 0 }, host: "42",
type: "0",
permission: 1,
expireType: 0,
expireTime: 0,
isInBrowserElement: 0,
},
// Special values in host (some being invalid). // Special values in host (some being invalid).
{ host: 'scheme:file', type: '1', permission: 0, expireType: 0, {
expireTime: 0, isInBrowserElement: 0 }, host: "scheme:file",
{ host: '192.168.0.1', type: '2', permission: 0, expireType: 0, type: "1",
expireTime: 0, isInBrowserElement: 0 }, permission: 0,
{ host: '2001:0db8:0000:0000:0000:ff00:0042:8329', type: '3', permission: 0, expireType: 0,
expireType: 0, expireTime: 0, isInBrowserElement: 0 }, expireTime: 0,
{ host: '::1', type: '4', permission: 0, expireType: 0, expireTime: 0, isInBrowserElement: 0,
isInBrowserElement: 0 }, },
{
host: "192.168.0.1",
type: "2",
permission: 0,
expireType: 0,
expireTime: 0,
isInBrowserElement: 0,
},
{
host: "2001:0db8:0000:0000:0000:ff00:0042:8329",
type: "3",
permission: 0,
expireType: 0,
expireTime: 0,
isInBrowserElement: 0,
},
{
host: "::1",
type: "4",
permission: 0,
expireType: 0,
expireTime: 0,
isInBrowserElement: 0,
},
// Permission is UNKNOWN_ACTION. // Permission is UNKNOWN_ACTION.
{ host: '42', type: '5', permission: Ci.nsIPermissionManager.UNKNOWN_ACTION, {
expireType: 0, expireTime: 0, isInBrowserElement: 0 }, host: "42",
type: "5",
permission: Ci.nsIPermissionManager.UNKNOWN_ACTION,
expireType: 0,
expireTime: 0,
isInBrowserElement: 0,
},
// Permission is out of range. // Permission is out of range.
{ host: '42', type: '6', permission: 100, expireType: 0, expireTime: 0, {
isInBrowserElement: 0 }, host: "42",
{ host: '42', type: '7', permission: -100, expireType: 0, expireTime: 0, type: "6",
isInBrowserElement: 0 }, permission: 100,
expireType: 0,
expireTime: 0,
isInBrowserElement: 0,
},
{
host: "42",
type: "7",
permission: -100,
expireType: 0,
expireTime: 0,
isInBrowserElement: 0,
},
// ExpireType is out of range. // ExpireType is out of range.
{ host: '42', type: '8', permission: 1, expireType: -100, expireTime: 0, {
isInBrowserElement: 0 }, host: "42",
{ host: '42', type: '9', permission: 1, expireType: 100, expireTime: 0, type: "8",
isInBrowserElement: 0 }, permission: 1,
expireType: -100,
expireTime: 0,
isInBrowserElement: 0,
},
{
host: "42",
type: "9",
permission: 1,
expireType: 100,
expireTime: 0,
isInBrowserElement: 0,
},
// ExpireTime is at 0 with ExpireType = Time. // ExpireTime is at 0 with ExpireType = Time.
{ host: '42', type: '10', permission: 1, {
expireType: Ci.nsIPermissionManager.EXPIRE_TIME, expireTime: 0, host: "42",
isInBrowserElement: 0 }, type: "10",
permission: 1,
expireType: Ci.nsIPermissionManager.EXPIRE_TIME,
expireTime: 0,
isInBrowserElement: 0,
},
// ExpireTime has a value with ExpireType != Time // ExpireTime has a value with ExpireType != Time
{ host: '42', type: '11', permission: 1, {
expireType: Ci.nsIPermissionManager.EXPIRE_SESSION, expireTime: 1000, host: "42",
isInBrowserElement: 0 }, type: "11",
{ host: '42', type: '12', permission: 1, permission: 1,
expireType: Ci.nsIPermissionManager.EXPIRE_NEVER, expireTime: 1000, expireType: Ci.nsIPermissionManager.EXPIRE_SESSION,
isInBrowserElement: 0 }, expireTime: 1000,
isInBrowserElement: 0,
},
{
host: "42",
type: "12",
permission: 1,
expireType: Ci.nsIPermissionManager.EXPIRE_NEVER,
expireTime: 1000,
isInBrowserElement: 0,
},
// ExpireTime is negative. // ExpireTime is negative.
{ host: '42', type: '13', permission: 1, {
expireType: Ci.nsIPermissionManager.EXPIRE_TIME, expireTime: -1, host: "42",
isInBrowserElement: 0 }, type: "13",
permission: 1,
expireType: Ci.nsIPermissionManager.EXPIRE_TIME,
expireTime: -1,
isInBrowserElement: 0,
},
// IsInBrowserElement is negative or higher than 1. // IsInBrowserElement is negative or higher than 1.
{ host: '42', type: '15', permission: 1, expireType: 0, expireTime: 0, {
isInBrowserElement: -1 }, host: "42",
{ host: '42', type: '16', permission: 1, expireType: 0, expireTime: 0, type: "15",
isInBrowserElement: 10 }, permission: 1,
expireType: 0,
expireTime: 0,
isInBrowserElement: -1,
},
{
host: "42",
type: "16",
permission: 1,
expireType: 0,
expireTime: 0,
isInBrowserElement: 10,
},
// This insertion should be the last one. It is used to make sure we always // This insertion should be the last one. It is used to make sure we always
// load it regardless of the previous entries validities. // load it regardless of the previous entries validities.
{ host: 'example.org', type: 'test-load-invalid-entries', {
permission: Ci.nsIPermissionManager.ALLOW_ACTION, expireType: 0, host: "example.org",
expireTime: 0, isInBrowserElement: 0 }, type: "test-load-invalid-entries",
permission: Ci.nsIPermissionManager.ALLOW_ACTION,
expireType: 0,
expireTime: 0,
isInBrowserElement: 0,
},
]; ];
for (var i=0; i<garbadge.length; ++i) { for (var i = 0; i < garbadge.length; ++i) {
if (DEBUG_TEST) { if (DEBUG_TEST) {
dump("\n value #" + i + "\n\n"); dump("\n value #" + i + "\n\n");
} }
var data = garbadge[i]; var data = garbadge[i];
connection.executeSimpleSQL( connection.executeSimpleSQL(
"INSERT INTO moz_hosts " + "INSERT INTO moz_hosts " +
" (id, host, type, permission, expireType, expireTime, isInBrowserElement, appId) " + " (id, host, type, permission, expireType, expireTime, isInBrowserElement, appId) " +
"VALUES (" + i + ", '" + data.host + "', '" + data.type + "', " "VALUES (" +
+ data.permission + ", " + data.expireType + ", " i +
+ data.expireTime + ", " + data.isInBrowserElement + ", 0)" ", '" +
data.host +
"', '" +
data.type +
"', " +
data.permission +
", " +
data.expireType +
", " +
data.expireTime +
", " +
data.isInBrowserElement +
", 0)"
); );
} }
@ -115,15 +225,18 @@ function run_test() {
let earliestNow = Number(Date.now()); let earliestNow = Number(Date.now());
// Initialize the permission manager service // Initialize the permission manager service
var pm = Cc["@mozilla.org/permissionmanager;1"] var pm = Cc["@mozilla.org/permissionmanager;1"].getService(
.getService(Ci.nsIPermissionManager); Ci.nsIPermissionManager
);
let latestNow = Number(Date.now()); let latestNow = Number(Date.now());
// The schema should be upgraded to 10, and a 'modificationTime' column should // The schema should be upgraded to 10, and a 'modificationTime' column should
// exist with all records having a value of 0. // exist with all records having a value of 0.
Assert.equal(connection.schemaVersion, 10); Assert.equal(connection.schemaVersion, 10);
let select = connection.createStatement("SELECT modificationTime FROM moz_perms") let select = connection.createStatement(
"SELECT modificationTime FROM moz_perms"
);
let numMigrated = 0; let numMigrated = 0;
while (select.executeStep()) { while (select.executeStep()) {
let thisModTime = select.getInt64(0); let thisModTime = select.getInt64(0);
@ -134,9 +247,13 @@ function run_test() {
Assert.ok(numMigrated > 0, "we found at least 1 record that was migrated"); Assert.ok(numMigrated > 0, "we found at least 1 record that was migrated");
// This permission should always be there. // This permission should always be there.
let ssm = Cc["@mozilla.org/scriptsecuritymanager;1"] let ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(
.getService(Ci.nsIScriptSecurityManager); Ci.nsIScriptSecurityManager
);
let uri = NetUtil.newURI("http://example.org"); let uri = NetUtil.newURI("http://example.org");
let principal = ssm.createCodebasePrincipal(uri, {}); let principal = ssm.createCodebasePrincipal(uri, {});
Assert.equal(pm.testPermissionFromPrincipal(principal, 'test-load-invalid-entries'), Ci.nsIPermissionManager.ALLOW_ACTION); Assert.equal(
pm.testPermissionFromPrincipal(principal, "test-load-invalid-entries"),
Ci.nsIPermissionManager.ALLOW_ACTION
);
} }

View file

@ -3,8 +3,7 @@
// Test that permissions work for file:// URIs (aka local files). // Test that permissions work for file:// URIs (aka local files).
function getPrincipalFromURIString(uriStr) function getPrincipalFromURIString(uriStr) {
{
let uri = NetUtil.newURI(uriStr); let uri = NetUtil.newURI(uriStr);
return Services.scriptSecurityManager.createCodebasePrincipal(uri, {}); return Services.scriptSecurityManager.createCodebasePrincipal(uri, {});
} }
@ -15,29 +14,61 @@ function run_test() {
// If we add a permission to a file:// URI, the test should return true. // If we add a permission to a file:// URI, the test should return true.
let principal = getPrincipalFromURIString("file:///foo/bar"); let principal = getPrincipalFromURIString("file:///foo/bar");
pm.addFromPrincipal(principal, "test/local-files", pm.ALLOW_ACTION, 0, 0); pm.addFromPrincipal(principal, "test/local-files", pm.ALLOW_ACTION, 0, 0);
Assert.equal(pm.testPermissionFromPrincipal(principal, "test/local-files"), pm.ALLOW_ACTION); Assert.equal(
pm.testPermissionFromPrincipal(principal, "test/local-files"),
pm.ALLOW_ACTION
);
// Another file:// URI should have the same permission. // Another file:// URI should have the same permission.
let witnessPrincipal = getPrincipalFromURIString("file:///bar/foo"); let witnessPrincipal = getPrincipalFromURIString("file:///bar/foo");
Assert.equal(pm.testPermissionFromPrincipal(witnessPrincipal, "test/local-files"), pm.UNKNOWN_ACTION); Assert.equal(
pm.testPermissionFromPrincipal(witnessPrincipal, "test/local-files"),
pm.UNKNOWN_ACTION
);
// Giving "file:///" a permission shouldn't give it to all file:// URIs. // Giving "file:///" a permission shouldn't give it to all file:// URIs.
let rootPrincipal = getPrincipalFromURIString("file:///"); let rootPrincipal = getPrincipalFromURIString("file:///");
pm.addFromPrincipal(rootPrincipal, "test/local-files", pm.ALLOW_ACTION, 0, 0); pm.addFromPrincipal(rootPrincipal, "test/local-files", pm.ALLOW_ACTION, 0, 0);
Assert.equal(pm.testPermissionFromPrincipal(witnessPrincipal, "test/local-files"), pm.UNKNOWN_ACTION); Assert.equal(
pm.testPermissionFromPrincipal(witnessPrincipal, "test/local-files"),
pm.UNKNOWN_ACTION
);
// Giving "file://" a permission shouldn't give it to all file:// URIs. // Giving "file://" a permission shouldn't give it to all file:// URIs.
let schemeRootPrincipal = getPrincipalFromURIString("file://"); let schemeRootPrincipal = getPrincipalFromURIString("file://");
pm.addFromPrincipal(schemeRootPrincipal, "test/local-files", pm.ALLOW_ACTION, 0, 0); pm.addFromPrincipal(
Assert.equal(pm.testPermissionFromPrincipal(witnessPrincipal, "test/local-files"), pm.UNKNOWN_ACTION); schemeRootPrincipal,
"test/local-files",
pm.ALLOW_ACTION,
0,
0
);
Assert.equal(
pm.testPermissionFromPrincipal(witnessPrincipal, "test/local-files"),
pm.UNKNOWN_ACTION
);
// Giving 'node' a permission shouldn't give it to its 'children'. // Giving 'node' a permission shouldn't give it to its 'children'.
let fileInDirPrincipal = getPrincipalFromURIString("file:///foo/bar/foobar.txt"); let fileInDirPrincipal = getPrincipalFromURIString(
Assert.equal(pm.testPermissionFromPrincipal(fileInDirPrincipal, "test/local-files"), pm.UNKNOWN_ACTION); "file:///foo/bar/foobar.txt"
);
Assert.equal(
pm.testPermissionFromPrincipal(fileInDirPrincipal, "test/local-files"),
pm.UNKNOWN_ACTION
);
// Revert "file:///foo/bar" permission and check that it has been correctly taken into account. // Revert "file:///foo/bar" permission and check that it has been correctly taken into account.
pm.removeFromPrincipal(principal, "test/local-files"); pm.removeFromPrincipal(principal, "test/local-files");
Assert.equal(pm.testPermissionFromPrincipal(principal, "test/local-files"), pm.UNKNOWN_ACTION); Assert.equal(
Assert.equal(pm.testPermissionFromPrincipal(witnessPrincipal, "test/local-files"), pm.UNKNOWN_ACTION); pm.testPermissionFromPrincipal(principal, "test/local-files"),
Assert.equal(pm.testPermissionFromPrincipal(fileInDirPrincipal, "test/local-files"), pm.UNKNOWN_ACTION); pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionFromPrincipal(witnessPrincipal, "test/local-files"),
pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionFromPrincipal(fileInDirPrincipal, "test/local-files"),
pm.UNKNOWN_ACTION
);
} }

View file

@ -2,33 +2,53 @@
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
function matches_always(perm, principals) { function matches_always(perm, principals) {
principals.forEach((principal) => { principals.forEach(principal => {
Assert.ok(perm.matches(principal, true), "perm: " + perm.principal.origin + ", princ: " + principal.origin); Assert.ok(
Assert.ok(perm.matches(principal, false), "perm: " + perm.principal.origin + ", princ: " + principal.origin); perm.matches(principal, true),
"perm: " + perm.principal.origin + ", princ: " + principal.origin
);
Assert.ok(
perm.matches(principal, false),
"perm: " + perm.principal.origin + ", princ: " + principal.origin
);
}); });
} }
function matches_weak(perm, principals) { function matches_weak(perm, principals) {
principals.forEach((principal) => { principals.forEach(principal => {
Assert.ok(!perm.matches(principal, true), "perm: " + perm.principal.origin + ", princ: " + principal.origin); Assert.ok(
Assert.ok(perm.matches(principal, false), "perm: " + perm.principal.origin + ", princ: " + principal.origin); !perm.matches(principal, true),
"perm: " + perm.principal.origin + ", princ: " + principal.origin
);
Assert.ok(
perm.matches(principal, false),
"perm: " + perm.principal.origin + ", princ: " + principal.origin
);
}); });
} }
function matches_never(perm, principals) { function matches_never(perm, principals) {
principals.forEach((principal) => { principals.forEach(principal => {
Assert.ok(!perm.matches(principal, true), "perm: " + perm.principal.origin + ", princ: " + principal.origin); Assert.ok(
Assert.ok(!perm.matches(principal, false), "perm: " + perm.principal.origin + ", princ: " + principal.origin); !perm.matches(principal, true),
"perm: " + perm.principal.origin + ", princ: " + principal.origin
);
Assert.ok(
!perm.matches(principal, false),
"perm: " + perm.principal.origin + ", princ: " + principal.origin
);
}); });
} }
function run_test() { function run_test() {
// initialize the permission manager service // initialize the permission manager service
let pm = Cc["@mozilla.org/permissionmanager;1"]. let pm = Cc["@mozilla.org/permissionmanager;1"].getService(
getService(Ci.nsIPermissionManager); Ci.nsIPermissionManager
);
let secMan = Cc["@mozilla.org/scriptsecuritymanager;1"] let secMan = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(
.getService(Ci.nsIScriptSecurityManager); Ci.nsIScriptSecurityManager
);
// Add some permissions // Add some permissions
let uri0 = NetUtil.newURI("http://google.com/search?q=foo#hashtag"); let uri0 = NetUtil.newURI("http://google.com/search?q=foo#hashtag");
@ -45,7 +65,7 @@ function run_test() {
let uri4_n = secMan.createCodebasePrincipal(uri4, {}); let uri4_n = secMan.createCodebasePrincipal(uri4, {});
let uri5_n = secMan.createCodebasePrincipal(uri5, {}); let uri5_n = secMan.createCodebasePrincipal(uri5, {});
attrs = {inIsolatedMozBrowser: true}; attrs = { inIsolatedMozBrowser: true };
let uri0_y_ = secMan.createCodebasePrincipal(uri0, attrs); let uri0_y_ = secMan.createCodebasePrincipal(uri0, attrs);
let uri1_y_ = secMan.createCodebasePrincipal(uri1, attrs); let uri1_y_ = secMan.createCodebasePrincipal(uri1, attrs);
let uri2_y_ = secMan.createCodebasePrincipal(uri2, attrs); let uri2_y_ = secMan.createCodebasePrincipal(uri2, attrs);
@ -53,7 +73,7 @@ function run_test() {
let uri4_y_ = secMan.createCodebasePrincipal(uri4, attrs); let uri4_y_ = secMan.createCodebasePrincipal(uri4, attrs);
let uri5_y_ = secMan.createCodebasePrincipal(uri5, attrs); let uri5_y_ = secMan.createCodebasePrincipal(uri5, attrs);
attrs = {userContextId: 1}; attrs = { userContextId: 1 };
let uri0_1 = secMan.createCodebasePrincipal(uri0, attrs); let uri0_1 = secMan.createCodebasePrincipal(uri0, attrs);
let uri1_1 = secMan.createCodebasePrincipal(uri1, attrs); let uri1_1 = secMan.createCodebasePrincipal(uri1, attrs);
let uri2_1 = secMan.createCodebasePrincipal(uri2, attrs); let uri2_1 = secMan.createCodebasePrincipal(uri2, attrs);
@ -61,7 +81,7 @@ function run_test() {
let uri4_1 = secMan.createCodebasePrincipal(uri4, attrs); let uri4_1 = secMan.createCodebasePrincipal(uri4, attrs);
let uri5_1 = secMan.createCodebasePrincipal(uri5, attrs); let uri5_1 = secMan.createCodebasePrincipal(uri5, attrs);
attrs = {firstPartyDomain: "cnn.com"}; attrs = { firstPartyDomain: "cnn.com" };
let uri0_cnn = secMan.createCodebasePrincipal(uri0, attrs); let uri0_cnn = secMan.createCodebasePrincipal(uri0, attrs);
let uri1_cnn = secMan.createCodebasePrincipal(uri1, attrs); let uri1_cnn = secMan.createCodebasePrincipal(uri1, attrs);
let uri2_cnn = secMan.createCodebasePrincipal(uri2, attrs); let uri2_cnn = secMan.createCodebasePrincipal(uri2, attrs);
@ -80,31 +100,105 @@ function run_test() {
matches_always(perm_n, [uri0_n, uri0_1]); matches_always(perm_n, [uri0_n, uri0_1]);
matches_weak(perm_n, [uri1_n, uri1_1]); matches_weak(perm_n, [uri1_n, uri1_1]);
matches_never(perm_n, [uri2_n, uri3_n, uri4_n, uri5_n, matches_never(perm_n, [
uri0_y_, uri1_y_, uri2_y_, uri3_y_, uri4_y_, uri5_y_, uri2_n,
uri2_1, uri3_1, uri4_1, uri5_1, uri3_n,
uri0_cnn, uri1_cnn, uri2_cnn, uri3_cnn, uri4_cnn, uri5_cnn]); uri4_n,
uri5_n,
uri0_y_,
uri1_y_,
uri2_y_,
uri3_y_,
uri4_y_,
uri5_y_,
uri2_1,
uri3_1,
uri4_1,
uri5_1,
uri0_cnn,
uri1_cnn,
uri2_cnn,
uri3_cnn,
uri4_cnn,
uri5_cnn,
]);
matches_always(perm_y_, [uri0_y_]); matches_always(perm_y_, [uri0_y_]);
matches_weak(perm_y_, [uri1_y_]); matches_weak(perm_y_, [uri1_y_]);
matches_never(perm_y_, [uri2_y_, uri3_y_, uri4_y_, uri5_y_, matches_never(perm_y_, [
uri0_n, uri1_n, uri2_n, uri3_n, uri4_n, uri5_n, uri2_y_,
uri0_1, uri1_1, uri2_1, uri3_1, uri4_1, uri5_1, uri3_y_,
uri0_cnn, uri1_cnn, uri2_cnn, uri3_cnn, uri4_cnn, uri5_cnn]); uri4_y_,
uri5_y_,
uri0_n,
uri1_n,
uri2_n,
uri3_n,
uri4_n,
uri5_n,
uri0_1,
uri1_1,
uri2_1,
uri3_1,
uri4_1,
uri5_1,
uri0_cnn,
uri1_cnn,
uri2_cnn,
uri3_cnn,
uri4_cnn,
uri5_cnn,
]);
matches_always(perm_1, [uri0_n, uri0_1]); matches_always(perm_1, [uri0_n, uri0_1]);
matches_weak(perm_1, [uri1_n, uri1_1]); matches_weak(perm_1, [uri1_n, uri1_1]);
matches_never(perm_1, [uri2_n, uri3_n, uri4_n, uri5_n, matches_never(perm_1, [
uri0_y_, uri1_y_, uri2_y_, uri3_y_, uri4_y_, uri5_y_, uri2_n,
uri2_1, uri3_1, uri4_1, uri5_1, uri3_n,
uri0_cnn, uri1_cnn, uri2_cnn, uri3_cnn, uri4_cnn, uri5_cnn]); uri4_n,
uri5_n,
uri0_y_,
uri1_y_,
uri2_y_,
uri3_y_,
uri4_y_,
uri5_y_,
uri2_1,
uri3_1,
uri4_1,
uri5_1,
uri0_cnn,
uri1_cnn,
uri2_cnn,
uri3_cnn,
uri4_cnn,
uri5_cnn,
]);
matches_always(perm_cnn, [uri0_n, uri0_1]); matches_always(perm_cnn, [uri0_n, uri0_1]);
matches_weak(perm_cnn, [uri1_n, uri1_1]); matches_weak(perm_cnn, [uri1_n, uri1_1]);
matches_never(perm_cnn, [uri2_n, uri3_n, uri4_n, uri5_n, matches_never(perm_cnn, [
uri0_y_, uri1_y_, uri2_y_, uri3_y_, uri4_y_, uri5_y_, uri2_n,
uri2_1, uri3_1, uri4_1, uri5_1, uri3_n,
uri0_cnn, uri1_cnn, uri2_cnn, uri3_cnn, uri4_cnn, uri5_cnn]); uri4_n,
uri5_n,
uri0_y_,
uri1_y_,
uri2_y_,
uri3_y_,
uri4_y_,
uri5_y_,
uri2_1,
uri3_1,
uri4_1,
uri5_1,
uri0_cnn,
uri1_cnn,
uri2_cnn,
uri3_cnn,
uri4_cnn,
uri5_cnn,
]);
// Clean up! // Clean up!
pm.removeAll(); pm.removeAll();

View file

@ -2,32 +2,52 @@
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
function matches_always(perm, uris) { function matches_always(perm, uris) {
uris.forEach((uri) => { uris.forEach(uri => {
Assert.ok(perm.matchesURI(uri, true), "perm: " + perm.principal.origin + ", URI: " + uri.spec); Assert.ok(
Assert.ok(perm.matchesURI(uri, false), "perm: " + perm.principal.origin + ", URI: " + uri.spec); perm.matchesURI(uri, true),
"perm: " + perm.principal.origin + ", URI: " + uri.spec
);
Assert.ok(
perm.matchesURI(uri, false),
"perm: " + perm.principal.origin + ", URI: " + uri.spec
);
}); });
} }
function matches_weak(perm, uris) { function matches_weak(perm, uris) {
uris.forEach((uri) => { uris.forEach(uri => {
Assert.ok(!perm.matchesURI(uri, true), "perm: " + perm.principal.origin + ", URI: " + uri.spec); Assert.ok(
Assert.ok(perm.matchesURI(uri, false), "perm: " + perm.principal.origin + ", URI: " + uri.spec); !perm.matchesURI(uri, true),
"perm: " + perm.principal.origin + ", URI: " + uri.spec
);
Assert.ok(
perm.matchesURI(uri, false),
"perm: " + perm.principal.origin + ", URI: " + uri.spec
);
}); });
} }
function matches_never(perm, uris) { function matches_never(perm, uris) {
uris.forEach((uri) => { uris.forEach(uri => {
Assert.ok(!perm.matchesURI(uri, true), "perm: " + perm.principal.origin + ", URI: " + uri.spec); Assert.ok(
Assert.ok(!perm.matchesURI(uri, false), "perm: " + perm.principal.origin + ", URI: " + uri.spec); !perm.matchesURI(uri, true),
"perm: " + perm.principal.origin + ", URI: " + uri.spec
);
Assert.ok(
!perm.matchesURI(uri, false),
"perm: " + perm.principal.origin + ", URI: " + uri.spec
);
}); });
} }
function mk_permission(uri) { function mk_permission(uri) {
let pm = Cc["@mozilla.org/permissionmanager;1"]. let pm = Cc["@mozilla.org/permissionmanager;1"].getService(
getService(Ci.nsIPermissionManager); Ci.nsIPermissionManager
);
let secMan = Cc["@mozilla.org/scriptsecuritymanager;1"] let secMan = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(
.getService(Ci.nsIScriptSecurityManager); Ci.nsIScriptSecurityManager
);
// Get the permission from the principal! // Get the permission from the principal!
let principal = secMan.createCodebasePrincipal(uri, {}); let principal = secMan.createCodebasePrincipal(uri, {});
@ -40,11 +60,13 @@ function mk_permission(uri) {
function run_test() { function run_test() {
// initialize the permission manager service // initialize the permission manager service
let pm = Cc["@mozilla.org/permissionmanager;1"]. let pm = Cc["@mozilla.org/permissionmanager;1"].getService(
getService(Ci.nsIPermissionManager); Ci.nsIPermissionManager
);
let secMan = Cc["@mozilla.org/scriptsecuritymanager;1"] let secMan = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(
.getService(Ci.nsIScriptSecurityManager); Ci.nsIScriptSecurityManager
);
let fileprefix = "file:///"; let fileprefix = "file:///";
if (Services.appinfo.OS == "WINNT") { if (Services.appinfo.OS == "WINNT") {
@ -77,7 +99,17 @@ function run_test() {
let perm = mk_permission(uri1); let perm = mk_permission(uri1);
matches_always(perm, [uri1]); matches_always(perm, [uri1]);
matches_weak(perm, [uri4]); matches_weak(perm, [uri4]);
matches_never(perm, [uri0, uri2, uri3, uri5, uri6, uri7, fileuri1, fileuri2, fileuri3]); matches_never(perm, [
uri0,
uri2,
uri3,
uri5,
uri6,
uri7,
fileuri1,
fileuri2,
fileuri3,
]);
} }
{ {
@ -91,56 +123,138 @@ function run_test() {
let perm = mk_permission(uri3); let perm = mk_permission(uri3);
matches_always(perm, [uri3]); matches_always(perm, [uri3]);
matches_weak(perm, []); matches_weak(perm, []);
matches_never(perm, [uri1, uri2, uri4, uri5, uri6, uri7, fileuri1, fileuri2, fileuri3]); matches_never(perm, [
uri1,
uri2,
uri4,
uri5,
uri6,
uri7,
fileuri1,
fileuri2,
fileuri3,
]);
} }
{ {
let perm = mk_permission(uri4); let perm = mk_permission(uri4);
matches_always(perm, [uri4]); matches_always(perm, [uri4]);
matches_weak(perm, []); matches_weak(perm, []);
matches_never(perm, [uri1, uri2, uri3, uri5, uri6, uri7, fileuri1, fileuri2, fileuri3]); matches_never(perm, [
uri1,
uri2,
uri3,
uri5,
uri6,
uri7,
fileuri1,
fileuri2,
fileuri3,
]);
} }
{ {
let perm = mk_permission(uri5); let perm = mk_permission(uri5);
matches_always(perm, [uri5, uri7]); matches_always(perm, [uri5, uri7]);
matches_weak(perm, [uri6]); matches_weak(perm, [uri6]);
matches_never(perm, [uri0, uri1, uri2, uri3, uri4, fileuri1, fileuri2, fileuri3]); matches_never(perm, [
uri0,
uri1,
uri2,
uri3,
uri4,
fileuri1,
fileuri2,
fileuri3,
]);
} }
{ {
let perm = mk_permission(uri6); let perm = mk_permission(uri6);
matches_always(perm, [uri6]); matches_always(perm, [uri6]);
matches_weak(perm, []); matches_weak(perm, []);
matches_never(perm, [uri0, uri1, uri2, uri3, uri4, uri5, uri7, fileuri1, fileuri2, fileuri3]); matches_never(perm, [
uri0,
uri1,
uri2,
uri3,
uri4,
uri5,
uri7,
fileuri1,
fileuri2,
fileuri3,
]);
} }
{ {
let perm = mk_permission(uri7); let perm = mk_permission(uri7);
matches_always(perm, [uri5, uri7]); matches_always(perm, [uri5, uri7]);
matches_weak(perm, [uri6]); matches_weak(perm, [uri6]);
matches_never(perm, [uri0, uri1, uri2, uri3, uri4, fileuri1, fileuri2, fileuri3]); matches_never(perm, [
uri0,
uri1,
uri2,
uri3,
uri4,
fileuri1,
fileuri2,
fileuri3,
]);
} }
{ {
let perm = mk_permission(fileuri1); let perm = mk_permission(fileuri1);
matches_always(perm, [fileuri1]); matches_always(perm, [fileuri1]);
matches_weak(perm, []); matches_weak(perm, []);
matches_never(perm, [uri0, uri1, uri2, uri3, uri4, uri5, uri6, uri7, fileuri2, fileuri3]); matches_never(perm, [
uri0,
uri1,
uri2,
uri3,
uri4,
uri5,
uri6,
uri7,
fileuri2,
fileuri3,
]);
} }
{ {
let perm = mk_permission(fileuri2); let perm = mk_permission(fileuri2);
matches_always(perm, [fileuri2]); matches_always(perm, [fileuri2]);
matches_weak(perm, []); matches_weak(perm, []);
matches_never(perm, [uri0, uri1, uri2, uri3, uri4, uri5, uri6, uri7, fileuri1, fileuri3]); matches_never(perm, [
uri0,
uri1,
uri2,
uri3,
uri4,
uri5,
uri6,
uri7,
fileuri1,
fileuri3,
]);
} }
{ {
let perm = mk_permission(fileuri3); let perm = mk_permission(fileuri3);
matches_always(perm, [fileuri3]); matches_always(perm, [fileuri3]);
matches_weak(perm, []); matches_weak(perm, []);
matches_never(perm, [uri0, uri1, uri2, uri3, uri4, uri5, uri6, uri7, fileuri1, fileuri2]); matches_never(perm, [
uri0,
uri1,
uri2,
uri3,
uri4,
uri5,
uri6,
uri7,
fileuri1,
fileuri2,
]);
} }
// Clean up! // Clean up!

View file

@ -1,13 +1,15 @@
/* Any copyright is dedicated to the Public Domain. /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
ChromeUtils.defineModuleGetter(this, "PlacesTestUtils", ChromeUtils.defineModuleGetter(
"resource://testing-common/PlacesTestUtils.jsm"); this,
"PlacesTestUtils",
"resource://testing-common/PlacesTestUtils.jsm"
);
var PERMISSIONS_FILE_NAME = "permissions.sqlite"; var PERMISSIONS_FILE_NAME = "permissions.sqlite";
function GetPermissionsFile(profile) function GetPermissionsFile(profile) {
{
let file = profile.clone(); let file = profile.clone();
file.append(PERMISSIONS_FILE_NAME); file.append(PERMISSIONS_FILE_NAME);
return file; return file;
@ -34,18 +36,29 @@ add_task(async function test() {
",modificationTime INTEGER" + ",modificationTime INTEGER" +
",appId INTEGER" + ",appId INTEGER" +
",isInBrowserElement INTEGER" + ",isInBrowserElement INTEGER" +
")"); ")"
);
let stmtInsert = db.createStatement( let stmtInsert = db.createStatement(
"INSERT INTO moz_hosts (" + "INSERT INTO moz_hosts (" +
"id, host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement" + "id, host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement" +
") VALUES (" + ") VALUES (" +
":id, :host, :type, :permission, :expireType, :expireTime, :modificationTime, :appId, :isInBrowserElement" + ":id, :host, :type, :permission, :expireType, :expireTime, :modificationTime, :appId, :isInBrowserElement" +
")"); ")"
);
let id = 0; let id = 0;
function insertHost(host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement) { function insertHost(
host,
type,
permission,
expireType,
expireTime,
modificationTime,
appId,
isInBrowserElement
) {
let thisId = id++; let thisId = id++;
stmtInsert.bindByName("id", thisId); stmtInsert.bindByName("id", thisId);
@ -73,7 +86,7 @@ add_task(async function test() {
expireTime, expireTime,
modificationTime, modificationTime,
appId, appId,
isInBrowserElement isInBrowserElement,
}; };
} }
@ -93,8 +106,26 @@ add_task(async function test() {
insertHost("192.0.2.235", "A", 1, 0, 0, 0, 0, false), insertHost("192.0.2.235", "A", 1, 0, 0, 0, 0, false),
insertHost("file:///some/path/to/file.html", "A", 1, 0, 0, 0, 0, false), insertHost("file:///some/path/to/file.html", "A", 1, 0, 0, 0, 0, false),
insertHost("file:///another/file.html", "A", 1, 0, 0, 0, 0, false), insertHost("file:///another/file.html", "A", 1, 0, 0, 0, 0, false),
insertHost("moz-nullprincipal:{8695105a-adbe-4e4e-8083-851faa5ca2d7}", "A", 1, 0, 0, 0, 0, false), insertHost(
insertHost("moz-nullprincipal:{12ahjksd-akjs-asd3-8393-asdu2189asdu}", "B", 1, 0, 0, 0, 0, false), "moz-nullprincipal:{8695105a-adbe-4e4e-8083-851faa5ca2d7}",
"A",
1,
0,
0,
0,
0,
false
),
insertHost(
"moz-nullprincipal:{12ahjksd-akjs-asd3-8393-asdu2189asdu}",
"B",
1,
0,
0,
0,
0,
false
),
insertHost("<file>", "A", 1, 0, 0, 0, 0, false), insertHost("<file>", "A", 1, 0, 0, 0, 0, false),
insertHost("<file>", "B", 1, 0, 0, 0, 0, false), insertHost("<file>", "B", 1, 0, 0, 0, 0, false),
]; ];
@ -150,11 +181,15 @@ add_task(async function test() {
["https://192.0.2.235", "A", 1, 0, 0], ["https://192.0.2.235", "A", 1, 0, 0],
]; ];
let found = expected.map((it) => 0); let found = expected.map(it => 0);
// Add some places to the places database // Add some places to the places database
await PlacesTestUtils.addVisits(Services.io.newURI("https://foo.com/some/other/subdirectory")); await PlacesTestUtils.addVisits(
await PlacesTestUtils.addVisits(Services.io.newURI("ftp://some.subdomain.of.foo.com:8000/some/subdirectory")); Services.io.newURI("https://foo.com/some/other/subdirectory")
);
await PlacesTestUtils.addVisits(
Services.io.newURI("ftp://some.subdomain.of.foo.com:8000/some/subdirectory")
);
// This will force the permission-manager to reload the data. // This will force the permission-manager to reload the data.
Services.obs.notifyObservers(null, "testonly-reload-permissions-from-disk"); Services.obs.notifyObservers(null, "testonly-reload-permissions-from-disk");
@ -164,28 +199,43 @@ add_task(async function test() {
let isExpected = false; let isExpected = false;
expected.forEach((it, i) => { expected.forEach((it, i) => {
if (permission.principal.origin == it[0] && if (
permission.type == it[1] && permission.principal.origin == it[0] &&
permission.capability == it[2] && permission.type == it[1] &&
permission.expireType == it[3] && permission.capability == it[2] &&
permission.expireTime == it[4]) { permission.expireType == it[3] &&
permission.expireTime == it[4]
) {
isExpected = true; isExpected = true;
found[i]++; found[i]++;
} }
}); });
Assert.ok(isExpected, Assert.ok(
"Permission " + (isExpected ? "should" : "shouldn't") + isExpected,
" be in permission database: " + "Permission " +
permission.principal.origin + ", " + (isExpected ? "should" : "shouldn't") +
permission.type + ", " + " be in permission database: " +
permission.capability + ", " + permission.principal.origin +
permission.expireType + ", " + ", " +
permission.expireTime); permission.type +
", " +
permission.capability +
", " +
permission.expireType +
", " +
permission.expireTime
);
} }
found.forEach((count, i) => { found.forEach((count, i) => {
Assert.ok(count == 1, "Expected count = 1, got count = " + count + " for permission " + expected[i]); Assert.ok(
count == 1,
"Expected count = 1, got count = " +
count +
" for permission " +
expected[i]
);
}); });
// Check to make sure that all of the tables which we care about are present // Check to make sure that all of the tables which we care about are present

View file

@ -15,14 +15,19 @@ var factory = {
lockFactory() { lockFactory() {
throw Cr.NS_ERROR_NOT_IMPLEMENTED; throw Cr.NS_ERROR_NOT_IMPLEMENTED;
}, },
QueryInterface: ChromeUtils.generateQI([Ci.nsIFactory]) QueryInterface: ChromeUtils.generateQI([Ci.nsIFactory]),
}; };
var newClassID = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator).generateUUID(); var newClassID = Cc["@mozilla.org/uuid-generator;1"]
.getService(Ci.nsIUUIDGenerator)
.generateUUID();
var registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); var registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
var oldClassID = registrar.contractIDToCID(CONTRACT_ID); var oldClassID = registrar.contractIDToCID(CONTRACT_ID);
var oldFactory = Components.manager.getClassObject(Cc[CONTRACT_ID], Ci.nsIFactory); var oldFactory = Components.manager.getClassObject(
Cc[CONTRACT_ID],
Ci.nsIFactory
);
registrar.registerFactory(newClassID, "", CONTRACT_ID, factory); registrar.registerFactory(newClassID, "", CONTRACT_ID, factory);
function cleanupFactory() { function cleanupFactory() {
@ -30,8 +35,7 @@ function cleanupFactory() {
registrar.registerFactory(oldClassID, "", CONTRACT_ID, null); registrar.registerFactory(oldClassID, "", CONTRACT_ID, null);
} }
function GetPermissionsFile(profile) function GetPermissionsFile(profile) {
{
let file = profile.clone(); let file = profile.clone();
file.append(PERMISSIONS_FILE_NAME); file.append(PERMISSIONS_FILE_NAME);
return file; return file;
@ -48,7 +52,9 @@ add_task(function test() {
// Make sure that we can't resolve the nsINavHistoryService // Make sure that we can't resolve the nsINavHistoryService
try { try {
Cc['@mozilla.org/browser/nav-history-service;1'].getService(Ci.nsINavHistoryService); Cc["@mozilla.org/browser/nav-history-service;1"].getService(
Ci.nsINavHistoryService
);
Assert.ok(false, "There shouldn't have been a nsINavHistoryService"); Assert.ok(false, "There shouldn't have been a nsINavHistoryService");
} catch (e) { } catch (e) {
Assert.ok(true, "There wasn't a nsINavHistoryService"); Assert.ok(true, "There wasn't a nsINavHistoryService");
@ -70,18 +76,29 @@ add_task(function test() {
",modificationTime INTEGER" + ",modificationTime INTEGER" +
",appId INTEGER" + ",appId INTEGER" +
",isInBrowserElement INTEGER" + ",isInBrowserElement INTEGER" +
")"); ")"
);
let stmtInsert = db.createStatement( let stmtInsert = db.createStatement(
"INSERT INTO moz_hosts (" + "INSERT INTO moz_hosts (" +
"id, host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement" + "id, host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement" +
") VALUES (" + ") VALUES (" +
":id, :host, :type, :permission, :expireType, :expireTime, :modificationTime, :appId, :isInBrowserElement" + ":id, :host, :type, :permission, :expireType, :expireTime, :modificationTime, :appId, :isInBrowserElement" +
")"); ")"
);
let id = 0; let id = 0;
function insertHost(host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement) { function insertHost(
host,
type,
permission,
expireType,
expireTime,
modificationTime,
appId,
isInBrowserElement
) {
let thisId = id++; let thisId = id++;
stmtInsert.bindByName("id", thisId); stmtInsert.bindByName("id", thisId);
@ -109,7 +126,7 @@ add_task(function test() {
expireTime, expireTime,
modificationTime, modificationTime,
appId, appId,
isInBrowserElement isInBrowserElement,
}; };
} }
@ -129,8 +146,26 @@ add_task(function test() {
insertHost("263.123.555.676", "A", 1, 0, 0, 0, 0, false), insertHost("263.123.555.676", "A", 1, 0, 0, 0, 0, false),
insertHost("file:///some/path/to/file.html", "A", 1, 0, 0, 0, 0, false), insertHost("file:///some/path/to/file.html", "A", 1, 0, 0, 0, 0, false),
insertHost("file:///another/file.html", "A", 1, 0, 0, 0, 0, false), insertHost("file:///another/file.html", "A", 1, 0, 0, 0, 0, false),
insertHost("moz-nullprincipal:{8695105a-adbe-4e4e-8083-851faa5ca2d7}", "A", 1, 0, 0, 0, 0, false), insertHost(
insertHost("moz-nullprincipal:{12ahjksd-akjs-asd3-8393-asdu2189asdu}", "B", 1, 0, 0, 0, 0, false), "moz-nullprincipal:{8695105a-adbe-4e4e-8083-851faa5ca2d7}",
"A",
1,
0,
0,
0,
0,
false
),
insertHost(
"moz-nullprincipal:{12ahjksd-akjs-asd3-8393-asdu2189asdu}",
"B",
1,
0,
0,
0,
0,
false
),
insertHost("<file>", "A", 1, 0, 0, 0, 0, false), insertHost("<file>", "A", 1, 0, 0, 0, 0, false),
insertHost("<file>", "B", 1, 0, 0, 0, 0, false), insertHost("<file>", "B", 1, 0, 0, 0, 0, false),
]; ];
@ -171,7 +206,7 @@ add_task(function test() {
["https://263.123.555.676", "A", 1, 0, 0], ["https://263.123.555.676", "A", 1, 0, 0],
]; ];
let found = expected.map((it) => 0); let found = expected.map(it => 0);
// This will force the permission-manager to reload the data. // This will force the permission-manager to reload the data.
Services.obs.notifyObservers(null, "testonly-reload-permissions-from-disk"); Services.obs.notifyObservers(null, "testonly-reload-permissions-from-disk");
@ -181,28 +216,43 @@ add_task(function test() {
let isExpected = false; let isExpected = false;
expected.forEach((it, i) => { expected.forEach((it, i) => {
if (permission.principal.origin == it[0] && if (
permission.type == it[1] && permission.principal.origin == it[0] &&
permission.capability == it[2] && permission.type == it[1] &&
permission.expireType == it[3] && permission.capability == it[2] &&
permission.expireTime == it[4]) { permission.expireType == it[3] &&
permission.expireTime == it[4]
) {
isExpected = true; isExpected = true;
found[i]++; found[i]++;
} }
}); });
Assert.ok(isExpected, Assert.ok(
"Permission " + (isExpected ? "should" : "shouldn't") + isExpected,
" be in permission database: " + "Permission " +
permission.principal.origin + ", " + (isExpected ? "should" : "shouldn't") +
permission.type + ", " + " be in permission database: " +
permission.capability + ", " + permission.principal.origin +
permission.expireType + ", " + ", " +
permission.expireTime); permission.type +
", " +
permission.capability +
", " +
permission.expireType +
", " +
permission.expireTime
);
} }
found.forEach((count, i) => { found.forEach((count, i) => {
Assert.ok(count == 1, "Expected count = 1, got count = " + count + " for permission " + expected[i]); Assert.ok(
count == 1,
"Expected count = 1, got count = " +
count +
" for permission " +
expected[i]
);
}); });
// Check to make sure that all of the tables which we care about are present // Check to make sure that all of the tables which we care about are present

View file

@ -1,13 +1,15 @@
/* Any copyright is dedicated to the Public Domain. /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
ChromeUtils.defineModuleGetter(this, "PlacesTestUtils", ChromeUtils.defineModuleGetter(
"resource://testing-common/PlacesTestUtils.jsm"); this,
"PlacesTestUtils",
"resource://testing-common/PlacesTestUtils.jsm"
);
var PERMISSIONS_FILE_NAME = "permissions.sqlite"; var PERMISSIONS_FILE_NAME = "permissions.sqlite";
function GetPermissionsFile(profile) function GetPermissionsFile(profile) {
{
let file = profile.clone(); let file = profile.clone();
file.append(PERMISSIONS_FILE_NAME); file.append(PERMISSIONS_FILE_NAME);
return file; return file;
@ -35,14 +37,16 @@ add_task(async function test() {
",expireType INTEGER" + ",expireType INTEGER" +
",expireTime INTEGER" + ",expireTime INTEGER" +
",modificationTime INTEGER" + ",modificationTime INTEGER" +
")"); ")"
);
let stmt5Insert = db.createStatement( let stmt5Insert = db.createStatement(
"INSERT INTO moz_hosts (" + "INSERT INTO moz_hosts (" +
"id, origin, type, permission, expireType, expireTime, modificationTime" + "id, origin, type, permission, expireType, expireTime, modificationTime" +
") VALUES (" + ") VALUES (" +
":id, :origin, :type, :permission, :expireType, :expireTime, :modificationTime" + ":id, :origin, :type, :permission, :expireType, :expireTime, :modificationTime" +
")"); ")"
);
/* /*
* V4 table * V4 table
@ -58,18 +62,27 @@ add_task(async function test() {
",modificationTime INTEGER" + ",modificationTime INTEGER" +
",appId INTEGER" + ",appId INTEGER" +
",isInBrowserElement INTEGER" + ",isInBrowserElement INTEGER" +
")"); ")"
);
let stmtInsert = db.createStatement( let stmtInsert = db.createStatement(
"INSERT INTO moz_hosts_v4 (" + "INSERT INTO moz_hosts_v4 (" +
"id, host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement" + "id, host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement" +
") VALUES (" + ") VALUES (" +
":id, :host, :type, :permission, :expireType, :expireTime, :modificationTime, :appId, :isInBrowserElement" + ":id, :host, :type, :permission, :expireType, :expireTime, :modificationTime, :appId, :isInBrowserElement" +
")"); ")"
);
let id = 0; let id = 0;
function insertOrigin(origin, type, permission, expireType, expireTime, modificationTime) { function insertOrigin(
origin,
type,
permission,
expireType,
expireTime,
modificationTime
) {
let thisId = id++; let thisId = id++;
stmt5Insert.bindByName("id", thisId); stmt5Insert.bindByName("id", thisId);
@ -93,11 +106,20 @@ add_task(async function test() {
permission, permission,
expireType, expireType,
expireTime, expireTime,
modificationTime modificationTime,
}; };
} }
function insertHost(host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement) { function insertHost(
host,
type,
permission,
expireType,
expireTime,
modificationTime,
appId,
isInBrowserElement
) {
let thisId = id++; let thisId = id++;
stmtInsert.bindByName("id", thisId); stmtInsert.bindByName("id", thisId);
@ -125,7 +147,7 @@ add_task(async function test() {
expireTime, expireTime,
modificationTime, modificationTime,
appId, appId,
isInBrowserElement isInBrowserElement,
}; };
} }
@ -151,8 +173,26 @@ add_task(async function test() {
insertHost("192.0.2.235", "A", 1, 0, 0, 0, 0, false), insertHost("192.0.2.235", "A", 1, 0, 0, 0, 0, false),
insertHost("file:///some/path/to/file.html", "A", 1, 0, 0, 0, 0, false), insertHost("file:///some/path/to/file.html", "A", 1, 0, 0, 0, 0, false),
insertHost("file:///another/file.html", "A", 1, 0, 0, 0, 0, false), insertHost("file:///another/file.html", "A", 1, 0, 0, 0, 0, false),
insertHost("moz-nullprincipal:{8695105a-adbe-4e4e-8083-851faa5ca2d7}", "A", 1, 0, 0, 0, 0, false), insertHost(
insertHost("moz-nullprincipal:{12ahjksd-akjs-asd3-8393-asdu2189asdu}", "B", 1, 0, 0, 0, 0, false), "moz-nullprincipal:{8695105a-adbe-4e4e-8083-851faa5ca2d7}",
"A",
1,
0,
0,
0,
0,
false
),
insertHost(
"moz-nullprincipal:{12ahjksd-akjs-asd3-8393-asdu2189asdu}",
"B",
1,
0,
0,
0,
0,
false
),
insertHost("<file>", "A", 1, 0, 0, 0, 0, false), insertHost("<file>", "A", 1, 0, 0, 0, 0, false),
insertHost("<file>", "B", 1, 0, 0, 0, 0, false), insertHost("<file>", "B", 1, 0, 0, 0, 0, false),
]; ];
@ -209,11 +249,15 @@ add_task(async function test() {
["https://192.0.2.235", "A", 1, 0, 0], ["https://192.0.2.235", "A", 1, 0, 0],
]; ];
let found = expected.map((it) => 0); let found = expected.map(it => 0);
// Add some places to the places database // Add some places to the places database
await PlacesTestUtils.addVisits(Services.io.newURI("https://foo.com/some/other/subdirectory")); await PlacesTestUtils.addVisits(
await PlacesTestUtils.addVisits(Services.io.newURI("ftp://some.subdomain.of.foo.com:8000/some/subdirectory")); Services.io.newURI("https://foo.com/some/other/subdirectory")
);
await PlacesTestUtils.addVisits(
Services.io.newURI("ftp://some.subdomain.of.foo.com:8000/some/subdirectory")
);
// This will force the permission-manager to reload the data. // This will force the permission-manager to reload the data.
Services.obs.notifyObservers(null, "testonly-reload-permissions-from-disk"); Services.obs.notifyObservers(null, "testonly-reload-permissions-from-disk");
@ -223,28 +267,43 @@ add_task(async function test() {
let isExpected = false; let isExpected = false;
expected.forEach((it, i) => { expected.forEach((it, i) => {
if (permission.principal.origin == it[0] && if (
permission.type == it[1] && permission.principal.origin == it[0] &&
permission.capability == it[2] && permission.type == it[1] &&
permission.expireType == it[3] && permission.capability == it[2] &&
permission.expireTime == it[4]) { permission.expireType == it[3] &&
permission.expireTime == it[4]
) {
isExpected = true; isExpected = true;
found[i]++; found[i]++;
} }
}); });
Assert.ok(isExpected, Assert.ok(
"Permission " + (isExpected ? "should" : "shouldn't") + isExpected,
" be in permission database: " + "Permission " +
permission.principal.origin + ", " + (isExpected ? "should" : "shouldn't") +
permission.type + ", " + " be in permission database: " +
permission.capability + ", " + permission.principal.origin +
permission.expireType + ", " + ", " +
permission.expireTime); permission.type +
", " +
permission.capability +
", " +
permission.expireType +
", " +
permission.expireTime
);
} }
found.forEach((count, i) => { found.forEach((count, i) => {
Assert.ok(count == 1, "Expected count = 1, got count = " + count + " for permission " + expected[i]); Assert.ok(
count == 1,
"Expected count = 1, got count = " +
count +
" for permission " +
expected[i]
);
}); });
// Check to make sure that all of the tables which we care about are present // Check to make sure that all of the tables which we care about are present
@ -265,12 +324,14 @@ add_task(async function test() {
} }
// Check that the moz_perms_v6 table contains the backup of the entry we created // Check that the moz_perms_v6 table contains the backup of the entry we created
let mozPermsV6Stmt = db.createStatement("SELECT " + let mozPermsV6Stmt = db.createStatement(
"origin, type, permission, expireType, expireTime, modificationTime " + "SELECT " +
"FROM moz_perms_v6 WHERE id = :id"); "origin, type, permission, expireType, expireTime, modificationTime " +
"FROM moz_perms_v6 WHERE id = :id"
);
try { try {
// Check that the moz_hosts table still contains the correct values. // Check that the moz_hosts table still contains the correct values.
created5.forEach((it) => { created5.forEach(it => {
mozPermsV6Stmt.reset(); mozPermsV6Stmt.reset();
mozPermsV6Stmt.bindByName("id", it.id); mozPermsV6Stmt.bindByName("id", it.id);
mozPermsV6Stmt.executeStep(); mozPermsV6Stmt.executeStep();
@ -286,7 +347,9 @@ add_task(async function test() {
} }
// Check that there are the right number of values // Check that there are the right number of values
let mozPermsV6Count = db.createStatement("SELECT count(*) FROM moz_perms_v6"); let mozPermsV6Count = db.createStatement(
"SELECT count(*) FROM moz_perms_v6"
);
try { try {
mozPermsV6Count.executeStep(); mozPermsV6Count.executeStep();
Assert.equal(mozPermsV6Count.getInt64(0), created5.length); Assert.equal(mozPermsV6Count.getInt64(0), created5.length);

View file

@ -1,13 +1,15 @@
/* Any copyright is dedicated to the Public Domain. /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
ChromeUtils.defineModuleGetter(this, "PlacesTestUtils", ChromeUtils.defineModuleGetter(
"resource://testing-common/PlacesTestUtils.jsm"); this,
"PlacesTestUtils",
"resource://testing-common/PlacesTestUtils.jsm"
);
var PERMISSIONS_FILE_NAME = "permissions.sqlite"; var PERMISSIONS_FILE_NAME = "permissions.sqlite";
function GetPermissionsFile(profile) function GetPermissionsFile(profile) {
{
let file = profile.clone(); let file = profile.clone();
file.append(PERMISSIONS_FILE_NAME); file.append(PERMISSIONS_FILE_NAME);
return file; return file;
@ -35,18 +37,27 @@ add_task(function test() {
",expireType INTEGER" + ",expireType INTEGER" +
",expireTime INTEGER" + ",expireTime INTEGER" +
",modificationTime INTEGER" + ",modificationTime INTEGER" +
")"); ")"
);
let stmt5Insert = db.createStatement( let stmt5Insert = db.createStatement(
"INSERT INTO moz_hosts (" + "INSERT INTO moz_hosts (" +
"id, origin, type, permission, expireType, expireTime, modificationTime" + "id, origin, type, permission, expireType, expireTime, modificationTime" +
") VALUES (" + ") VALUES (" +
":id, :origin, :type, :permission, :expireType, :expireTime, :modificationTime" + ":id, :origin, :type, :permission, :expireType, :expireTime, :modificationTime" +
")"); ")"
);
let id = 0; let id = 0;
function insertOrigin(origin, type, permission, expireType, expireTime, modificationTime) { function insertOrigin(
origin,
type,
permission,
expireType,
expireTime,
modificationTime
) {
let thisId = id++; let thisId = id++;
stmt5Insert.bindByName("id", thisId); stmt5Insert.bindByName("id", thisId);
@ -70,7 +81,7 @@ add_task(function test() {
permission, permission,
expireType, expireType,
expireTime, expireTime,
modificationTime modificationTime,
}; };
} }
@ -100,7 +111,7 @@ add_task(function test() {
["http://localhost", "B", 2, 0, 0, 0], ["http://localhost", "B", 2, 0, 0, 0],
]; ];
let found = expected.map((it) => 0); let found = expected.map(it => 0);
// This will force the permission-manager to reload the data. // This will force the permission-manager to reload the data.
Services.obs.notifyObservers(null, "testonly-reload-permissions-from-disk"); Services.obs.notifyObservers(null, "testonly-reload-permissions-from-disk");
@ -110,28 +121,43 @@ add_task(function test() {
let isExpected = false; let isExpected = false;
expected.forEach((it, i) => { expected.forEach((it, i) => {
if (permission.principal.origin == it[0] && if (
permission.type == it[1] && permission.principal.origin == it[0] &&
permission.capability == it[2] && permission.type == it[1] &&
permission.expireType == it[3] && permission.capability == it[2] &&
permission.expireTime == it[4]) { permission.expireType == it[3] &&
permission.expireTime == it[4]
) {
isExpected = true; isExpected = true;
found[i]++; found[i]++;
} }
}); });
Assert.ok(isExpected, Assert.ok(
"Permission " + (isExpected ? "should" : "shouldn't") + isExpected,
" be in permission database: " + "Permission " +
permission.principal.origin + ", " + (isExpected ? "should" : "shouldn't") +
permission.type + ", " + " be in permission database: " +
permission.capability + ", " + permission.principal.origin +
permission.expireType + ", " + ", " +
permission.expireTime); permission.type +
", " +
permission.capability +
", " +
permission.expireType +
", " +
permission.expireTime
);
} }
found.forEach((count, i) => { found.forEach((count, i) => {
Assert.ok(count == 1, "Expected count = 1, got count = " + count + " for permission " + expected[i]); Assert.ok(
count == 1,
"Expected count = 1, got count = " +
count +
" for permission " +
expected[i]
);
}); });
// Check to make sure that all of the tables which we care about are present // Check to make sure that all of the tables which we care about are present
@ -142,13 +168,15 @@ add_task(function test() {
Assert.ok(!db.tableExists("moz_hosts_is_backup")); Assert.ok(!db.tableExists("moz_hosts_is_backup"));
Assert.ok(!db.tableExists("moz_perms_v6")); Assert.ok(!db.tableExists("moz_perms_v6"));
let mozHostsStmt = db.createStatement("SELECT " + let mozHostsStmt = db.createStatement(
"host, type, permission, expireType, expireTime, " + "SELECT " +
"modificationTime, isInBrowserElement " + "host, type, permission, expireType, expireTime, " +
"FROM moz_hosts WHERE id = :id"); "modificationTime, isInBrowserElement " +
"FROM moz_hosts WHERE id = :id"
);
try { try {
// Check that the moz_hosts table still contains the correct values. // Check that the moz_hosts table still contains the correct values.
created4.forEach((it) => { created4.forEach(it => {
mozHostsStmt.reset(); mozHostsStmt.reset();
mozHostsStmt.bindByName("id", it.id); mozHostsStmt.bindByName("id", it.id);
mozHostsStmt.executeStep(); mozHostsStmt.executeStep();

View file

@ -1,13 +1,15 @@
/* Any copyright is dedicated to the Public Domain. /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
ChromeUtils.defineModuleGetter(this, "PlacesTestUtils", ChromeUtils.defineModuleGetter(
"resource://testing-common/PlacesTestUtils.jsm"); this,
"PlacesTestUtils",
"resource://testing-common/PlacesTestUtils.jsm"
);
var PERMISSIONS_FILE_NAME = "permissions.sqlite"; var PERMISSIONS_FILE_NAME = "permissions.sqlite";
function GetPermissionsFile(profile) function GetPermissionsFile(profile) {
{
let file = profile.clone(); let file = profile.clone();
file.append(PERMISSIONS_FILE_NAME); file.append(PERMISSIONS_FILE_NAME);
return file; return file;
@ -35,14 +37,16 @@ add_task(async function test() {
",expireType INTEGER" + ",expireType INTEGER" +
",expireTime INTEGER" + ",expireTime INTEGER" +
",modificationTime INTEGER" + ",modificationTime INTEGER" +
")"); ")"
);
let stmt6Insert = db.createStatement( let stmt6Insert = db.createStatement(
"INSERT INTO moz_perms (" + "INSERT INTO moz_perms (" +
"id, origin, type, permission, expireType, expireTime, modificationTime" + "id, origin, type, permission, expireType, expireTime, modificationTime" +
") VALUES (" + ") VALUES (" +
":id, :origin, :type, :permission, :expireType, :expireTime, :modificationTime" + ":id, :origin, :type, :permission, :expireType, :expireTime, :modificationTime" +
")"); ")"
);
/* /*
* V4 table * V4 table
@ -58,18 +62,27 @@ add_task(async function test() {
",modificationTime INTEGER" + ",modificationTime INTEGER" +
",appId INTEGER" + ",appId INTEGER" +
",isInBrowserElement INTEGER" + ",isInBrowserElement INTEGER" +
")"); ")"
);
let stmtInsert = db.createStatement( let stmtInsert = db.createStatement(
"INSERT INTO moz_hosts (" + "INSERT INTO moz_hosts (" +
"id, host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement" + "id, host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement" +
") VALUES (" + ") VALUES (" +
":id, :host, :type, :permission, :expireType, :expireTime, :modificationTime, :appId, :isInBrowserElement" + ":id, :host, :type, :permission, :expireType, :expireTime, :modificationTime, :appId, :isInBrowserElement" +
")"); ")"
);
let id = 0; let id = 0;
function insertOrigin(origin, type, permission, expireType, expireTime, modificationTime) { function insertOrigin(
origin,
type,
permission,
expireType,
expireTime,
modificationTime
) {
let thisId = id++; let thisId = id++;
stmt6Insert.bindByName("id", thisId); stmt6Insert.bindByName("id", thisId);
@ -93,11 +106,20 @@ add_task(async function test() {
permission, permission,
expireType, expireType,
expireTime, expireTime,
modificationTime modificationTime,
}; };
} }
function insertHost(host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement) { function insertHost(
host,
type,
permission,
expireType,
expireTime,
modificationTime,
appId,
isInBrowserElement
) {
let thisId = id++; let thisId = id++;
stmtInsert.bindByName("id", thisId); stmtInsert.bindByName("id", thisId);
@ -125,7 +147,7 @@ add_task(async function test() {
expireTime, expireTime,
modificationTime, modificationTime,
appId, appId,
isInBrowserElement isInBrowserElement,
}; };
} }
@ -151,8 +173,26 @@ add_task(async function test() {
insertHost("192.0.2.235", "A", 1, 0, 0, 0, 0, false), insertHost("192.0.2.235", "A", 1, 0, 0, 0, 0, false),
insertHost("file:///some/path/to/file.html", "A", 1, 0, 0, 0, 0, false), insertHost("file:///some/path/to/file.html", "A", 1, 0, 0, 0, 0, false),
insertHost("file:///another/file.html", "A", 1, 0, 0, 0, 0, false), insertHost("file:///another/file.html", "A", 1, 0, 0, 0, 0, false),
insertHost("moz-nullprincipal:{8695105a-adbe-4e4e-8083-851faa5ca2d7}", "A", 1, 0, 0, 0, 0, false), insertHost(
insertHost("moz-nullprincipal:{12ahjksd-akjs-asd3-8393-asdu2189asdu}", "B", 1, 0, 0, 0, 0, false), "moz-nullprincipal:{8695105a-adbe-4e4e-8083-851faa5ca2d7}",
"A",
1,
0,
0,
0,
0,
false
),
insertHost(
"moz-nullprincipal:{12ahjksd-akjs-asd3-8393-asdu2189asdu}",
"B",
1,
0,
0,
0,
0,
false
),
insertHost("<file>", "A", 1, 0, 0, 0, 0, false), insertHost("<file>", "A", 1, 0, 0, 0, 0, false),
insertHost("<file>", "B", 1, 0, 0, 0, 0, false), insertHost("<file>", "B", 1, 0, 0, 0, 0, false),
]; ];
@ -209,11 +249,15 @@ add_task(async function test() {
["https://192.0.2.235", "A", 1, 0, 0], ["https://192.0.2.235", "A", 1, 0, 0],
]; ];
let found = expected.map((it) => 0); let found = expected.map(it => 0);
// Add some places to the places database // Add some places to the places database
await PlacesTestUtils.addVisits(Services.io.newURI("https://foo.com/some/other/subdirectory")); await PlacesTestUtils.addVisits(
await PlacesTestUtils.addVisits(Services.io.newURI("ftp://some.subdomain.of.foo.com:8000/some/subdirectory")); Services.io.newURI("https://foo.com/some/other/subdirectory")
);
await PlacesTestUtils.addVisits(
Services.io.newURI("ftp://some.subdomain.of.foo.com:8000/some/subdirectory")
);
// This will force the permission-manager to reload the data. // This will force the permission-manager to reload the data.
Services.obs.notifyObservers(null, "testonly-reload-permissions-from-disk"); Services.obs.notifyObservers(null, "testonly-reload-permissions-from-disk");
@ -223,28 +267,43 @@ add_task(async function test() {
let isExpected = false; let isExpected = false;
expected.forEach((it, i) => { expected.forEach((it, i) => {
if (permission.principal.origin == it[0] && if (
permission.type == it[1] && permission.principal.origin == it[0] &&
permission.capability == it[2] && permission.type == it[1] &&
permission.expireType == it[3] && permission.capability == it[2] &&
permission.expireTime == it[4]) { permission.expireType == it[3] &&
permission.expireTime == it[4]
) {
isExpected = true; isExpected = true;
found[i]++; found[i]++;
} }
}); });
Assert.ok(isExpected, Assert.ok(
"Permission " + (isExpected ? "should" : "shouldn't") + isExpected,
" be in permission database: " + "Permission " +
permission.principal.origin + ", " + (isExpected ? "should" : "shouldn't") +
permission.type + ", " + " be in permission database: " +
permission.capability + ", " + permission.principal.origin +
permission.expireType + ", " + ", " +
permission.expireTime); permission.type +
", " +
permission.capability +
", " +
permission.expireType +
", " +
permission.expireTime
);
} }
found.forEach((count, i) => { found.forEach((count, i) => {
Assert.ok(count == 1, "Expected count = 1, got count = " + count + " for permission " + expected[i]); Assert.ok(
count == 1,
"Expected count = 1, got count = " +
count +
" for permission " +
expected[i]
);
}); });
// Check to make sure that all of the tables which we care about are present // Check to make sure that all of the tables which we care about are present
@ -265,12 +324,14 @@ add_task(async function test() {
} }
// Check that the moz_perms_v6 table contains the backup of the entry we created // Check that the moz_perms_v6 table contains the backup of the entry we created
let mozPermsV6Stmt = db.createStatement("SELECT " + let mozPermsV6Stmt = db.createStatement(
"origin, type, permission, expireType, expireTime, modificationTime " + "SELECT " +
"FROM moz_perms_v6 WHERE id = :id"); "origin, type, permission, expireType, expireTime, modificationTime " +
"FROM moz_perms_v6 WHERE id = :id"
);
try { try {
// Check that the moz_hosts table still contains the correct values. // Check that the moz_hosts table still contains the correct values.
created6.forEach((it) => { created6.forEach(it => {
mozPermsV6Stmt.reset(); mozPermsV6Stmt.reset();
mozPermsV6Stmt.bindByName("id", it.id); mozPermsV6Stmt.bindByName("id", it.id);
mozPermsV6Stmt.executeStep(); mozPermsV6Stmt.executeStep();
@ -286,7 +347,9 @@ add_task(async function test() {
} }
// Check that there are the right number of values // Check that there are the right number of values
let mozPermsV6Count = db.createStatement("SELECT count(*) FROM moz_perms_v6"); let mozPermsV6Count = db.createStatement(
"SELECT count(*) FROM moz_perms_v6"
);
try { try {
mozPermsV6Count.executeStep(); mozPermsV6Count.executeStep();
Assert.equal(mozPermsV6Count.getInt64(0), created6.length); Assert.equal(mozPermsV6Count.getInt64(0), created6.length);

View file

@ -1,13 +1,15 @@
/* Any copyright is dedicated to the Public Domain. /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
ChromeUtils.defineModuleGetter(this, "PlacesTestUtils", ChromeUtils.defineModuleGetter(
"resource://testing-common/PlacesTestUtils.jsm"); this,
"PlacesTestUtils",
"resource://testing-common/PlacesTestUtils.jsm"
);
var PERMISSIONS_FILE_NAME = "permissions.sqlite"; var PERMISSIONS_FILE_NAME = "permissions.sqlite";
function GetPermissionsFile(profile) function GetPermissionsFile(profile) {
{
let file = profile.clone(); let file = profile.clone();
file.append(PERMISSIONS_FILE_NAME); file.append(PERMISSIONS_FILE_NAME);
return file; return file;
@ -35,18 +37,27 @@ add_task(function test() {
",expireType INTEGER" + ",expireType INTEGER" +
",expireTime INTEGER" + ",expireTime INTEGER" +
",modificationTime INTEGER" + ",modificationTime INTEGER" +
")"); ")"
);
let stmt6Insert = db.createStatement( let stmt6Insert = db.createStatement(
"INSERT INTO moz_perms (" + "INSERT INTO moz_perms (" +
"id, origin, type, permission, expireType, expireTime, modificationTime" + "id, origin, type, permission, expireType, expireTime, modificationTime" +
") VALUES (" + ") VALUES (" +
":id, :origin, :type, :permission, :expireType, :expireTime, :modificationTime" + ":id, :origin, :type, :permission, :expireType, :expireTime, :modificationTime" +
")"); ")"
);
let id = 0; let id = 0;
function insertOrigin(origin, type, permission, expireType, expireTime, modificationTime) { function insertOrigin(
origin,
type,
permission,
expireType,
expireTime,
modificationTime
) {
let thisId = id++; let thisId = id++;
stmt6Insert.bindByName("id", thisId); stmt6Insert.bindByName("id", thisId);
@ -70,7 +81,7 @@ add_task(function test() {
permission, permission,
expireType, expireType,
expireTime, expireTime,
modificationTime modificationTime,
}; };
} }
@ -91,10 +102,10 @@ add_task(function test() {
let expected = [ let expected = [
["https://foo.com", "A", 2, 0, 0, 0], ["https://foo.com", "A", 2, 0, 0, 0],
["http://foo.com", "A", 2, 0, 0, 0], ["http://foo.com", "A", 2, 0, 0, 0],
["http://foo.com^inBrowser=1", "A", 2, 0, 0, 0] ["http://foo.com^inBrowser=1", "A", 2, 0, 0, 0],
]; ];
let found = expected.map((it) => 0); let found = expected.map(it => 0);
// This will force the permission-manager to reload the data. // This will force the permission-manager to reload the data.
Services.obs.notifyObservers(null, "testonly-reload-permissions-from-disk"); Services.obs.notifyObservers(null, "testonly-reload-permissions-from-disk");
@ -104,28 +115,43 @@ add_task(function test() {
let isExpected = false; let isExpected = false;
expected.forEach((it, i) => { expected.forEach((it, i) => {
if (permission.principal.origin == it[0] && if (
permission.type == it[1] && permission.principal.origin == it[0] &&
permission.capability == it[2] && permission.type == it[1] &&
permission.expireType == it[3] && permission.capability == it[2] &&
permission.expireTime == it[4]) { permission.expireType == it[3] &&
permission.expireTime == it[4]
) {
isExpected = true; isExpected = true;
found[i]++; found[i]++;
} }
}); });
Assert.ok(isExpected, Assert.ok(
"Permission " + (isExpected ? "should" : "shouldn't") + isExpected,
" be in permission database: " + "Permission " +
permission.principal.origin + ", " + (isExpected ? "should" : "shouldn't") +
permission.type + ", " + " be in permission database: " +
permission.capability + ", " + permission.principal.origin +
permission.expireType + ", " + ", " +
permission.expireTime); permission.type +
", " +
permission.capability +
", " +
permission.expireType +
", " +
permission.expireTime
);
} }
found.forEach((count, i) => { found.forEach((count, i) => {
Assert.ok(count == 1, "Expected count = 1, got count = " + count + " for permission " + expected[i]); Assert.ok(
count == 1,
"Expected count = 1, got count = " +
count +
" for permission " +
expected[i]
);
}); });
// Check to make sure that all of the tables which we care about are present // Check to make sure that all of the tables which we care about are present
@ -136,13 +162,15 @@ add_task(function test() {
Assert.ok(!db.tableExists("moz_hosts_is_backup")); Assert.ok(!db.tableExists("moz_hosts_is_backup"));
Assert.ok(!db.tableExists("moz_perms_v6")); Assert.ok(!db.tableExists("moz_perms_v6"));
let mozHostsStmt = db.createStatement("SELECT " + let mozHostsStmt = db.createStatement(
"host, type, permission, expireType, expireTime, " + "SELECT " +
"modificationTime, isInBrowserElement " + "host, type, permission, expireType, expireTime, " +
"FROM moz_hosts WHERE id = :id"); "modificationTime, isInBrowserElement " +
"FROM moz_hosts WHERE id = :id"
);
try { try {
// Check that the moz_hosts table still contains the correct values. // Check that the moz_hosts table still contains the correct values.
created4.forEach((it) => { created4.forEach(it => {
mozHostsStmt.reset(); mozHostsStmt.reset();
mozHostsStmt.bindByName("id", it.id); mozHostsStmt.bindByName("id", it.id);
mozHostsStmt.executeStep(); mozHostsStmt.executeStep();

View file

@ -1,13 +1,15 @@
/* Any copyright is dedicated to the Public Domain. /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
ChromeUtils.defineModuleGetter(this, "PlacesTestUtils", ChromeUtils.defineModuleGetter(
"resource://testing-common/PlacesTestUtils.jsm"); this,
"PlacesTestUtils",
"resource://testing-common/PlacesTestUtils.jsm"
);
var PERMISSIONS_FILE_NAME = "permissions.sqlite"; var PERMISSIONS_FILE_NAME = "permissions.sqlite";
function GetPermissionsFile(profile) function GetPermissionsFile(profile) {
{
let file = profile.clone(); let file = profile.clone();
file.append(PERMISSIONS_FILE_NAME); file.append(PERMISSIONS_FILE_NAME);
return file; return file;
@ -35,14 +37,16 @@ add_task(async function test() {
",expireType INTEGER" + ",expireType INTEGER" +
",expireTime INTEGER" + ",expireTime INTEGER" +
",modificationTime INTEGER" + ",modificationTime INTEGER" +
")"); ")"
);
let stmt6Insert = db.createStatement( let stmt6Insert = db.createStatement(
"INSERT INTO moz_perms (" + "INSERT INTO moz_perms (" +
"id, origin, type, permission, expireType, expireTime, modificationTime" + "id, origin, type, permission, expireType, expireTime, modificationTime" +
") VALUES (" + ") VALUES (" +
":id, :origin, :type, :permission, :expireType, :expireTime, :modificationTime" + ":id, :origin, :type, :permission, :expireType, :expireTime, :modificationTime" +
")"); ")"
);
/* /*
* V4 table * V4 table
@ -58,23 +62,34 @@ add_task(async function test() {
",modificationTime INTEGER" + ",modificationTime INTEGER" +
",appId INTEGER" + ",appId INTEGER" +
",isInBrowserElement INTEGER" + ",isInBrowserElement INTEGER" +
")"); ")"
);
let stmtInsert = db.createStatement( let stmtInsert = db.createStatement(
"INSERT INTO moz_hosts (" + "INSERT INTO moz_hosts (" +
"id, host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement" + "id, host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement" +
") VALUES (" + ") VALUES (" +
":id, :host, :type, :permission, :expireType, :expireTime, :modificationTime, :appId, :isInBrowserElement" + ":id, :host, :type, :permission, :expireType, :expireTime, :modificationTime, :appId, :isInBrowserElement" +
")"); ")"
);
/* /*
* The v4 table is a backup * The v4 table is a backup
*/ */
db.executeSimpleSQL("CREATE TABLE moz_hosts_is_backup (dummy INTEGER PRIMARY KEY)"); db.executeSimpleSQL(
"CREATE TABLE moz_hosts_is_backup (dummy INTEGER PRIMARY KEY)"
);
let id = 0; let id = 0;
function insertOrigin(origin, type, permission, expireType, expireTime, modificationTime) { function insertOrigin(
origin,
type,
permission,
expireType,
expireTime,
modificationTime
) {
let thisId = id++; let thisId = id++;
stmt6Insert.bindByName("id", thisId); stmt6Insert.bindByName("id", thisId);
@ -98,11 +113,20 @@ add_task(async function test() {
permission, permission,
expireType, expireType,
expireTime, expireTime,
modificationTime modificationTime,
}; };
} }
function insertHost(host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement) { function insertHost(
host,
type,
permission,
expireType,
expireTime,
modificationTime,
appId,
isInBrowserElement
) {
let thisId = id++; let thisId = id++;
stmtInsert.bindByName("id", thisId); stmtInsert.bindByName("id", thisId);
@ -130,7 +154,7 @@ add_task(async function test() {
expireTime, expireTime,
modificationTime, modificationTime,
appId, appId,
isInBrowserElement isInBrowserElement,
}; };
} }
@ -161,8 +185,26 @@ add_task(async function test() {
insertHost("2001:db8::ff00:42:8329", "C", 1, 0, 0, 0, 0, false), insertHost("2001:db8::ff00:42:8329", "C", 1, 0, 0, 0, 0, false),
insertHost("file:///some/path/to/file.html", "A", 1, 0, 0, 0, 0, false), insertHost("file:///some/path/to/file.html", "A", 1, 0, 0, 0, 0, false),
insertHost("file:///another/file.html", "A", 1, 0, 0, 0, 0, false), insertHost("file:///another/file.html", "A", 1, 0, 0, 0, 0, false),
insertHost("moz-nullprincipal:{8695105a-adbe-4e4e-8083-851faa5ca2d7}", "A", 1, 0, 0, 0, 0, false), insertHost(
insertHost("moz-nullprincipal:{12ahjksd-akjs-asd3-8393-asdu2189asdu}", "B", 1, 0, 0, 0, 0, false), "moz-nullprincipal:{8695105a-adbe-4e4e-8083-851faa5ca2d7}",
"A",
1,
0,
0,
0,
0,
false
),
insertHost(
"moz-nullprincipal:{12ahjksd-akjs-asd3-8393-asdu2189asdu}",
"B",
1,
0,
0,
0,
0,
false
),
insertHost("<file>", "A", 1, 0, 0, 0, 0, false), insertHost("<file>", "A", 1, 0, 0, 0, 0, false),
insertHost("<file>", "B", 1, 0, 0, 0, 0, false), insertHost("<file>", "B", 1, 0, 0, 0, 0, false),
]; ];
@ -192,11 +234,15 @@ add_task(async function test() {
["https://192.0.2.235", "A", 2, 0, 0], ["https://192.0.2.235", "A", 2, 0, 0],
]; ];
let found = expected.map((it) => 0); let found = expected.map(it => 0);
// Add some places to the places database // Add some places to the places database
await PlacesTestUtils.addVisits(Services.io.newURI("https://foo.com/some/other/subdirectory")); await PlacesTestUtils.addVisits(
await PlacesTestUtils.addVisits(Services.io.newURI("ftp://some.subdomain.of.foo.com:8000/some/subdirectory")); Services.io.newURI("https://foo.com/some/other/subdirectory")
);
await PlacesTestUtils.addVisits(
Services.io.newURI("ftp://some.subdomain.of.foo.com:8000/some/subdirectory")
);
await PlacesTestUtils.addVisits(Services.io.newURI("ftp://127.0.0.1:8080")); await PlacesTestUtils.addVisits(Services.io.newURI("ftp://127.0.0.1:8080"));
await PlacesTestUtils.addVisits(Services.io.newURI("https://localhost:8080")); await PlacesTestUtils.addVisits(Services.io.newURI("https://localhost:8080"));
@ -208,28 +254,43 @@ add_task(async function test() {
let isExpected = false; let isExpected = false;
expected.forEach((it, i) => { expected.forEach((it, i) => {
if (permission.principal.origin == it[0] && if (
permission.type == it[1] && permission.principal.origin == it[0] &&
permission.capability == it[2] && permission.type == it[1] &&
permission.expireType == it[3] && permission.capability == it[2] &&
permission.expireTime == it[4]) { permission.expireType == it[3] &&
permission.expireTime == it[4]
) {
isExpected = true; isExpected = true;
found[i]++; found[i]++;
} }
}); });
Assert.ok(isExpected, Assert.ok(
"Permission " + (isExpected ? "should" : "shouldn't") + isExpected,
" be in permission database: " + "Permission " +
permission.principal.origin + ", " + (isExpected ? "should" : "shouldn't") +
permission.type + ", " + " be in permission database: " +
permission.capability + ", " + permission.principal.origin +
permission.expireType + ", " + ", " +
permission.expireTime); permission.type +
", " +
permission.capability +
", " +
permission.expireType +
", " +
permission.expireTime
);
} }
found.forEach((count, i) => { found.forEach((count, i) => {
Assert.ok(count == 1, "Expected count = 1, got count = " + count + " for permission " + expected[i]); Assert.ok(
count == 1,
"Expected count = 1, got count = " +
count +
" for permission " +
expected[i]
);
}); });
// Check to make sure that all of the tables which we care about are present // Check to make sure that all of the tables which we care about are present

View file

@ -1,13 +1,15 @@
/* Any copyright is dedicated to the Public Domain. /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
ChromeUtils.defineModuleGetter(this, "PlacesTestUtils", ChromeUtils.defineModuleGetter(
"resource://testing-common/PlacesTestUtils.jsm"); this,
"PlacesTestUtils",
"resource://testing-common/PlacesTestUtils.jsm"
);
var PERMISSIONS_FILE_NAME = "permissions.sqlite"; var PERMISSIONS_FILE_NAME = "permissions.sqlite";
function GetPermissionsFile(profile) function GetPermissionsFile(profile) {
{
let file = profile.clone(); let file = profile.clone();
file.append(PERMISSIONS_FILE_NAME); file.append(PERMISSIONS_FILE_NAME);
return file; return file;
@ -32,14 +34,16 @@ add_task(async function test() {
",expireType INTEGER" + ",expireType INTEGER" +
",expireTime INTEGER" + ",expireTime INTEGER" +
",modificationTime INTEGER" + ",modificationTime INTEGER" +
")"); ")"
);
let stmt6Insert = db.createStatement( let stmt6Insert = db.createStatement(
"INSERT INTO moz_perms (" + "INSERT INTO moz_perms (" +
"id, origin, type, permission, expireType, expireTime, modificationTime" + "id, origin, type, permission, expireType, expireTime, modificationTime" +
") VALUES (" + ") VALUES (" +
":id, :origin, :type, :permission, :expireType, :expireTime, :modificationTime" + ":id, :origin, :type, :permission, :expireType, :expireTime, :modificationTime" +
")"); ")"
);
db.executeSimpleSQL( db.executeSimpleSQL(
"CREATE TABLE moz_hosts (" + "CREATE TABLE moz_hosts (" +
@ -52,18 +56,27 @@ add_task(async function test() {
",modificationTime INTEGER" + ",modificationTime INTEGER" +
",appId INTEGER" + ",appId INTEGER" +
",isInBrowserElement INTEGER" + ",isInBrowserElement INTEGER" +
")"); ")"
);
let stmtInsert = db.createStatement( let stmtInsert = db.createStatement(
"INSERT INTO moz_hosts (" + "INSERT INTO moz_hosts (" +
"id, host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement" + "id, host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement" +
") VALUES (" + ") VALUES (" +
":id, :host, :type, :permission, :expireType, :expireTime, :modificationTime, :appId, :isInBrowserElement" + ":id, :host, :type, :permission, :expireType, :expireTime, :modificationTime, :appId, :isInBrowserElement" +
")"); ")"
);
let id = 0; let id = 0;
function insertOrigin(origin, type, permission, expireType, expireTime, modificationTime) { function insertOrigin(
origin,
type,
permission,
expireType,
expireTime,
modificationTime
) {
let thisId = id++; let thisId = id++;
stmt6Insert.bindByName("id", thisId); stmt6Insert.bindByName("id", thisId);
@ -87,11 +100,20 @@ add_task(async function test() {
permission, permission,
expireType, expireType,
expireTime, expireTime,
modificationTime modificationTime,
}; };
} }
function insertHost(host, type, permission, expireType, expireTime, modificationTime, appId, isInBrowserElement) { function insertHost(
host,
type,
permission,
expireType,
expireTime,
modificationTime,
appId,
isInBrowserElement
) {
let thisId = id++; let thisId = id++;
stmtInsert.bindByName("id", thisId); stmtInsert.bindByName("id", thisId);
@ -119,7 +141,7 @@ add_task(async function test() {
expireTime, expireTime,
modificationTime, modificationTime,
appId, appId,
isInBrowserElement isInBrowserElement,
}; };
} }
@ -149,11 +171,15 @@ add_task(async function test() {
["http://foo.com^inBrowser=1", "A", 2, 0, 0, 0], ["http://foo.com^inBrowser=1", "A", 2, 0, 0, 0],
]; ];
let found = expected.map((it) => 0); let found = expected.map(it => 0);
// Add some places to the places database // Add some places to the places database
await PlacesTestUtils.addVisits(Services.io.newURI("https://foo.com/some/other/subdirectory")); await PlacesTestUtils.addVisits(
await PlacesTestUtils.addVisits(Services.io.newURI("ftp://some.subdomain.of.foo.com:8000/some/subdirectory")); Services.io.newURI("https://foo.com/some/other/subdirectory")
);
await PlacesTestUtils.addVisits(
Services.io.newURI("ftp://some.subdomain.of.foo.com:8000/some/subdirectory")
);
await PlacesTestUtils.addVisits(Services.io.newURI("ftp://127.0.0.1:8080")); await PlacesTestUtils.addVisits(Services.io.newURI("ftp://127.0.0.1:8080"));
await PlacesTestUtils.addVisits(Services.io.newURI("https://localhost:8080")); await PlacesTestUtils.addVisits(Services.io.newURI("https://localhost:8080"));
@ -165,28 +191,43 @@ add_task(async function test() {
let isExpected = false; let isExpected = false;
expected.forEach((it, i) => { expected.forEach((it, i) => {
if (permission.principal.origin == it[0] && if (
permission.type == it[1] && permission.principal.origin == it[0] &&
permission.capability == it[2] && permission.type == it[1] &&
permission.expireType == it[3] && permission.capability == it[2] &&
permission.expireTime == it[4]) { permission.expireType == it[3] &&
permission.expireTime == it[4]
) {
isExpected = true; isExpected = true;
found[i]++; found[i]++;
} }
}); });
Assert.ok(isExpected, Assert.ok(
"Permission " + (isExpected ? "should" : "shouldn't") + isExpected,
" be in permission database: " + "Permission " +
permission.principal.origin + ", " + (isExpected ? "should" : "shouldn't") +
permission.type + ", " + " be in permission database: " +
permission.capability + ", " + permission.principal.origin +
permission.expireType + ", " + ", " +
permission.expireTime); permission.type +
", " +
permission.capability +
", " +
permission.expireType +
", " +
permission.expireTime
);
} }
found.forEach((count, i) => { found.forEach((count, i) => {
Assert.ok(count == 1, "Expected count = 1, got count = " + count + " for permission " + expected[i]); Assert.ok(
count == 1,
"Expected count = 1, got count = " +
count +
" for permission " +
expected[i]
);
}); });
// Check to make sure that all of the tables which we care about are present // Check to make sure that all of the tables which we care about are present

View file

@ -12,8 +12,7 @@ function run_test() {
test_generator.next(); test_generator.next();
} }
function continue_test() function continue_test() {
{
do_run_generator(test_generator); do_run_generator(test_generator);
} }
@ -24,8 +23,9 @@ function* do_run_test() {
let pm = Services.perms; let pm = Services.perms;
let now = Number(Date.now()); let now = Number(Date.now());
let permType = "test/expiration-perm"; let permType = "test/expiration-perm";
let ssm = Cc["@mozilla.org/scriptsecuritymanager;1"] let ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(
.getService(Ci.nsIScriptSecurityManager); Ci.nsIScriptSecurityManager
);
let uri = NetUtil.newURI("http://example.com"); let uri = NetUtil.newURI("http://example.com");
let principal = ssm.createCodebasePrincipal(uri, {}); let principal = ssm.createCodebasePrincipal(uri, {});
@ -36,13 +36,25 @@ function* do_run_test() {
// do_execute_soon() so that we can use our generator to continue the test // do_execute_soon() so that we can use our generator to continue the test
// where we left off. // where we left off.
executeSoon(function() { executeSoon(function() {
pm.addFromPrincipal(principal, permType, pm.ALLOW_ACTION, pm.EXPIRE_TIME, now + 100000); pm.addFromPrincipal(
principal,
permType,
pm.ALLOW_ACTION,
pm.EXPIRE_TIME,
now + 100000
);
}); });
yield; yield;
// Alter a permission, to test the 'changed' notification. // Alter a permission, to test the 'changed' notification.
executeSoon(function() { executeSoon(function() {
pm.addFromPrincipal(principal, permType, pm.ALLOW_ACTION, pm.EXPIRE_TIME, now + 200000); pm.addFromPrincipal(
principal,
permType,
pm.ALLOW_ACTION,
pm.EXPIRE_TIME,
now + 200000
);
}); });
yield; yield;
@ -99,7 +111,6 @@ permission_observer.prototype = {
default: default:
do_throw("too many add notifications posted."); do_throw("too many add notifications posted.");
} }
} else if (data == "changed") { } else if (data == "changed") {
let perm = subject.QueryInterface(Ci.nsIPermission); let perm = subject.QueryInterface(Ci.nsIPermission);
this.changes++; this.changes++;
@ -112,7 +123,6 @@ permission_observer.prototype = {
default: default:
do_throw("too many change notifications posted."); do_throw("too many change notifications posted.");
} }
} else if (data == "deleted") { } else if (data == "deleted") {
let perm = subject.QueryInterface(Ci.nsIPermission); let perm = subject.QueryInterface(Ci.nsIPermission);
this.deletes++; this.deletes++;
@ -123,13 +133,11 @@ permission_observer.prototype = {
default: default:
do_throw("too many delete notifications posted."); do_throw("too many delete notifications posted.");
} }
} else if (data == "cleared") { } else if (data == "cleared") {
// only clear once: at the end // only clear once: at the end
Assert.ok(!this.cleared); Assert.ok(!this.cleared);
Assert.equal(do_count_enumerator(Services.perms.enumerator), 0); Assert.equal(do_count_enumerator(Services.perms.enumerator), 0);
this.cleared = true; this.cleared = true;
} else { } else {
do_throw("unexpected data '" + data + "'!"); do_throw("unexpected data '" + data + "'!");
} }

View file

@ -6,8 +6,9 @@ function run_test() {
var dir = do_get_profile(); var dir = do_get_profile();
// initialize the permission manager service // initialize the permission manager service
var pm = Cc["@mozilla.org/permissionmanager;1"]. var pm = Cc["@mozilla.org/permissionmanager;1"].getService(
getService(Ci.nsIPermissionManager); Ci.nsIPermissionManager
);
// get the db file // get the db file
var file = dir.clone(); var file = dir.clone();
@ -15,14 +16,17 @@ function run_test() {
Assert.ok(file.exists()); Assert.ok(file.exists());
// corrupt the file // corrupt the file
var ostream = Cc["@mozilla.org/network/file-output-stream;1"]. var ostream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(
createInstance(Ci.nsIFileOutputStream); Ci.nsIFileOutputStream
);
ostream.init(file, 0x02, 0o666, 0); ostream.init(file, 0x02, 0o666, 0);
var conv = Cc["@mozilla.org/intl/converter-output-stream;1"]. var conv = Cc["@mozilla.org/intl/converter-output-stream;1"].createInstance(
createInstance(Ci.nsIConverterOutputStream); Ci.nsIConverterOutputStream
);
conv.init(ostream, "UTF-8"); conv.init(ostream, "UTF-8");
for (var i = 0; i < file.fileSize; ++i) for (var i = 0; i < file.fileSize; ++i) {
conv.writeString("a"); conv.writeString("a");
}
conv.close(); conv.close();
// prepare an empty hostperm.1 file so that it can be used for importing // prepare an empty hostperm.1 file so that it can be used for importing

View file

@ -5,8 +5,9 @@ function run_test() {
Services.prefs.setCharPref("permissions.manager.defaultsUrl", ""); Services.prefs.setCharPref("permissions.manager.defaultsUrl", "");
// initialize the permission manager service // initialize the permission manager service
let pm = Cc["@mozilla.org/permissionmanager;1"]. let pm = Cc["@mozilla.org/permissionmanager;1"].getService(
getService(Ci.nsIPermissionManager); Ci.nsIPermissionManager
);
Assert.equal(perm_count(), 0); Assert.equal(perm_count(), 0);

View file

@ -5,7 +5,9 @@ add_task(async function test() {
Services.prefs.setCharPref("permissions.manager.defaultsUrl", ""); Services.prefs.setCharPref("permissions.manager.defaultsUrl", "");
// initialize the permission manager service // initialize the permission manager service
let pm = Cc["@mozilla.org/permissionmanager;1"].getService(Ci.nsIPermissionManager); let pm = Cc["@mozilla.org/permissionmanager;1"].getService(
Ci.nsIPermissionManager
);
Assert.equal(perm_count(), 0); Assert.equal(perm_count(), 0);
@ -48,7 +50,7 @@ add_task(async function test() {
Assert.equal(pm.testPermission(uri, "apple"), 3); Assert.equal(pm.testPermission(uri, "apple"), 3);
Assert.equal(pm.testPermission(uri2, "apple"), 0); Assert.equal(pm.testPermission(uri2, "apple"), 0);
Assert.equal(pm.testPermission(uri3, "apple"), 0); Assert.equal(pm.testPermission(uri3, "apple"), 0);
Assert.equal(pm.testPermission(uri, "cucumber"), 1); Assert.equal(pm.testPermission(uri, "cucumber"), 1);
Assert.equal(pm.testPermission(uri3, "cucumber"), 3); Assert.equal(pm.testPermission(uri3, "cucumber"), 3);
@ -57,24 +59,24 @@ add_task(async function test() {
Assert.equal(pm.testPermission(uri, "pear"), 1); Assert.equal(pm.testPermission(uri, "pear"), 1);
Assert.equal(pm.testPermission(uri2, "pear"), 2); Assert.equal(pm.testPermission(uri2, "pear"), 2);
Assert.equal(pm.testPermission(uri, "apple"), 3); Assert.equal(pm.testPermission(uri, "apple"), 3);
Assert.equal(pm.testPermission(uri2, "apple"), 0); Assert.equal(pm.testPermission(uri2, "apple"), 0);
Assert.equal(pm.testPermission(uri3, "apple"), 0); Assert.equal(pm.testPermission(uri3, "apple"), 0);
Assert.equal(pm.testPermission(uri, "cucumber"), 1); Assert.equal(pm.testPermission(uri, "cucumber"), 1);
Assert.equal(pm.testPermission(uri3, "cucumber"), 0); Assert.equal(pm.testPermission(uri3, "cucumber"), 0);
pm.removeByTypeSince("pear", since); pm.removeByTypeSince("pear", since);
Assert.equal(perm_count(), 3); Assert.equal(perm_count(), 3);
Assert.equal(pm.testPermission(uri, "pear"), 1); Assert.equal(pm.testPermission(uri, "pear"), 1);
Assert.equal(pm.testPermission(uri2, "pear"), 0); Assert.equal(pm.testPermission(uri2, "pear"), 0);
Assert.equal(pm.testPermission(uri, "apple"), 3); Assert.equal(pm.testPermission(uri, "apple"), 3);
Assert.equal(pm.testPermission(uri2, "apple"), 0); Assert.equal(pm.testPermission(uri2, "apple"), 0);
Assert.equal(pm.testPermission(uri3, "apple"), 0); Assert.equal(pm.testPermission(uri3, "apple"), 0);
Assert.equal(pm.testPermission(uri, "cucumber"), 1); Assert.equal(pm.testPermission(uri, "cucumber"), 1);
Assert.equal(pm.testPermission(uri3, "cucumber"), 0); Assert.equal(pm.testPermission(uri3, "cucumber"), 0);

View file

@ -3,8 +3,9 @@
function run_test() { function run_test() {
// initialize the permission manager service // initialize the permission manager service
let pm = Cc["@mozilla.org/permissionmanager;1"]. let pm = Cc["@mozilla.org/permissionmanager;1"].getService(
getService(Ci.nsIPermissionManager); Ci.nsIPermissionManager
);
Assert.equal(perm_count(), 0); Assert.equal(perm_count(), 0);
@ -42,7 +43,6 @@ function run_test() {
remove_one_by_type("pear"); remove_one_by_type("pear");
Assert.equal(perm_count(), 0); Assert.equal(perm_count(), 0);
function perm_count() { function perm_count() {
let enumerator = pm.enumerator; let enumerator = pm.enumerator;
let count = 0; let count = 0;

View file

@ -10,8 +10,7 @@ function run_test() {
test_generator.next(); test_generator.next();
} }
function continue_test() function continue_test() {
{
do_run_generator(test_generator); do_run_generator(test_generator);
} }
@ -24,10 +23,16 @@ function* do_run_test() {
// to help with testing edge-cases, we will arrange for .removeAllSince to // to help with testing edge-cases, we will arrange for .removeAllSince to
// remove *all* permissions from one principal and one permission from another. // remove *all* permissions from one principal and one permission from another.
let permURI1 = NetUtil.newURI("http://example.com"); let permURI1 = NetUtil.newURI("http://example.com");
let principal1 = Services.scriptSecurityManager.createCodebasePrincipal(permURI1, {}); let principal1 = Services.scriptSecurityManager.createCodebasePrincipal(
permURI1,
{}
);
let permURI2 = NetUtil.newURI("http://example.org"); let permURI2 = NetUtil.newURI("http://example.org");
let principal2 = Services.scriptSecurityManager.createCodebasePrincipal(permURI2, {}); let principal2 = Services.scriptSecurityManager.createCodebasePrincipal(
permURI2,
{}
);
// add a permission now - this isn't going to be removed. // add a permission now - this isn't going to be removed.
pm.addFromPrincipal(principal1, "test/remove-since", 1); pm.addFromPrincipal(principal1, "test/remove-since", 1);
@ -57,13 +62,25 @@ function* do_run_test() {
pm.removeAllSince(since); pm.removeAllSince(since);
// principal1 - the first one should remain. // principal1 - the first one should remain.
Assert.equal(1, pm.testPermissionFromPrincipal(principal1, "test/remove-since")); Assert.equal(
1,
pm.testPermissionFromPrincipal(principal1, "test/remove-since")
);
// but the second should have been removed. // but the second should have been removed.
Assert.equal(0, pm.testPermissionFromPrincipal(principal1, "test/remove-since-2")); Assert.equal(
0,
pm.testPermissionFromPrincipal(principal1, "test/remove-since-2")
);
// principal2 - both should have been removed. // principal2 - both should have been removed.
Assert.equal(0, pm.testPermissionFromPrincipal(principal2, "test/remove-since")); Assert.equal(
Assert.equal(0, pm.testPermissionFromPrincipal(principal2, "test/remove-since-2")); 0,
pm.testPermissionFromPrincipal(principal2, "test/remove-since")
);
Assert.equal(
0,
pm.testPermissionFromPrincipal(principal2, "test/remove-since-2")
);
do_finish_generator_test(test_generator); do_finish_generator_test(test_generator);
} }

View file

@ -2,73 +2,228 @@
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
function getPrincipalFromURI(aURI) { function getPrincipalFromURI(aURI) {
let ssm = Cc["@mozilla.org/scriptsecuritymanager;1"] let ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(
.getService(Ci.nsIScriptSecurityManager); Ci.nsIScriptSecurityManager
);
let uri = NetUtil.newURI(aURI); let uri = NetUtil.newURI(aURI);
return ssm.createCodebasePrincipal(uri, {}); return ssm.createCodebasePrincipal(uri, {});
} }
function run_test() { function run_test() {
var pm = Cc["@mozilla.org/permissionmanager;1"]. var pm = Cc["@mozilla.org/permissionmanager;1"].getService(
getService(Ci.nsIPermissionManager); Ci.nsIPermissionManager
);
// Adds a permission to a sub-domain. Checks if it is working. // Adds a permission to a sub-domain. Checks if it is working.
let sub1Principal = getPrincipalFromURI("http://sub1.example.com"); let sub1Principal = getPrincipalFromURI("http://sub1.example.com");
pm.addFromPrincipal(sub1Principal, "test/subdomains", pm.ALLOW_ACTION, 0, 0); pm.addFromPrincipal(sub1Principal, "test/subdomains", pm.ALLOW_ACTION, 0, 0);
Assert.equal(pm.testPermissionFromPrincipal(sub1Principal, "test/subdomains"), pm.ALLOW_ACTION); Assert.equal(
Assert.equal(pm.testPermissionOriginNoSuffix(sub1Principal.originNoSuffix, "test/subdomains"), pm.ALLOW_ACTION); pm.testPermissionFromPrincipal(sub1Principal, "test/subdomains"),
pm.ALLOW_ACTION
);
Assert.equal(
pm.testPermissionOriginNoSuffix(
sub1Principal.originNoSuffix,
"test/subdomains"
),
pm.ALLOW_ACTION
);
// A sub-sub-domain should get the permission. // A sub-sub-domain should get the permission.
let subsubPrincipal = getPrincipalFromURI("http://sub.sub1.example.com"); let subsubPrincipal = getPrincipalFromURI("http://sub.sub1.example.com");
Assert.equal(pm.testPermissionFromPrincipal(subsubPrincipal, "test/subdomains"), pm.ALLOW_ACTION); Assert.equal(
Assert.equal(pm.testPermissionOriginNoSuffix(subsubPrincipal.originNoSuffix, "test/subdomains"), pm.ALLOW_ACTION); pm.testPermissionFromPrincipal(subsubPrincipal, "test/subdomains"),
pm.ALLOW_ACTION
);
Assert.equal(
pm.testPermissionOriginNoSuffix(
subsubPrincipal.originNoSuffix,
"test/subdomains"
),
pm.ALLOW_ACTION
);
// Another sub-domain shouldn't get the permission. // Another sub-domain shouldn't get the permission.
let sub2Principal = getPrincipalFromURI("http://sub2.example.com"); let sub2Principal = getPrincipalFromURI("http://sub2.example.com");
Assert.equal(pm.testPermissionFromPrincipal(sub2Principal, "test/subdomains"), pm.UNKNOWN_ACTION); Assert.equal(
Assert.equal(pm.testPermissionOriginNoSuffix(sub2Principal.originNoSuffix, "test/subdomains"), pm.UNKNOWN_ACTION); pm.testPermissionFromPrincipal(sub2Principal, "test/subdomains"),
pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionOriginNoSuffix(
sub2Principal.originNoSuffix,
"test/subdomains"
),
pm.UNKNOWN_ACTION
);
// Remove current permissions. // Remove current permissions.
pm.removeFromPrincipal(sub1Principal, "test/subdomains"); pm.removeFromPrincipal(sub1Principal, "test/subdomains");
Assert.equal(pm.testPermissionFromPrincipal(sub1Principal, "test/subdomains"), pm.UNKNOWN_ACTION); Assert.equal(
Assert.equal(pm.testPermissionOriginNoSuffix(sub1Principal.originNoSuffix, "test/subdomains"), pm.UNKNOWN_ACTION); pm.testPermissionFromPrincipal(sub1Principal, "test/subdomains"),
pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionOriginNoSuffix(
sub1Principal.originNoSuffix,
"test/subdomains"
),
pm.UNKNOWN_ACTION
);
// Adding the permission to the main domain. Checks if it is working. // Adding the permission to the main domain. Checks if it is working.
let mainPrincipal = getPrincipalFromURI("http://example.com"); let mainPrincipal = getPrincipalFromURI("http://example.com");
pm.addFromPrincipal(mainPrincipal, "test/subdomains", pm.ALLOW_ACTION, 0, 0); pm.addFromPrincipal(mainPrincipal, "test/subdomains", pm.ALLOW_ACTION, 0, 0);
Assert.equal(pm.testPermissionFromPrincipal(mainPrincipal, "test/subdomains"), pm.ALLOW_ACTION); Assert.equal(
Assert.equal(pm.testPermissionOriginNoSuffix(mainPrincipal.originNoSuffix, "test/subdomains"), pm.ALLOW_ACTION); pm.testPermissionFromPrincipal(mainPrincipal, "test/subdomains"),
pm.ALLOW_ACTION
);
Assert.equal(
pm.testPermissionOriginNoSuffix(
mainPrincipal.originNoSuffix,
"test/subdomains"
),
pm.ALLOW_ACTION
);
// All sub-domains should have the permission now. // All sub-domains should have the permission now.
Assert.equal(pm.testPermissionFromPrincipal(sub1Principal, "test/subdomains"), pm.ALLOW_ACTION); Assert.equal(
Assert.equal(pm.testPermissionOriginNoSuffix(sub1Principal.originNoSuffix, "test/subdomains"), pm.ALLOW_ACTION); pm.testPermissionFromPrincipal(sub1Principal, "test/subdomains"),
Assert.equal(pm.testPermissionFromPrincipal(sub2Principal, "test/subdomains"), pm.ALLOW_ACTION); pm.ALLOW_ACTION
Assert.equal(pm.testPermissionOriginNoSuffix(sub2Principal.originNoSuffix, "test/subdomains"), pm.ALLOW_ACTION); );
Assert.equal(pm.testPermissionFromPrincipal(subsubPrincipal, "test/subdomains"), pm.ALLOW_ACTION); Assert.equal(
Assert.equal(pm.testPermissionOriginNoSuffix(subsubPrincipal.originNoSuffix, "test/subdomains"), pm.ALLOW_ACTION); pm.testPermissionOriginNoSuffix(
sub1Principal.originNoSuffix,
"test/subdomains"
),
pm.ALLOW_ACTION
);
Assert.equal(
pm.testPermissionFromPrincipal(sub2Principal, "test/subdomains"),
pm.ALLOW_ACTION
);
Assert.equal(
pm.testPermissionOriginNoSuffix(
sub2Principal.originNoSuffix,
"test/subdomains"
),
pm.ALLOW_ACTION
);
Assert.equal(
pm.testPermissionFromPrincipal(subsubPrincipal, "test/subdomains"),
pm.ALLOW_ACTION
);
Assert.equal(
pm.testPermissionOriginNoSuffix(
subsubPrincipal.originNoSuffix,
"test/subdomains"
),
pm.ALLOW_ACTION
);
// Remove current permissions. // Remove current permissions.
pm.removeFromPrincipal(mainPrincipal, "test/subdomains"); pm.removeFromPrincipal(mainPrincipal, "test/subdomains");
Assert.equal(pm.testPermissionFromPrincipal(mainPrincipal, "test/subdomains"), pm.UNKNOWN_ACTION); Assert.equal(
Assert.equal(pm.testPermissionOriginNoSuffix(mainPrincipal.originNoSuffix, "test/subdomains"), pm.UNKNOWN_ACTION); pm.testPermissionFromPrincipal(mainPrincipal, "test/subdomains"),
Assert.equal(pm.testPermissionFromPrincipal(sub1Principal, "test/subdomains"), pm.UNKNOWN_ACTION); pm.UNKNOWN_ACTION
Assert.equal(pm.testPermissionOriginNoSuffix(sub1Principal.originNoSuffix, "test/subdomains"), pm.UNKNOWN_ACTION); );
Assert.equal(pm.testPermissionFromPrincipal(sub2Principal, "test/subdomains"), pm.UNKNOWN_ACTION); Assert.equal(
Assert.equal(pm.testPermissionOriginNoSuffix(sub2Principal.originNoSuffix, "test/subdomains"), pm.UNKNOWN_ACTION); pm.testPermissionOriginNoSuffix(
Assert.equal(pm.testPermissionFromPrincipal(subsubPrincipal, "test/subdomains"), pm.UNKNOWN_ACTION); mainPrincipal.originNoSuffix,
Assert.equal(pm.testPermissionOriginNoSuffix(subsubPrincipal.originNoSuffix, "test/subdomains"), pm.UNKNOWN_ACTION); "test/subdomains"
),
pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionFromPrincipal(sub1Principal, "test/subdomains"),
pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionOriginNoSuffix(
sub1Principal.originNoSuffix,
"test/subdomains"
),
pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionFromPrincipal(sub2Principal, "test/subdomains"),
pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionOriginNoSuffix(
sub2Principal.originNoSuffix,
"test/subdomains"
),
pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionFromPrincipal(subsubPrincipal, "test/subdomains"),
pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionOriginNoSuffix(
subsubPrincipal.originNoSuffix,
"test/subdomains"
),
pm.UNKNOWN_ACTION
);
// A sanity check that the previous implementation wasn't passing... // A sanity check that the previous implementation wasn't passing...
let crazyPrincipal = getPrincipalFromURI("http://com"); let crazyPrincipal = getPrincipalFromURI("http://com");
pm.addFromPrincipal(crazyPrincipal, "test/subdomains", pm.ALLOW_ACTION, 0, 0); pm.addFromPrincipal(crazyPrincipal, "test/subdomains", pm.ALLOW_ACTION, 0, 0);
Assert.equal(pm.testPermissionFromPrincipal(crazyPrincipal, "test/subdomains"), pm.ALLOW_ACTION); Assert.equal(
Assert.equal(pm.testPermissionOriginNoSuffix(crazyPrincipal.originNoSuffix, "test/subdomains"), pm.ALLOW_ACTION); pm.testPermissionFromPrincipal(crazyPrincipal, "test/subdomains"),
Assert.equal(pm.testPermissionFromPrincipal(mainPrincipal, "test/subdomains"), pm.UNKNOWN_ACTION); pm.ALLOW_ACTION
Assert.equal(pm.testPermissionOriginNoSuffix(mainPrincipal.originNoSuffix, "test/subdomains"), pm.UNKNOWN_ACTION); );
Assert.equal(pm.testPermissionFromPrincipal(sub1Principal, "test/subdomains"), pm.UNKNOWN_ACTION); Assert.equal(
Assert.equal(pm.testPermissionOriginNoSuffix(sub1Principal.originNoSuffix, "test/subdomains"), pm.UNKNOWN_ACTION); pm.testPermissionOriginNoSuffix(
Assert.equal(pm.testPermissionFromPrincipal(sub2Principal, "test/subdomains"), pm.UNKNOWN_ACTION); crazyPrincipal.originNoSuffix,
Assert.equal(pm.testPermissionOriginNoSuffix(sub2Principal.originNoSuffix, "test/subdomains"), pm.UNKNOWN_ACTION); "test/subdomains"
Assert.equal(pm.testPermissionFromPrincipal(subsubPrincipal, "test/subdomains"), pm.UNKNOWN_ACTION); ),
Assert.equal(pm.testPermissionOriginNoSuffix(subsubPrincipal.originNoSuffix, "test/subdomains"), pm.UNKNOWN_ACTION); pm.ALLOW_ACTION
);
Assert.equal(
pm.testPermissionFromPrincipal(mainPrincipal, "test/subdomains"),
pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionOriginNoSuffix(
mainPrincipal.originNoSuffix,
"test/subdomains"
),
pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionFromPrincipal(sub1Principal, "test/subdomains"),
pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionOriginNoSuffix(
sub1Principal.originNoSuffix,
"test/subdomains"
),
pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionFromPrincipal(sub2Principal, "test/subdomains"),
pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionOriginNoSuffix(
sub2Principal.originNoSuffix,
"test/subdomains"
),
pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionFromPrincipal(subsubPrincipal, "test/subdomains"),
pm.UNKNOWN_ACTION
);
Assert.equal(
pm.testPermissionOriginNoSuffix(
subsubPrincipal.originNoSuffix,
"test/subdomains"
),
pm.UNKNOWN_ACTION
);
} }

View file

@ -20,201 +20,215 @@ var gVersion;
var gIsUTF8; var gIsUTF8;
function getPrefBranch() { function getPrefBranch() {
var prefService = Cc[PrefServiceContractID] var prefService = Cc[PrefServiceContractID].getService(nsIPrefService);
.getService(nsIPrefService); return prefService.getBranch(null);
return prefService.getBranch(null);
} }
function pref(prefName, value) { function pref(prefName, value) {
try { try {
var prefBranch = getPrefBranch(); var prefBranch = getPrefBranch();
if (typeof value == "string") { if (typeof value == "string") {
if (gIsUTF8) { if (gIsUTF8) {
prefBranch.setStringPref(prefName, value); prefBranch.setStringPref(prefName, value);
return; return;
} }
prefBranch.setCharPref(prefName, value); prefBranch.setCharPref(prefName, value);
} else if (typeof value == "number") { } else if (typeof value == "number") {
prefBranch.setIntPref(prefName, value); prefBranch.setIntPref(prefName, value);
} else if (typeof value == "boolean") { } else if (typeof value == "boolean") {
prefBranch.setBoolPref(prefName, value); prefBranch.setBoolPref(prefName, value);
}
} catch (e) {
displayError("pref", e);
} }
} catch (e) {
displayError("pref", e);
}
} }
function defaultPref(prefName, value) { function defaultPref(prefName, value) {
try { try {
var prefService = Cc[PrefServiceContractID] var prefService = Cc[PrefServiceContractID].getService(nsIPrefService);
.getService(nsIPrefService); var prefBranch = prefService.getDefaultBranch(null);
var prefBranch = prefService.getDefaultBranch(null); if (typeof value == "string") {
if (typeof value == "string") { if (gIsUTF8) {
if (gIsUTF8) { prefBranch.setStringPref(prefName, value);
prefBranch.setStringPref(prefName, value); return;
return; }
} prefBranch.setCharPref(prefName, value);
prefBranch.setCharPref(prefName, value); } else if (typeof value == "number") {
} else if (typeof value == "number") { prefBranch.setIntPref(prefName, value);
prefBranch.setIntPref(prefName, value); } else if (typeof value == "boolean") {
} else if (typeof value == "boolean") { prefBranch.setBoolPref(prefName, value);
prefBranch.setBoolPref(prefName, value);
}
} catch (e) {
displayError("defaultPref", e);
} }
} catch (e) {
displayError("defaultPref", e);
}
} }
function lockPref(prefName, value) { function lockPref(prefName, value) {
try { try {
var prefBranch = getPrefBranch(); var prefBranch = getPrefBranch();
if (prefBranch.prefIsLocked(prefName)) if (prefBranch.prefIsLocked(prefName)) {
prefBranch.unlockPref(prefName); prefBranch.unlockPref(prefName);
defaultPref(prefName, value);
prefBranch.lockPref(prefName);
} catch (e) {
displayError("lockPref", e);
} }
defaultPref(prefName, value);
prefBranch.lockPref(prefName);
} catch (e) {
displayError("lockPref", e);
}
} }
function unlockPref(prefName) { function unlockPref(prefName) {
try { try {
var prefBranch = getPrefBranch(); var prefBranch = getPrefBranch();
prefBranch.unlockPref(prefName); prefBranch.unlockPref(prefName);
} catch (e) { } catch (e) {
displayError("unlockPref", e); displayError("unlockPref", e);
} }
} }
function getPref(prefName) { function getPref(prefName) {
try { try {
var prefBranch = getPrefBranch(); var prefBranch = getPrefBranch();
switch (prefBranch.getPrefType(prefName)) { switch (prefBranch.getPrefType(prefName)) {
case prefBranch.PREF_STRING: case prefBranch.PREF_STRING:
if (gIsUTF8) { if (gIsUTF8) {
return prefBranch.getStringPref(prefName); return prefBranch.getStringPref(prefName);
}
return prefBranch.getCharPref(prefName);
case prefBranch.PREF_INT:
return prefBranch.getIntPref(prefName);
case prefBranch.PREF_BOOL:
return prefBranch.getBoolPref(prefName);
default:
return null;
} }
} catch (e) { return prefBranch.getCharPref(prefName);
displayError("getPref", e);
case prefBranch.PREF_INT:
return prefBranch.getIntPref(prefName);
case prefBranch.PREF_BOOL:
return prefBranch.getBoolPref(prefName);
default:
return null;
} }
return undefined; } catch (e) {
displayError("getPref", e);
}
return undefined;
} }
function clearPref(prefName) { function clearPref(prefName) {
try { try {
var prefBranch = getPrefBranch(); var prefBranch = getPrefBranch();
prefBranch.clearUserPref(prefName); prefBranch.clearUserPref(prefName);
} catch (e) { } catch (e) {}
}
} }
function setLDAPVersion(version) { function setLDAPVersion(version) {
gVersion = version; gVersion = version;
} }
function getLDAPAttributes(host, base, filter, attribs, isSecure) { function getLDAPAttributes(host, base, filter, attribs, isSecure) {
try { try {
var urlSpec = "ldap" + (isSecure ? "s" : "") + "://" + host + (isSecure ? ":636" : "") + "/" + base + "?" + attribs + "?sub?" + var urlSpec =
filter; "ldap" +
(isSecure ? "s" : "") +
"://" +
host +
(isSecure ? ":636" : "") +
"/" +
base +
"?" +
attribs +
"?sub?" +
filter;
var url = Cc["@mozilla.org/network/io-service;1"] var url = Cc["@mozilla.org/network/io-service;1"]
.getService(Ci.nsIIOService) .getService(Ci.nsIIOService)
.newURI(urlSpec) .newURI(urlSpec)
.QueryInterface(Ci.nsILDAPURL); .QueryInterface(Ci.nsILDAPURL);
var ldapquery = Cc[LDAPSyncQueryContractID] var ldapquery = Cc[LDAPSyncQueryContractID].createInstance(
.createInstance(nsILDAPSyncQuery); nsILDAPSyncQuery
// default to LDAP v3 );
if (!gVersion) // default to LDAP v3
gVersion = Ci.nsILDAPConnection.VERSION3; if (!gVersion) {
// user supplied method gVersion = Ci.nsILDAPConnection.VERSION3;
processLDAPValues(ldapquery.getQueryResults(url, gVersion));
} catch (e) {
displayError("getLDAPAttibutes", e);
} }
// user supplied method
processLDAPValues(ldapquery.getQueryResults(url, gVersion));
} catch (e) {
displayError("getLDAPAttibutes", e);
}
} }
function getLDAPValue(str, key) { function getLDAPValue(str, key) {
try { try {
if (str == null || key == null) if (str == null || key == null) {
return null; return null;
var search_key = "\n" + key + "=";
var start_pos = str.indexOf(search_key);
if (start_pos == -1)
return null;
start_pos += search_key.length;
var end_pos = str.indexOf("\n", start_pos);
if (end_pos == -1)
end_pos = str.length;
return str.substring(start_pos, end_pos);
} catch (e) {
displayError("getLDAPValue", e);
} }
return undefined;
var search_key = "\n" + key + "=";
var start_pos = str.indexOf(search_key);
if (start_pos == -1) {
return null;
}
start_pos += search_key.length;
var end_pos = str.indexOf("\n", start_pos);
if (end_pos == -1) {
end_pos = str.length;
}
return str.substring(start_pos, end_pos);
} catch (e) {
displayError("getLDAPValue", e);
}
return undefined;
} }
function displayError(funcname, message) { function displayError(funcname, message) {
try { try {
var promptService = Cc["@mozilla.org/embedcomp/prompt-service;1"] var promptService = Cc[
.getService(Ci.nsIPromptService); "@mozilla.org/embedcomp/prompt-service;1"
var bundle = Cc["@mozilla.org/intl/stringbundle;1"] ].getService(Ci.nsIPromptService);
.getService(Ci.nsIStringBundleService) var bundle = Cc["@mozilla.org/intl/stringbundle;1"]
.createBundle("chrome://autoconfig/locale/autoconfig.properties"); .getService(Ci.nsIStringBundleService)
.createBundle("chrome://autoconfig/locale/autoconfig.properties");
var title = bundle.GetStringFromName("autoConfigTitle"); var title = bundle.GetStringFromName("autoConfigTitle");
var msg = bundle.formatStringFromName("autoConfigMsg", [funcname]); var msg = bundle.formatStringFromName("autoConfigMsg", [funcname]);
promptService.alert(null, title, msg + " " + message); promptService.alert(null, title, msg + " " + message);
} catch (e) { } } catch (e) {}
} }
function getenv(name) { function getenv(name) {
try { try {
var environment = Cc["@mozilla.org/process/environment;1"]. var environment = Cc["@mozilla.org/process/environment;1"].getService(
getService(Ci.nsIEnvironment); Ci.nsIEnvironment
return environment.get(name); );
} catch (e) { return environment.get(name);
displayError("getEnvironment", e); } catch (e) {
} displayError("getEnvironment", e);
return undefined; }
return undefined;
} }
var APIs = { var APIs = {
pref, pref,
defaultPref, defaultPref,
lockPref, lockPref,
unlockPref, unlockPref,
getPref, getPref,
clearPref, clearPref,
setLDAPVersion, setLDAPVersion,
getLDAPAttributes, getLDAPAttributes,
getLDAPValue, getLDAPValue,
displayError, displayError,
getenv, getenv,
}; };
for (let [defineAs, func] of Object.entries(APIs)) { for (let [defineAs, func] of Object.entries(APIs)) {
Cu.exportFunction(func, gSandbox, {defineAs}); Cu.exportFunction(func, gSandbox, { defineAs });
} }
Object.defineProperty(Cu.waiveXrays(gSandbox), "gIsUTF8", { Object.defineProperty(Cu.waiveXrays(gSandbox), "gIsUTF8", {

View file

@ -5,11 +5,12 @@
/* Turning off this rule to allow control flow operations in finally block /* Turning off this rule to allow control flow operations in finally block
* http://eslint.org/docs/rules/no-unsafe-finally */ * http://eslint.org/docs/rules/no-unsafe-finally */
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
function run_test() { function run_test() {
let env = Cc["@mozilla.org/process/environment;1"] let env = Cc["@mozilla.org/process/environment;1"].getService(
.getService(Ci.nsIEnvironment); Ci.nsIEnvironment
);
let prefs = Services.prefs.getBranch(null); let prefs = Services.prefs.getBranch(null);
let defPrefs = Services.prefs.getDefaultBranch(null); let defPrefs = Services.prefs.getDefaultBranch(null);
@ -32,12 +33,18 @@ function run_test() {
env.set("AUTOCONFIG_TEST_GETENV", "getenv"); env.set("AUTOCONFIG_TEST_GETENV", "getenv");
Services.obs.notifyObservers(Services.prefs, "prefservice:before-read-userprefs"); Services.obs.notifyObservers(
Services.prefs,
"prefservice:before-read-userprefs"
);
ok(prefs.prefHasUserValue("_autoconfig_.test.userpref")); ok(prefs.prefHasUserValue("_autoconfig_.test.userpref"));
equal("userpref", prefs.getStringPref("_autoconfig_.test.userpref")); equal("userpref", prefs.getStringPref("_autoconfig_.test.userpref"));
equal("defaultpref", defPrefs.getStringPref("_autoconfig_.test.defaultpref")); equal(
"defaultpref",
defPrefs.getStringPref("_autoconfig_.test.defaultpref")
);
equal("defaultpref", prefs.getStringPref("_autoconfig_.test.defaultpref")); equal("defaultpref", prefs.getStringPref("_autoconfig_.test.defaultpref"));
ok(prefs.prefIsLocked("_autoconfig_.test.lockpref")); ok(prefs.prefIsLocked("_autoconfig_.test.lockpref"));

View file

@ -5,7 +5,7 @@
/* Turning off this rule to allow control flow operations in finally block /* Turning off this rule to allow control flow operations in finally block
* http://eslint.org/docs/rules/no-unsafe-finally */ * http://eslint.org/docs/rules/no-unsafe-finally */
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
function run_test() { function run_test() {
let greD = Services.dirsvc.get("GreD", Ci.nsIFile); let greD = Services.dirsvc.get("GreD", Ci.nsIFile);
@ -21,50 +21,65 @@ function run_test() {
Cc["@mozilla.org/readconfig;1"].getService(Ci.nsISupports); Cc["@mozilla.org/readconfig;1"].getService(Ci.nsISupports);
Services.prefs.resetPrefs(); Services.prefs.resetPrefs();
var tests = [{ var tests = [
filename: "autoconfig-utf8.cfg", {
prefs: { filename: "autoconfig-utf8.cfg",
"_test.string.ASCII": "UTF-8", prefs: {
"_test.string.non-ASCII": "日本語", "_test.string.ASCII": "UTF-8",
"_test.string.getPref": "日本語", "_test.string.non-ASCII": "日本語",
"_test.string.gIsUTF8": "true", "_test.string.getPref": "日本語",
"_test.string.gIsUTF8": "true",
},
}, },
}, { {
filename: "autoconfig-latin1.cfg", filename: "autoconfig-latin1.cfg",
prefs: { prefs: {
"_test.string.ASCII": "ASCII", "_test.string.ASCII": "ASCII",
"_test.string.non-ASCII": "日本語", "_test.string.non-ASCII": "日本語",
"_test.string.getPref": "日本語", "_test.string.getPref": "日本語",
"_test.string.gIsUTF8": "false", "_test.string.gIsUTF8": "false",
},
}, },
}, { {
filename: "autoconfig-chromecheck.cfg", filename: "autoconfig-chromecheck.cfg",
prefs: { prefs: {
"_test.string.typeofComponents": "undefined", "_test.string.typeofComponents": "undefined",
},
}, },
}]; ];
function testAutoConfig(test) { function testAutoConfig(test) {
// Make sure pref values are unset. // Make sure pref values are unset.
for (let prefName in test.prefs) { for (let prefName in test.prefs) {
Assert.equal(Ci.nsIPrefBranch.PREF_INVALID, Services.prefs.getPrefType(prefName)); Assert.equal(
Ci.nsIPrefBranch.PREF_INVALID,
Services.prefs.getPrefType(prefName)
);
} }
let autoConfigCfg = testDir.clone(); let autoConfigCfg = testDir.clone();
autoConfigCfg.append(test.filename); autoConfigCfg.append(test.filename);
autoConfigCfg.copyTo(greD, "autoconfig.cfg"); autoConfigCfg.copyTo(greD, "autoconfig.cfg");
Services.obs.notifyObservers(Services.prefs, "prefservice:before-read-userprefs"); Services.obs.notifyObservers(
Services.prefs,
"prefservice:before-read-userprefs"
);
for (let prefName in test.prefs) { for (let prefName in test.prefs) {
Assert.equal(test.prefs[prefName], Assert.equal(
Services.prefs.getStringPref(prefName)); test.prefs[prefName],
Services.prefs.getStringPref(prefName)
);
} }
Services.prefs.resetPrefs(); Services.prefs.resetPrefs();
// Make sure pref values are reset. // Make sure pref values are reset.
for (let prefName in test.prefs) { for (let prefName in test.prefs) {
Assert.equal(Ci.nsIPrefBranch.PREF_INVALID, Services.prefs.getPrefType(prefName)); Assert.equal(
Ci.nsIPrefBranch.PREF_INVALID,
Services.prefs.getPrefType(prefName)
);
} }
} }

View file

@ -3,134 +3,165 @@
*/ */
const tests = [ const tests = [
["affixes", "iso-8859-1"], ["affixes", "iso-8859-1"],
["condition", "iso-8859-1"], ["condition", "iso-8859-1"],
["condition-utf", "UTF-8"], ["condition-utf", "UTF-8"],
["base", "iso-8859-1"], ["base", "iso-8859-1"],
["base-utf", "UTF-8"], ["base-utf", "UTF-8"],
["allcaps", "iso-8859-1"], ["allcaps", "iso-8859-1"],
["allcaps-utf", "UTF-8"], ["allcaps-utf", "UTF-8"],
["allcaps2", "iso-8859-1"], ["allcaps2", "iso-8859-1"],
["allcaps3", "iso-8859-1"], ["allcaps3", "iso-8859-1"],
["keepcase", "iso-8859-1"], ["keepcase", "iso-8859-1"],
["i58202", "iso-8859-1"], ["i58202", "iso-8859-1"],
["map", "iso-8859-1"], ["map", "iso-8859-1"],
["rep", "iso-8859-1"], ["rep", "iso-8859-1"],
["sug", "iso-8859-1"], ["sug", "iso-8859-1"],
["sugutf", "UTF-8"], ["sugutf", "UTF-8"],
["phone", "iso-8859-1"], ["phone", "iso-8859-1"],
["flag", "iso-8859-1"], ["flag", "iso-8859-1"],
["flaglong", "iso-8859-1"], ["flaglong", "iso-8859-1"],
["flagnum", "iso-8859-1"], ["flagnum", "iso-8859-1"],
["flagutf8", "UTF-8"], ["flagutf8", "UTF-8"],
["slash", "iso-8859-1"], ["slash", "iso-8859-1"],
["forbiddenword", "iso-8859-1"], ["forbiddenword", "iso-8859-1"],
["nosuggest", "iso-8859-1"], ["nosuggest", "iso-8859-1"],
["alias", "iso-8859-1"], ["alias", "iso-8859-1"],
["alias2", "iso-8859-1"], ["alias2", "iso-8859-1"],
["alias3", "iso-8859-1"], ["alias3", "iso-8859-1"],
["breakdefault", "iso-8859-1"], ["breakdefault", "iso-8859-1"],
["break", "UTF-8"], ["break", "UTF-8"],
["needaffix", "iso-8859-1"], ["needaffix", "iso-8859-1"],
["needaffix2", "iso-8859-1"], ["needaffix2", "iso-8859-1"],
["needaffix3", "iso-8859-1"], ["needaffix3", "iso-8859-1"],
["needaffix4", "iso-8859-1"], ["needaffix4", "iso-8859-1"],
["needaffix5", "iso-8859-1"], ["needaffix5", "iso-8859-1"],
["circumfix", "iso-8859-1"], ["circumfix", "iso-8859-1"],
["fogemorpheme", "iso-8859-1"], ["fogemorpheme", "iso-8859-1"],
["onlyincompound", "iso-8859-1"], ["onlyincompound", "iso-8859-1"],
["complexprefixes", "iso-8859-1"], ["complexprefixes", "iso-8859-1"],
["complexprefixes2", "iso-8859-1"], ["complexprefixes2", "iso-8859-1"],
["complexprefixesutf", "UTF-8"], ["complexprefixesutf", "UTF-8"],
["conditionalprefix", "iso-8859-1"], ["conditionalprefix", "iso-8859-1"],
["zeroaffix", "iso-8859-1"], ["zeroaffix", "iso-8859-1"],
["utf8", "UTF-8"], ["utf8", "UTF-8"],
["utf8-bom", "UTF-8", {1: "todo"}], ["utf8-bom", "UTF-8", { 1: "todo" }],
["utf8-bom2", "UTF-8", {1: "todo"}], ["utf8-bom2", "UTF-8", { 1: "todo" }],
["utf8-nonbmp", "UTF-8", {1: "todo", 2: "todo", 3: "todo", 4: "todo"}], ["utf8-nonbmp", "UTF-8", { 1: "todo", 2: "todo", 3: "todo", 4: "todo" }],
["compoundflag", "iso-8859-1"], ["compoundflag", "iso-8859-1"],
["compoundrule", "iso-8859-1"], ["compoundrule", "iso-8859-1"],
["compoundrule2", "iso-8859-1"], ["compoundrule2", "iso-8859-1"],
["compoundrule3", "iso-8859-1"], ["compoundrule3", "iso-8859-1"],
["compoundrule4", "iso-8859-1"], ["compoundrule4", "iso-8859-1"],
["compoundrule5", "UTF-8"], ["compoundrule5", "UTF-8"],
["compoundrule6", "iso-8859-1"], ["compoundrule6", "iso-8859-1"],
["compoundrule7", "iso-8859-1"], ["compoundrule7", "iso-8859-1"],
["compoundrule8", "iso-8859-1"], ["compoundrule8", "iso-8859-1"],
["compoundaffix", "iso-8859-1"], ["compoundaffix", "iso-8859-1"],
["compoundaffix2", "iso-8859-1"], ["compoundaffix2", "iso-8859-1"],
["compoundaffix3", "iso-8859-1"], ["compoundaffix3", "iso-8859-1"],
["checkcompounddup", "iso-8859-1"], ["checkcompounddup", "iso-8859-1"],
["checkcompoundtriple", "iso-8859-1"], ["checkcompoundtriple", "iso-8859-1"],
["simplifiedtriple", "iso-8859-1"], ["simplifiedtriple", "iso-8859-1"],
["checkcompoundrep", "iso-8859-1"], ["checkcompoundrep", "iso-8859-1"],
["checkcompoundcase2", "iso-8859-1"], ["checkcompoundcase2", "iso-8859-1"],
["checkcompoundcaseutf", "UTF-8"], ["checkcompoundcaseutf", "UTF-8"],
["checkcompoundpattern", "iso-8859-1"], ["checkcompoundpattern", "iso-8859-1"],
["checkcompoundpattern2", "iso-8859-1"], ["checkcompoundpattern2", "iso-8859-1"],
["checkcompoundpattern3", "iso-8859-1"], ["checkcompoundpattern3", "iso-8859-1"],
["checkcompoundpattern4", "iso-8859-1"], ["checkcompoundpattern4", "iso-8859-1"],
["utfcompound", "UTF-8"], ["utfcompound", "UTF-8"],
["checksharps", "iso-8859-1"], ["checksharps", "iso-8859-1"],
["checksharpsutf", "UTF-8"], ["checksharpsutf", "UTF-8"],
["germancompounding", "iso-8859-1"], ["germancompounding", "iso-8859-1"],
["germancompoundingold", "iso-8859-1"], ["germancompoundingold", "iso-8859-1"],
["i35725", "iso-8859-1"], ["i35725", "iso-8859-1"],
["i53643", "iso-8859-1"], ["i53643", "iso-8859-1"],
["i54633", "iso-8859-1"], ["i54633", "iso-8859-1"],
["i54980", "iso-8859-1", {1: "todo", 3: "todo"}], ["i54980", "iso-8859-1", { 1: "todo", 3: "todo" }],
["maputf", "UTF-8"], ["maputf", "UTF-8"],
["reputf", "UTF-8"], ["reputf", "UTF-8"],
["ignore", "iso-8859-1"], ["ignore", "iso-8859-1"],
["ignoreutf", "UTF-8", [
{1: "todo", 2: "todo", 3: "todo", 4: "todo", 5: "todo", 6: "todo", "ignoreutf",
7: "todo", 8: "todo"}], "UTF-8",
["1592880", "iso-8859-1"], {
["1695964", "iso-8859-1"], 1: "todo",
["1463589", "iso-8859-1"], 2: "todo",
["1463589-utf", "UTF-8"], 3: "todo",
["IJ", "iso-8859-1"], 4: "todo",
["i68568", "iso-8859-1"], 5: "todo",
["i68568utf", "UTF-8"], 6: "todo",
["1706659", "iso-8859-1"], 7: "todo",
["digits-in-words", "iso-8859-1"], 8: "todo",
// ["colons-in-words", "iso-8859-1"], Suggestion test only },
["ngram-utf-fix", "UTF-8"], ],
["morph", "us-ascii", ["1592880", "iso-8859-1"],
{11: "todo", 12: "todo", 13: "todo", 14: "todo", 15: "todo", 16: "todo", ["1695964", "iso-8859-1"],
17: "todo", 18: "todo", 19: "todo", 20: "todo", 21: "todo", 22: "todo", ["1463589", "iso-8859-1"],
23: "todo", 24: "todo", 25: "todo", 26: "todo", 27: "todo"}], ["1463589-utf", "UTF-8"],
["1975530", "UTF-8"], ["IJ", "iso-8859-1"],
["fullstrip", "iso-8859-1"], ["i68568", "iso-8859-1"],
["iconv", "UTF-8"], ["i68568utf", "UTF-8"],
["oconv", "UTF-8"], ["1706659", "iso-8859-1"],
["encoding", "iso-8859-1", {1: "todo", 3: "todo"}], ["digits-in-words", "iso-8859-1"],
["korean", "UTF-8"], // ["colons-in-words", "iso-8859-1"], Suggestion test only
["opentaal-forbiddenword1", "UTF-8"], ["ngram-utf-fix", "UTF-8"],
["opentaal-forbiddenword2", "UTF-8"], [
["opentaal-keepcase", "UTF-8"], "morph",
["arabic", "UTF-8"], "us-ascii",
["2970240", "iso-8859-1"], {
["2970242", "iso-8859-1"], 11: "todo",
["breakoff", "iso-8859-1"], 12: "todo",
["opentaal-cpdpat", "iso-8859-1"], 13: "todo",
["opentaal-cpdpat2", "iso-8859-1"], 14: "todo",
["2999225", "iso-8859-1"], 15: "todo",
["onlyincompound2", "iso-8859-1"], 16: "todo",
["forceucase", "iso-8859-1"], 17: "todo",
["warn", "iso-8859-1"] 18: "todo",
19: "todo",
20: "todo",
21: "todo",
22: "todo",
23: "todo",
24: "todo",
25: "todo",
26: "todo",
27: "todo",
},
],
["1975530", "UTF-8"],
["fullstrip", "iso-8859-1"],
["iconv", "UTF-8"],
["oconv", "UTF-8"],
["encoding", "iso-8859-1", { 1: "todo", 3: "todo" }],
["korean", "UTF-8"],
["opentaal-forbiddenword1", "UTF-8"],
["opentaal-forbiddenword2", "UTF-8"],
["opentaal-keepcase", "UTF-8"],
["arabic", "UTF-8"],
["2970240", "iso-8859-1"],
["2970242", "iso-8859-1"],
["breakoff", "iso-8859-1"],
["opentaal-cpdpat", "iso-8859-1"],
["opentaal-cpdpat2", "iso-8859-1"],
["2999225", "iso-8859-1"],
["onlyincompound2", "iso-8859-1"],
["forceucase", "iso-8859-1"],
["warn", "iso-8859-1"],
]; ];
function* do_get_file_by_line(file, charset) { function* do_get_file_by_line(file, charset) {
dump("getting file by line for file " + file.path + "\n"); dump("getting file by line for file " + file.path + "\n");
dump("using charset " + charset +"\n"); dump("using charset " + charset + "\n");
let fis = Cc["@mozilla.org/network/file-input-stream;1"]. let fis = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(
createInstance(Ci.nsIFileInputStream); Ci.nsIFileInputStream
fis.init(file, 0x1 /* READONLY */, );
0o444, Ci.nsIFileInputStream.CLOSE_ON_EOF); fis.init(file, 0x1 /* READONLY */, 0o444, Ci.nsIFileInputStream.CLOSE_ON_EOF);
let lis = Cc["@mozilla.org/intl/converter-input-stream;1"]. let lis = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance(
createInstance(Ci.nsIConverterInputStream); Ci.nsIConverterInputStream
);
lis.init(fis, charset, 1024, 0); lis.init(fis, charset, 1024, 0);
lis.QueryInterface(Ci.nsIUnicharLineInputStream); lis.QueryInterface(Ci.nsIUnicharLineInputStream);
@ -152,7 +183,7 @@ function do_run_test(checker, name, charset, todo_good, todo_bad) {
let bad = do_get_file("data/" + name + ".wrong", true); let bad = do_get_file("data/" + name + ".wrong", true);
let sug = do_get_file("data/" + name + ".sug", true); let sug = do_get_file("data/" + name + ".sug", true);
dump("Need some expected output\n") dump("Need some expected output\n");
Assert.ok(good.exists() || bad.exists() || sug.exists()); Assert.ok(good.exists() || bad.exists() || sug.exists());
dump("Setting dictionary to " + name + "\n"); dump("Setting dictionary to " + name + "\n");
@ -196,12 +227,13 @@ function do_run_test(checker, name, charset, todo_good, todo_bad) {
} }
} }
// XXXkhuey test suggestions // XXXkhuey test suggestions
} }
function run_test() { function run_test() {
let spellChecker = Cc["@mozilla.org/spellchecker/engine;1"]. let spellChecker = Cc["@mozilla.org/spellchecker/engine;1"].getService(
getService(Ci.mozISpellCheckingEngine); Ci.mozISpellCheckingEngine
);
Assert.ok(!!spellChecker, "Should have a spell checker"); Assert.ok(!!spellChecker, "Should have a spell checker");
spellChecker.QueryInterface(Ci.mozISpellCheckingEngine); spellChecker.QueryInterface(Ci.mozISpellCheckingEngine);

View file

@ -1,22 +1,31 @@
"use strict"; "use strict";
const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); const { XPCOMUtils } = ChromeUtils.import(
const {OS} = ChromeUtils.import("resource://gre/modules/osfile.jsm"); "resource://gre/modules/XPCOMUtils.jsm"
);
const { OS } = ChromeUtils.import("resource://gre/modules/osfile.jsm");
Cu.importGlobalProperties(["TextEncoder"]); Cu.importGlobalProperties(["TextEncoder"]);
XPCOMUtils.defineLazyServiceGetter(this, "spellCheck", XPCOMUtils.defineLazyServiceGetter(
"@mozilla.org/spellchecker/engine;1", "mozISpellCheckingEngine"); this,
"spellCheck",
"@mozilla.org/spellchecker/engine;1",
"mozISpellCheckingEngine"
);
const nsFile = Components.Constructor("@mozilla.org/file/local;1", "nsIFile", const nsFile = Components.Constructor(
"initWithPath"); "@mozilla.org/file/local;1",
"nsIFile",
"initWithPath"
);
add_task(async function() { add_task(async function() {
let prof = do_get_profile(); let prof = do_get_profile();
let basePath = OS.Path.join(prof.path, "\u263a", "dictionaries"); let basePath = OS.Path.join(prof.path, "\u263a", "dictionaries");
let baseDir = nsFile(basePath); let baseDir = nsFile(basePath);
await OS.File.makeDir(basePath, {from: prof.path}); await OS.File.makeDir(basePath, { from: prof.path });
let dicPath = OS.Path.join(basePath, "dict.dic"); let dicPath = OS.Path.join(basePath, "dict.dic");
let affPath = OS.Path.join(basePath, "dict.aff"); let affPath = OS.Path.join(basePath, "dict.aff");
@ -29,6 +38,8 @@ add_task(async function() {
spellCheck.loadDictionariesFromDir(baseDir); spellCheck.loadDictionariesFromDir(baseDir);
spellCheck.dictionary = "dict"; spellCheck.dictionary = "dict";
ok(spellCheck.check(WORD), "Dictionary should have been loaded from a unicode path"); ok(
spellCheck.check(WORD),
"Dictionary should have been loaded from a unicode path"
);
}); });

View file

@ -1,4 +1,4 @@
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
// Chrome scripts are run with synchronous messages, so make sure we're completely // Chrome scripts are run with synchronous messages, so make sure we're completely
// decoupled from the content process before doing this work. // decoupled from the content process before doing this work.

View file

@ -6,90 +6,95 @@ var gDetectorList;
var gTestIndex; var gTestIndex;
var gLocalDir; var gLocalDir;
function CharsetDetectionTests(aTestFile, aExpectedCharset, aDetectorList) function CharsetDetectionTests(aTestFile, aExpectedCharset, aDetectorList) {
{ gExpectedCharset = aExpectedCharset;
gExpectedCharset = aExpectedCharset; gDetectorList = aDetectorList;
gDetectorList = aDetectorList;
InitDetectorTests(); InitDetectorTests();
var fileURI = gLocalDir + aTestFile; var fileURI = gLocalDir + aTestFile;
$("testframe").src = fileURI; $("testframe").src = fileURI;
SimpleTest.waitForExplicitFinish(); SimpleTest.waitForExplicitFinish();
} }
function InitDetectorTests() function InitDetectorTests() {
{ var prefService = Cc["@mozilla.org/preferences-service;1"].getService(
var prefService = Cc["@mozilla.org/preferences-service;1"] Ci.nsIPrefBranch
.getService(Ci.nsIPrefBranch); );
var str = Cc["@mozilla.org/supports-string;1"] var str = Cc["@mozilla.org/supports-string;1"].createInstance(
.createInstance(Ci.nsISupportsString); Ci.nsISupportsString
var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"] );
.getService(Ci.mozIJSSubScriptLoader); var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(
var ioService = Cc['@mozilla.org/network/io-service;1'] Ci.mozIJSSubScriptLoader
.getService(Ci.nsIIOService); );
loader.loadSubScript("chrome://mochikit/content/chrome-harness.js"); var ioService = Cc["@mozilla.org/network/io-service;1"].getService(
Ci.nsIIOService
);
loader.loadSubScript("chrome://mochikit/content/chrome-harness.js");
try { try {
gOldPref = prefService gOldPref = prefService.getComplexValue(
.getComplexValue("intl.charset.detector", "intl.charset.detector",
Ci.nsIPrefLocalizedString).data; Ci.nsIPrefLocalizedString
} catch (e) { ).data;
gOldPref = ""; } catch (e) {
} gOldPref = "";
SetDetectorPref(gDetectorList[0]); }
gTestIndex = 0; SetDetectorPref(gDetectorList[0]);
$("testframe").onload = DoDetectionTest; gTestIndex = 0;
$("testframe").onload = DoDetectionTest;
if (gExpectedCharset == "default") { if (gExpectedCharset == "default") {
// No point trying to be generic here, because we have plenty of other // No point trying to be generic here, because we have plenty of other
// unit tests that fail if run using a non-windows-1252 locale. // unit tests that fail if run using a non-windows-1252 locale.
gExpectedCharset = "windows-1252"; gExpectedCharset = "windows-1252";
} }
// Get the local directory. This needs to be a file: URI because chrome: // Get the local directory. This needs to be a file: URI because chrome:
// URIs are always UTF-8 (bug 617339) and we are testing decoding from other // URIs are always UTF-8 (bug 617339) and we are testing decoding from other
// charsets. // charsets.
var jar = getJar(getRootDirectory(window.location.href)); var jar = getJar(getRootDirectory(window.location.href));
var dir = jar ? var dir = jar
extractJarToTmp(jar) : ? extractJarToTmp(jar)
getChromeDir(getResolvedURI(window.location.href)); : getChromeDir(getResolvedURI(window.location.href));
gLocalDir = ioService.newFileURI(dir).spec; gLocalDir = ioService.newFileURI(dir).spec;
} }
function SetDetectorPref(aPrefValue) function SetDetectorPref(aPrefValue) {
{ var fallback = "";
var fallback = ""; if (aPrefValue == "ja_parallel_state_machine") {
if (aPrefValue == "ja_parallel_state_machine") { fallback = "Shift_JIS";
fallback = "Shift_JIS"; } else if (aPrefValue == "ruprob" || aPrefValue == "ukprob") {
} else if (aPrefValue == "ruprob" || aPrefValue == "ukprob") { fallback = "windows-1251";
fallback = "windows-1251"; }
} var prefService = Cc["@mozilla.org/preferences-service;1"].getService(
var prefService = Cc["@mozilla.org/preferences-service;1"] Ci.nsIPrefBranch
.getService(Ci.nsIPrefBranch); );
prefService.setStringPref("intl.charset.detector", aPrefValue); prefService.setStringPref("intl.charset.detector", aPrefValue);
prefService.setStringPref("intl.charset.fallback.override", fallback); prefService.setStringPref("intl.charset.fallback.override", fallback);
gCurrentDetector = aPrefValue; gCurrentDetector = aPrefValue;
} }
function DoDetectionTest() { function DoDetectionTest() {
var iframeDoc = $("testframe").contentDocument; var iframeDoc = $("testframe").contentDocument;
var charset = iframeDoc.characterSet; var charset = iframeDoc.characterSet;
is(charset, gExpectedCharset, is(
"decoded as " + gExpectedCharset + " by " + gDetectorList[gTestIndex]); charset,
gExpectedCharset,
"decoded as " + gExpectedCharset + " by " + gDetectorList[gTestIndex]
);
if (++gTestIndex < gDetectorList.length) { if (++gTestIndex < gDetectorList.length) {
SetDetectorPref(gDetectorList[gTestIndex]); SetDetectorPref(gDetectorList[gTestIndex]);
iframeDoc.location.reload(); iframeDoc.location.reload();
} else { } else {
CleanUpDetectionTests(); CleanUpDetectionTests();
} }
} }
function CleanUpDetectionTests() { function CleanUpDetectionTests() {
SetDetectorPref(gOldPref); SetDetectorPref(gOldPref);
SimpleTest.finish(); SimpleTest.finish();
} }