Bug 1351663 - Support SameSite flag in browser.cookies API draft
authorRob Wu <rob@robwu.nl>
Sat, 09 Jun 2018 01:26:26 +0200
changeset 813066 fbb47c48fd9962d0e1a566813ea911b51da1ae78
parent 813065 32e8a023568ab9932319345cd4ddba8711fe036a
push id114753
push userbmo:rob@robwu.nl
push dateMon, 02 Jul 2018 10:34:57 +0000
bugs1351663
milestone63.0a1
Bug 1351663 - Support SameSite flag in browser.cookies API A part of cookies.json is copied from https://chromium.googlesource.com/chromium/src/+/ea90e377568cce415d261ecd472ab941ccc42a8e/chrome/common/extensions/api/cookies.json MozReview-Commit-ID: LCVN9Y8uHIL
toolkit/components/extensions/parent/ext-cookies.js
toolkit/components/extensions/schemas/cookies.json
toolkit/components/extensions/test/mochitest/test_ext_cookies.html
toolkit/components/extensions/test/mochitest/test_ext_cookies_containers.html
toolkit/components/extensions/test/xpcshell/test_ext_cookies_samesite.js
toolkit/components/extensions/test/xpcshell/xpcshell-common.ini
--- a/toolkit/components/extensions/parent/ext-cookies.js
+++ b/toolkit/components/extensions/parent/ext-cookies.js
@@ -4,25 +4,32 @@ ChromeUtils.defineModuleGetter(this, "Se
                                "resource://gre/modules/Services.jsm");
 
 /* globals DEFAULT_STORE, PRIVATE_STORE */
 
 var {
   ExtensionError,
 } = ExtensionUtils;
 
+const SAME_SITE_STATUSES = [
+  "no_restriction", // Index 0 = Ci.nsICookie2.SAMESITE_UNSET
+  "lax",            // Index 1 = Ci.nsICookie2.SAMESITE_LAX
+  "strict",         // Index 2 = Ci.nsICookie2.SAMESITE_STRICT
+];
+
 const convertCookie = ({cookie, isPrivate}) => {
   let result = {
     name: cookie.name,
     value: cookie.value,
     domain: cookie.host,
     hostOnly: !cookie.isDomain,
     path: cookie.path,
     secure: cookie.isSecure,
     httpOnly: cookie.isHttpOnly,
+    sameSite: SAME_SITE_STATUSES[cookie.sameSite],
     session: cookie.isSession,
     firstPartyDomain: cookie.originAttributes.firstPartyDomain || "",
   };
 
   if (!cookie.isSession) {
     result.expirationDate = cookie.expiry;
   }
 
@@ -371,20 +378,23 @@ this.cookies = class extends ExtensionAP
           }
 
           let originAttributes = {
             userContextId,
             privateBrowsingId: isPrivate ? 1 : 0,
             firstPartyDomain: details.firstPartyDomain,
           };
 
+          let sameSite = SAME_SITE_STATUSES.indexOf(details.sameSite);
+
           // The permission check may have modified the domain, so use
           // the new value instead.
           Services.cookies.add(cookieAttrs.host, path, name, value,
-                               secure, httpOnly, isSession, expiry, originAttributes);
+                               secure, httpOnly, isSession, expiry,
+                               originAttributes, sameSite);
 
           return self.cookies.get(details);
         },
 
         remove: function(details) {
           normalizeFirstPartyDomain(details);
 
           let allowed = ["url", "name", "storeId", "firstPartyDomain"];
--- a/toolkit/components/extensions/schemas/cookies.json
+++ b/toolkit/components/extensions/schemas/cookies.json
@@ -18,27 +18,34 @@
     ]
   },
   {
     "namespace": "cookies",
     "description": "Use the <code>browser.cookies</code> API to query and modify cookies, and to be notified when they change.",
     "permissions": ["cookies"],
     "types": [
       {
+        "id": "SameSiteStatus",
+        "type": "string",
+        "enum": ["no_restriction", "lax", "strict"],
+        "description": "A cookie's 'SameSite' state (https://tools.ietf.org/html/draft-west-first-party-cookies). 'no_restriction' corresponds to a cookie set without a 'SameSite' attribute, 'lax' to 'SameSite=Lax', and 'strict' to 'SameSite=Strict'."
+      },
+      {
         "id": "Cookie",
         "type": "object",
         "description": "Represents information about an HTTP cookie.",
         "properties": {
           "name": {"type": "string", "description": "The name of the cookie."},
           "value": {"type": "string", "description": "The value of the cookie."},
           "domain": {"type": "string", "description": "The domain of the cookie (e.g. \"www.google.com\", \"example.com\")."},
           "hostOnly": {"type": "boolean", "description": "True if the cookie is a host-only cookie (i.e. a request's host must exactly match the domain of the cookie)."},
           "path": {"type": "string", "description": "The path of the cookie."},
           "secure": {"type": "boolean", "description": "True if the cookie is marked as Secure (i.e. its scope is limited to secure channels, typically HTTPS)."},
           "httpOnly": {"type": "boolean", "description": "True if the cookie is marked as HttpOnly (i.e. the cookie is inaccessible to client-side scripts)."},
+          "sameSite": {"$ref": "SameSiteStatus", "description": "The cookie's same-site status (i.e. whether the cookie is sent with cross-site requests)."},
           "session": {"type": "boolean", "description": "True if the cookie is a session cookie, as opposed to a persistent cookie with an expiration date."},
           "expirationDate": {"type": "number", "optional": true, "description": "The expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies."},
           "storeId": {"type": "string", "description": "The ID of the cookie store containing this cookie, as provided in getAllCookieStores()."},
           "firstPartyDomain": {"type": "string", "description": "The first-party domain of the cookie."}
         }
       },
       {
         "id": "CookieStore",
@@ -131,16 +138,17 @@
             "properties": {
               "url": {"type": "string", "description": "The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. If host permissions for this URL are not specified in the manifest file, the API call will fail."},
               "name": {"type": "string", "optional": true, "description": "The name of the cookie. Empty by default if omitted."},
               "value": {"type": "string", "optional": true, "description": "The value of the cookie. Empty by default if omitted."},
               "domain": {"type": "string", "optional": true, "description": "The domain of the cookie. If omitted, the cookie becomes a host-only cookie."},
               "path": {"type": "string", "optional": true, "description": "The path of the cookie. Defaults to the path portion of the url parameter."},
               "secure": {"type": "boolean", "optional": true, "description": "Whether the cookie should be marked as Secure. Defaults to false."},
               "httpOnly": {"type": "boolean", "optional": true, "description": "Whether the cookie should be marked as HttpOnly. Defaults to false."},
+              "sameSite": {"$ref": "SameSiteStatus", "optional": true, "description": "The cookie's same-site status.", "default": "no_restriction"},
               "expirationDate": {"type": "number", "optional": true, "description": "The expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie becomes a session cookie."},
               "storeId": {"type": "string", "optional": true, "description": "The ID of the cookie store in which to set the cookie. By default, the cookie is set in the current execution context's cookie store."},
               "firstPartyDomain": {"type": "string", "optional": true, "description": "The first-party domain of the cookie. This attribute is required if First-Party Isolation is enabled."}
             }
           },
           {
             "type": "function",
             "name": "callback",
--- a/toolkit/components/extensions/test/mochitest/test_ext_cookies.html
+++ b/toolkit/components/extensions/test/mochitest/test_ext_cookies.html
@@ -76,16 +76,17 @@ add_task(async function test_cookies() {
     let expected = {
       name: "name1",
       value: "value1",
       domain: "example.org",
       hostOnly: true,
       path: "/",
       secure: false,
       httpOnly: false,
+      sameSite: "no_restriction",
       session: false,
       expirationDate: THE_FUTURE,
       storeId: STORE_ID,
       firstPartyDomain: "",
     };
 
     // Remove all cookies before starting the test.
     await browser.browsingData.removeCookies({});
--- a/toolkit/components/extensions/test/mochitest/test_ext_cookies_containers.html
+++ b/toolkit/components/extensions/test/mochitest/test_ext_cookies_containers.html
@@ -40,16 +40,17 @@ add_task(async function test_cookie_cont
     let expected = {
       name: "name1",
       value: "value1",
       domain: "example.org",
       hostOnly: true,
       path: "/",
       secure: false,
       httpOnly: false,
+      sameSite: "no_restriction",
       session: false,
       expirationDate: THE_FUTURE,
       storeId: "firefox-container-1",
       firstPartyDomain: "",
     };
 
     let cookie = await browser.cookies.set({
       url: TEST_URL, name: "name1", value: "value1",
new file mode 100644
--- /dev/null
+++ b/toolkit/components/extensions/test/xpcshell/test_ext_cookies_samesite.js
@@ -0,0 +1,73 @@
+"use strict";
+
+const server = createHttpServer({hosts: ["example.org"]});
+server.registerPathHandler("/sameSiteCookiesApiTest", (request, response) => {
+  response.setStatusLine(request.httpVersion, 200, "OK");
+  response.setHeader("Content-Type", "text/html; charset=utf-8", false);
+  response.write("<!DOCTYPE html><html></html>");
+});
+
+add_task(async function test_samesite_cookies() {
+  function contentScript() {
+    document.cookie = "test1=whatever";
+    document.cookie = "test2=whatever; SameSite=lax";
+    document.cookie = "test3=whatever; SameSite=strict";
+    browser.runtime.sendMessage("do-check-cookies");
+  }
+  async function background() {
+    await new Promise(resolve => {
+      browser.runtime.onMessage.addListener(msg => {
+        browser.test.assertEq("do-check-cookies", msg, "expected message");
+        resolve();
+      });
+    });
+
+    const url = "https://example.org/";
+
+    // Baseline. Every cookie must have the expected sameSite.
+    let cookie = await browser.cookies.get({url, name: "test1"});
+    browser.test.assertEq("no_restriction", cookie.sameSite, "Expected sameSite for test1");
+
+    cookie = await browser.cookies.get({url, name: "test2"});
+    browser.test.assertEq("lax", cookie.sameSite, "Expected sameSite for test2");
+
+    cookie = await browser.cookies.get({url, name: "test3"});
+    browser.test.assertEq("strict", cookie.sameSite, "Expected sameSite for test3");
+
+    // Testing cookies.getAll + cookies.set
+    let cookies = await browser.cookies.getAll({url, name: "test3"});
+    browser.test.assertEq(1, cookies.length, "There is only one test3 cookie");
+
+    cookie = await browser.cookies.set({url, name: "test3", value: "newvalue"});
+    browser.test.assertEq("no_restriction", cookie.sameSite, "sameSite defaults to no_restriction");
+
+    for (let sameSite of ["no_restriction", "lax", "strict"]) {
+      cookie = await browser.cookies.set({url, name: "test3", sameSite});
+      browser.test.assertEq(sameSite, cookie.sameSite, `Expected sameSite=${sameSite} in return value of cookies.set`);
+      cookies = await browser.cookies.getAll({url, name: "test3"});
+      browser.test.assertEq(1, cookies.length, `test3 is still the only cookie after setting sameSite=${sameSite}`);
+      browser.test.assertEq(sameSite, cookies[0].sameSite, `test3 was updated to sameSite=${sameSite}`);
+    }
+
+    browser.test.notifyPass("cookies");
+  }
+  let extension = ExtensionTestUtils.loadExtension({
+    background,
+    manifest: {
+      permissions: ["cookies", "*://example.org/"],
+      content_scripts: [{
+        matches: ["*://example.org/sameSiteCookiesApiTest*"],
+        js: ["contentscript.js"],
+      }],
+    },
+    files: {
+      "contentscript.js": contentScript,
+    },
+  });
+
+  await extension.startup();
+  let contentPage = await ExtensionTestUtils.loadContentPage("http://example.org/sameSiteCookiesApiTest");
+  await extension.awaitFinish("cookies");
+  await contentPage.close();
+  await extension.unload();
+});
--- a/toolkit/components/extensions/test/xpcshell/xpcshell-common.ini
+++ b/toolkit/components/extensions/test/xpcshell/xpcshell-common.ini
@@ -14,16 +14,17 @@ skip-if = os == "android" # Android does
 [test_ext_background_teardown.js]
 [test_ext_background_telemetry.js]
 [test_ext_background_window_properties.js]
 skip-if = os == "android"
 [test_ext_browserSettings.js]
 [test_ext_browserSettings_homepage.js]
 skip-if = os == "android"
 [test_ext_cookieBehaviors.js]
+[test_ext_cookies_samesite.js]
 [test_ext_content_security_policy.js]
 [test_ext_contentscript_api_injection.js]
 [test_ext_contentscript_async_loading.js]
 skip-if = os == 'android' && debug # The generated script takes too long to load on Android debug
 [test_ext_contentscript_context.js]
 [test_ext_contentscript_create_iframe.js]
 [test_ext_contentscript_css.js]
 [test_ext_contentscript_exporthelpers.js]