庖丁解牛学前端2——从domain字段来分析cookie的优先级

参考文献:

  1. RFC 2109 HTTP 状态存储规范 由贝尔实验室发布于1997年
  2. RFC 6265 HTTP cookie规范 由UC伯克利发布于2011年

从一个BUG入手:

名字相同且在父子域名下的cookie,会互相干扰,于是希望彻底弄懂Cookie的优先级问题。

背景知识:

  • server拿到的cookie是string,可以解析为List>,除了键值就不包含其他信息,因此cookie的优先级的控制只能由浏览器来实现。

通过以下javascript写入cookie后发现,实际写入的cookie的domain值为.sub.father.com

document.cookie = "name=sub.father.com;domain=sub.father.com;path=/";

RFC 2109里找到答案:

The Domain attribute specifies the domain for which the
cookie is valid.  An explicitly specified domain must always start
with a dot.

局部结论1:

  • if cookie的显式domain参数不以dot开头,这个cookie是无效的(RFC)
  • 设置cookie时,显式设置domain参数的情况下,不管前面有没有dot,自动加dot。(浏览器实现)

写了一个最简单的koa服务器来打印cookie的值,以便后续实验的验证,后续所有的实验都在http://sub.father.com/cookieTestURL下进行。

// router
router.get('/cookieTest',controller.cookieTest);

// controller
let cookieTest = async (ctx) => {
  ctx.body = ctx.cookies.get('name'); // 将名字为name的cookie打印出来
};

实验一:显式/隐式子域名 vs 显式父域名

// .sub.father.com vs .father.com
document.cookie = "name=.sub.father.com;domain=.sub.father.com;";
document.cookie = "name=.father.com;domain=.father.com;";
// chrome:  .sub.father.com
// firefox: .sub.father.com
// safari:  .father.com

// 将时间顺序颠倒,再来一次
document.cookie = "name=.father.com;domain=.father.com;";
document.cookie = "name=.sub.father.com;domain=.sub.father.com;";
// chrome:  .father.com
// firefox: .father.com 
// safari:  .father.com 

// sub.father.com vs .father.com
document.cookie = "name=sub.father.com;";
document.cookie = "name=.father.com;domain=.father.com;";
// chrome:  sub.father.com
// firefox: sub.father.com
// safari:  .father.com

// 将时间顺序颠倒,再来一次
document.cookie = "name=.father.com;domain=.father.com;";
document.cookie = "name=sub.father.com;";
// chrome:  .father.com
// firefox: .father.com
// safari:  .father.com

局部结论2:

  • chromefirefox浏览器下,较早设置的那个cookie优先级高
  • safari浏览器下,.father.com优先级高于.sub.father.comsub.father.com

注:局部结论2是通过实验得出的结论,并没有找到对应的RFC规范作支撑。

实验二:使用隐式domain法,提前在father.com下写入cookie,在子域名尝试读取。

document.cookie
// ""

局部结论3:

  • domain为father.com的cookie在sub.father.com页面不可见。

理论支撑:见RFC 6265的domain-match算法:

A string domain-matches a given domain string if at least one of the
following conditions hold:
   o  The domain string and the string are identical.  (Note that both
      the domain string and the string will have been canonicalized to
      lower case at this point.)
   o  All of the following conditions hold:
      *  The domain string is a suffix of the string.
      *  The last character of the string that is not included in the
         domain string is a %x2E (".") character.
      *  The string is a host name (i.e., not an IP address).

满足第一个条件的是精确匹配,满足第二个条件的是子域名匹配。证明局部结论3的正确性。

总结

  1. 通过RFC 6265定义cookie可见性。
  2. 在cookie可见的情况下,针对不同的domain,各个浏览器有自己的实现方式(主要体现为按时创建时间先后父域名优先)。

你可能感兴趣的:(庖丁解牛学前端)