Cookie security: what each Set-Cookie attribute does, and how to choose them
Every cookie your server sets travels in a Set-Cookie header, and its attributes decide who can read the cookie, over what connection, to which hosts and paths, for how long and in which cross-site situations.
This guide explains each attribute in plain terms with the standard behind it, and comes with a Set-Cookie decision table for six kinds of cookie and a verification pack you run with Node.js alone.
In this guide
Set-Cookie decision table and cookie verification pack
An illustration on invented hosts. Part 1 is a Set-Cookie decision table for six kinds of cookie a business site sends, with the choice and a sourced reason for every attribute and prefix, and the rules every header has to meet.
How to use itHide the instructions
Parts 2 to 4 are a Node.js lab with no installs: an invented site in a careless and a careful version, a checker that reads each Set-Cookie header from the login, logout, subdomain and cross-site flows and compares it with the table and the cookie draft's rules, and a regression test that fails on the careless version. Part 5 lists steps to confirm in your own browser what it stores and sends, Part 6 points the test at your own site, and Part 7 is a cookie register. Use it for learning and for checking the cookies your own site sets.
cookie-security.txt
Introduction5 lines
Part 1: The Set-Cookie decision table100 lines
Part 2: The lab files744 lines
Part 3: Run the four flows against both versions328 lines
Part 4: The regression test168 lines
Part 5: Check what your own browser stores and sends23 lines
Part 6: Point the test at your own site6 lines
Part 7: A cookie register to keep30 lines
Whole template1,442 lines
ILLUSTRATION ONLY. The hosts app.example.com, shop.example.com, widget.example.net and partner.example.org, every cookie and every cookie value below are invented for this page. The lab runs on your own machine and binds to 127.0.0.1 on a port the system picks. Its responses only set made-up cookies, which a scripted client reads and never stores. Use it for learning and for checking the cookies your own site sets.
What this asset is, and what it is not. Part 1 is a decision table: for six kinds of cookie a business site sends, the choice for each attribute and prefix, with the reason and its source. Parts 2 to 4 are a lab. An invented site sends its cookies in a careless and a careful version, and a checker reads each Set-Cookie header that the login, logout, subdomain and cross-site flows send. For each header it reports, attribute by attribute, what is present, what the decision table expects for that cookie, and whether the cookie draft's prefix rules and other storage rules hold. The checker judges header text against written rules. It is not a browser: it stores no cookies and cannot show what any browser keeps or sends. Part 5 is how to see that in your own browser, Part 6 is how to point the test at your own site, and Part 7 is a cookie register to keep.
Written and run on: Node.js 26.0.0, the only version it was run on. It uses node:http, node:crypto, node:test and node:assert, which ship with Node.js, so there is nothing to install. Every output below comes from that run; cookie values and timings will differ on your machine.
================================================================
PART 1: THE SET-COOKIE DECISION TABLE
Each block below is one kind of cookie a business site sends. For each attribute and prefix it gives the choice, the reason, and the document the reason comes from in parentheses. "This page's advice" marks a choice no source makes for you. Each block ends with the header the careful version of the lab sends, so you can compare it with your own.
Source names used in the table:
RFC 6265 IETF RFC 6265, HTTP State Management Mechanism, April 2011, Standards Track
cookie draft IETF draft-ietf-httpbis-rfc6265bis-22, Cookies: HTTP State Management Mechanism, an Internet-Draft dated 1 December 2025 that would obsolete RFC 6265 if approved
MDN Set-Cookie MDN Web Docs, Set-Cookie header
MDN cookies guide MDN Web Docs, Using HTTP cookies
MDN CHIPS MDN Web Docs, Cookies Having Independent Partitioned State (CHIPS)
MDN Site glossary MDN Web Docs glossary, Site
ASVS 5.0 OWASP ASVS 5.0.0, chapter V3 Web Frontend Security unless another chapter is named, with requirement number and level
WSTG-SESS-09 OWASP Web Security Testing Guide v4.2, Testing for Session Hijacking
OWASP session sheet OWASP Session Management Cheat Sheet
OWASP CSRF sheet OWASP Cross-Site Request Forgery Prevention Cheat Sheet
Django settings Django 6.1 documentation, Settings
Every block has the same eight lines: Prefix, Secure, HttpOnly, SameSite, Domain, Path, Expires or Max-Age, and Partitioned.
ROW 1 SESSION COOKIE: the value that keeps a signed-in visitor signed in
Prefix: __Host-. A browser that supports prefixes accepts a __Host- cookie only if it was set with Secure, a Path of / and no Domain attribute, which locks it to the host that set it (cookie draft 4.1.3.2). ASVS 5.0 3.3.3 (Level 2) asks for __Host- unless a cookie is explicitly designed to be shared with other hosts, and the OWASP session sheet recommends it for session IDs.
Secure: set. Without it the cookie also travels in plain-HTTP requests. The cookie draft's example is an active network attacker who redirects a visitor's request to the site over HTTP, intercepts the cookies the browser includes and replays them (cookie draft 8.3). ASVS 5.0 3.3.1 (Level 1).
HttpOnly: set. Script on the page cannot read the cookie, through document.cookie for example, though the cookie is still sent with requests that script makes (MDN Set-Cookie). ASVS 5.0 3.3.4 (Level 2), which also asks that the session token reaches the browser only through the Set-Cookie header.
SameSite: Lax or Strict, written out. The OWASP session sheet says session cookies must set Strict (its preference) or Lax explicitly, and not rely on the browser default, which varies across browsers and versions. ASVS 5.0 3.3.2 (Level 2) asks for a value set according to the cookie's purpose. The CSRF guide covers the choice between the two.
Domain: leave it out. The cookie then goes only to the host that set it, which MDN Set-Cookie calls more restrictive than setting the host name, because subdomains of the host do not get it. __Host- requires it to be absent.
Path: /. __Host- requires it (cookie draft 4.1.3.2), and Path cannot be relied upon for security in any case (RFC 6265 4.1.2.4).
Expires or Max-Age: none, which makes it a session cookie (MDN Set-Cookie). If yours has to outlive a browser restart, keep it no longer than the absolute session limit your server enforces, because the expiry is not a timeout (this page's advice; the session management guide covers timeouts).
Partitioned: no. It is your own site's cookie, not one set inside another site's page (this page's advice).
Careful lab header: __Host-sid=...; Path=/; Secure; HttpOnly; SameSite=Lax
ROW 2 REMEMBER-THIS-DEVICE COOKIE: a long-lived token that changes how the next sign-in works
Prefix: __Host-, for the reasons in row 1 (ASVS 5.0 3.3.3, Level 2).
Secure: set (ASVS 5.0 3.3.1, Level 1).
HttpOnly: set. No script needs to read it (ASVS 5.0 3.3.4, Level 2).
SameSite: Strict. It only has to reach your own sign-in requests, which come from your own pages (this page's advice; ASVS 5.0 3.3.2 asks for a value set according to the cookie's purpose).
Domain: leave it out, as in row 1.
Path: /, as in row 1.
Expires or Max-Age: Max-Age, set to the remember period your own policy chooses; the lab uses 2592000 seconds as an example. The cookie draft says a browser must limit a cookie's lifetime, that the limit should not be more than 400 days, and that a longer Expires or Max-Age is reduced to the limit (cookie draft 5.5). Max-Age takes precedence when both are set (MDN Set-Cookie). What a remembered device may skip is the session management guide's subject.
Partitioned: no.
Careful lab header: __Host-remember=...; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=2592000
ROW 3 ANTI-FORGERY TOKEN COOKIE: a cookie that carries a CSRF token, as in the double-submit pattern
Prefix: __Host-. The OWASP CSRF sheet says prefixes on cookies with CSRF tokens extend protection against cookies being injected or overwritten, that a __Host- cookie cannot be written or overwritten from another subdomain, and, unless signed-in users need to visit different subdomains, recommends __Host- together with SameSite.
Secure: set (ASVS 5.0 3.3.1, Level 1).
HttpOnly: set when your script does not read the token from this cookie, as in the lab, where the page carries the token. Leave it off when your script does read it, since ASVS 5.0 3.3.4 covers values not meant for script. Django settings says that designating its CSRF cookie HttpOnly doesn't offer any practical protection, because CSRF is only to protect against cross-domain attacks, and that an attacker who can read the cookie via JavaScript is already on the same domain as far as the browser knows.
SameSite: Lax or Strict (this page's advice; ASVS 5.0 3.3.2, Level 2, asks for a value set according to the cookie's purpose). What SameSite does against forged requests is the CSRF guide's subject.
Domain: leave it out, as in row 1.
Path: /, as in row 1.
Expires or Max-Age: none. The token belongs to the session (this page's advice).
Partitioned: no.
Careful lab header: __Host-csrf=...; Path=/; Secure; HttpOnly; SameSite=Strict
ROW 4 PREFERENCE COOKIE THAT SCRIPT READS: a theme or language choice
Prefix: __Host-. ASVS 5.0 3.3.3 (Level 2) asks for it on any cookie not explicitly designed to be shared with other hosts.
Secure: set. The cookie draft says a server using cookies over a secure channel should set Secure on every cookie (cookie draft 8.3). ASVS 5.0 3.3.1 (Level 1) asks for it too, in a section the ASVS introduces as requirements for sensitive cookies.
HttpOnly: off. Your script has to read the value, and HttpOnly forbids script access (MDN Set-Cookie). Keep anything sensitive out of it: ASVS 5.0 14.3.3 (Level 2, chapter V14 Data Protection) asks that data in browser storage, cookies included, contains no sensitive data apart from session tokens.
SameSite: Lax, so the visitor's choice applies when they arrive from a link on another site (this page's advice; MDN cookies guide describes Lax as useful for cookies that affect the display of a site).
Domain: leave it out, as in row 1.
Path: /, as in row 1.
Expires or Max-Age: Max-Age, for as long as the choice should last; the lab uses 31536000 seconds. The cookie draft asks servers to select reasonable expiration periods based on the cookie's purpose rather than gratuitously long ones (cookie draft 7.4).
Partitioned: no.
Careful lab header: __Host-theme=dark; Path=/; Secure; SameSite=Lax; Max-Age=31536000
ROW 5 COOKIE SHARED ACROSS SUBDOMAINS ON PURPOSE: a signed-in hint that shop.example.com reads to show an account link
Prefix: __Secure-. ASVS 5.0 3.3.1 (Level 1) asks for __Secure- on a cookie that does not use __Host-, and the OWASP session sheet says to use __Secure- only when subdomain sharing is required. A browser that supports prefixes accepts it only with Secure (cookie draft 4.1.3.1).
Secure: set, as the prefix requires.
HttpOnly: set, because no script reads it in the lab (ASVS 5.0 3.3.4, Level 2).
SameSite: Lax (this page's advice). Requests between your own subdomains over HTTPS are same-site: a site is determined by the registrable domain, and for SameSite cookies the scheme has to match as well (MDN Site glossary).
Domain: example.com, the parent domain you control, set on purpose. MDN Set-Cookie says setting the domain makes the cookie available to that domain and all its subdomains. Any host under example.com can also set a cookie with this name and Domain (cookie draft 5.7, step 10), and a host receiving it may be unable to tell it from one it set itself (cookie draft 8.6), so the value grants nothing and every server that reads it treats it as untrusted input (this page's advice). WSTG-SESS-09 says full HSTS adoption is required when session cookies are issued with the Domain attribute set, and ASVS 5.0 3.4.1 asks, from Level 2, for an HSTS policy that applies to all subdomains.
Path: / (this page's advice).
Expires or Max-Age: none in the lab. The hint should not outlive the session it signals (this page's advice).
Partitioned: no.
Careful lab header: __Secure-signed_in=yes; Domain=example.com; Path=/; Secure; HttpOnly; SameSite=Lax
ROW 6 EMBEDDED WIDGET COOKIE: a chat or booking widget served from widget.example.net inside other sites' pages
Prefix: __Host-. MDN CHIPS recommends the __Host- prefix on partitioned cookies if you do not need to share them between subdomains.
Secure: set. SameSite=None needs it (MDN Set-Cookie), and a browser that follows the cookie draft ignores a SameSite=None cookie without it (cookie draft 5.7, step 19). Partitioned needs it too (MDN Set-Cookie).
HttpOnly: set if the widget's own script does not read it, as in the lab (ASVS 5.0 3.3.4, Level 2).
SameSite: None. The cookie draft says content intended for embedding in cross-site contexts will not have access to same-site cookies, and that cookies required there should be marked None (cookie draft 8.8.3). It also says a Lax or Strict cookie cannot be set in a response to a cross-site subresource request (cookie draft 4.1.2.7).
Domain: leave it out, as in row 1.
Path: /, as in row 1.
Expires or Max-Age: none in the lab (this page's advice).
Partitioned: set when the widget's state should be kept separately for each site that embeds it. MDN CHIPS says a Partitioned cookie is double-keyed, by the origin that sets it and by the top-level page, marks the feature Baseline 2025, newly available since December 2025, and says it might not work in older devices or browsers. The cookie draft does not define Partitioned, and says most user agents now limit third-party cookies in a variety of ways, so resources cannot rely on them being treated consistently (cookie draft 7.1).
Careful lab header: __Host-widget_session=...; Path=/; Secure; HttpOnly; SameSite=None; Partitioned
RULES EVERY HEADER HAS TO MEET, WHATEVER ITS ROW
A name starting with __Secure- needs the Secure attribute and a secure origin (cookie draft 4.1.3.1; 5.7, steps 13 and 20).
A name starting with __Host- needs Secure, no Domain attribute and a Path attribute of / (cookie draft 4.1.3.2; 5.7, step 21).
A browser that follows the cookie draft matches both prefixes whatever their capitalisation (cookie draft 5.4). The server-side definition is a case-sensitive match, so write them exactly as above (cookie draft 4.1.3).
SameSite=None needs Secure (MDN Set-Cookie; cookie draft 5.7, step 19).
Partitioned needs Secure (MDN Set-Cookie).
A page served over plain http: cannot set a Secure cookie (MDN Set-Cookie; cookie draft 5.7, step 13). MDN notes an exception for localhost.
Name and value together take no more than 4096 bytes (ASVS 5.0 3.3.5, Level 3).
One Set-Cookie header per cookie, never combined into one header, and never two headers with the same cookie name in one response (cookie draft 3 and 4.1.1).
To remove a cookie, send the same name with the same Path and Domain and an Expires date in the past (RFC 6265 3.1). The cookie draft replaces a stored cookie only when the name, domain, host-only flag and path all match (5.7, step 23), and it applies the prefix checks first (steps 20 and 21), so a header that clears a __Host- or __Secure- cookie has to meet the prefix rules too.
================================================================
PART 2: THE LAB FILES
================================================================
Make an empty folder, save the five files below into it with the names shown, and open a terminal in that folder.
================================================================
FILE 1 OF 5: cookie-lab-site.mjs
================================================================
// cookie-lab-site.mjs: an invented business site that sends its cookies in
// two versions, careless and careful. Illustration only. It listens on
// 127.0.0.1, has no accounts, checks no passwords and keeps nothing between
// requests. Each response only sets or clears cookies.
// The scripted client puts the invented host it is pretending to reach in the
// Host header, and the site answers as that host.
import { createServer } from 'node:http'
import { randomBytes } from 'node:crypto'
export const APP_HOST = 'app.example.com'
export const WIDGET_HOST = 'widget.example.net'
// A clearing header carries an Expires date in the past, which is how RFC 6265
// and draft-ietf-httpbis-rfc6265bis-22 show a server removing a cookie.
const PAST_DATE = 'Thu, 01 Jan 1970 00:00:00 GMT'
// The careless version: attributes left out, a session cookie shared with
// every subdomain, a lifetime far past what browsers keep, and a logout that
// clears the wrong scope.
const CARELESS = {
login: function () {
return [
'sid=' + newValue() + '; Domain=example.com; HttpOnly',
'csrf=' + newValue(),
'remember=' + newValue() + '; Max-Age=315360000',
'signed_in=yes; Domain=example.com',
]
},
home: function () {
return ['theme=dark']
},
logout: function () {
return [
'sid=; Path=/; Expires=' + PAST_DATE,
'signed_in=; Path=/; Expires=' + PAST_DATE,
]
},
embed: function () {
return ['widget_session=' + newValue() + '; SameSite=None']
},
}
// The careful version: every cookie set as the decision table says.
const CAREFUL = {
login: function () {
return [
'__Host-sid=' + newValue() + '; Path=/; Secure; HttpOnly; SameSite=Lax',
'__Host-csrf=' + newValue() + '; Path=/; Secure; HttpOnly; SameSite=Strict',
'__Host-remember=' + newValue() + '; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=2592000',
'__Secure-signed_in=yes; Domain=example.com; Path=/; Secure; HttpOnly; SameSite=Lax',
]
},
home: function () {
return ['__Host-theme=dark; Path=/; Secure; SameSite=Lax; Max-Age=31536000']
},
logout: function () {
return [
'__Host-sid=; Path=/; Secure; HttpOnly; SameSite=Lax; Expires=' + PAST_DATE,
'__Host-csrf=; Path=/; Secure; HttpOnly; SameSite=Strict; Expires=' + PAST_DATE,
'__Secure-signed_in=; Domain=example.com; Path=/; Secure; HttpOnly; SameSite=Lax; Expires=' + PAST_DATE,
]
},
embed: function () {
return ['__Host-widget_session=' + newValue() + '; Path=/; Secure; HttpOnly; SameSite=None; Partitioned']
},
}
const VERSIONS = { careless: CARELESS, careful: CAREFUL }
// Which response sets which cookies, by method, host and path.
const ROUTES = [
{ method: 'POST', host: APP_HOST, path: '/account/login', step: 'login' },
{ method: 'GET', host: APP_HOST, path: '/', step: 'home' },
{ method: 'POST', host: APP_HOST, path: '/account/logout', step: 'logout' },
{ method: 'GET', host: WIDGET_HOST, path: '/embed', step: 'embed' },
]
function newValue() {
return randomBytes(16).toString('hex')
}
export function startLabSite(versionName, port) {
const version = VERSIONS[versionName]
if (!version) throw new Error('Unknown version: ' + versionName)
const server = createServer(function (request, response) {
answerRequest(version, request, response)
})
return new Promise(function (resolve) {
server.listen(port || 0, '127.0.0.1', function () {
resolve({ server: server, port: server.address().port })
})
})
}
function answerRequest(version, request, response) {
request.resume()
const host = (request.headers.host || '').toLowerCase()
const path = new URL(request.url, 'http://127.0.0.1').pathname
const route = ROUTES.find(function (candidate) {
return candidate.method === request.method && candidate.host === host && candidate.path === path
})
if (!route) {
response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
response.end('not-found')
return
}
// An array sends one Set-Cookie header per cookie, never a combined one.
response.setHeader('Set-Cookie', version[route.step]())
response.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })
response.end(route.step)
}
================================================================
FILE 2 OF 5: cookie-rules.mjs
================================================================
// cookie-rules.mjs: reads Set-Cookie header text and checks it against the
// decision table and against rules in draft-ietf-httpbis-rfc6265bis-22.
// It judges the text a server sends against written rules. It is not a
// browser: it stores nothing and cannot show what a browser keeps or sends.
export const PARENT_DOMAIN = 'example.com'
// draft-22 section 5.5: browsers limit a cookie's lifetime, and the
// recommended limit is 400 days (34560000 seconds).
export const LIFETIME_LIMIT_SECONDS = 34560000
// ASVS 5.0 requirement 3.3.5: cookie name and value together no more than 4096 bytes.
export const SIZE_LIMIT_BYTES = 4096
// What the decision table expects for each kind of cookie.
export const DECISION_TABLE = {
session: {
label: 'session cookie', prefix: '__Host-', secure: true, httpOnly: true,
sameSite: ['Strict', 'Lax'], domain: '', path: '/', lifetime: 'session', partitioned: false,
},
antiForgery: {
label: 'anti-forgery token cookie', prefix: '__Host-', secure: true, httpOnly: true,
sameSite: ['Strict', 'Lax'], domain: '', path: '/', lifetime: 'session', partitioned: false,
},
rememberDevice: {
label: 'remember-this-device cookie', prefix: '__Host-', secure: true, httpOnly: true,
sameSite: ['Strict'], domain: '', path: '/', lifetime: 'persistent', partitioned: false,
},
preference: {
label: 'preference cookie that script reads', prefix: '__Host-', secure: true, httpOnly: false,
sameSite: ['Lax'], domain: '', path: '/', lifetime: 'persistent', partitioned: false,
},
sharedHint: {
label: 'cookie shared across subdomains on purpose', prefix: '__Secure-', secure: true, httpOnly: true,
sameSite: ['Lax', 'Strict'], domain: PARENT_DOMAIN, path: '/', lifetime: 'session', partitioned: false,
},
widget: {
label: 'embedded widget cookie (cross-site)', prefix: '__Host-', secure: true, httpOnly: true,
sameSite: ['None'], domain: '', path: '/', lifetime: 'session', partitioned: true,
},
}
// Which kind each cookie is, by its name without a prefix.
export const KIND_BY_BASE_NAME = {
sid: 'session', csrf: 'antiForgery', remember: 'rememberDevice',
theme: 'preference', signed_in: 'sharedHint', widget_session: 'widget',
}
// Splits one Set-Cookie header into its name, value and attributes.
// Attribute names are compared in lower case, as the draft allows any case.
export function parseSetCookie(headerText) {
const parts = headerText.split(';')
const pair = parts.shift()
const equalsAt = pair.indexOf('=')
const cookie = { header: headerText, name: pair.slice(0, equalsAt).trim(), value: pair.slice(equalsAt + 1).trim(), attributes: [] }
for (const part of parts) {
const text = part.trim()
if (!text) continue
const at = text.indexOf('=')
const name = at === -1 ? text : text.slice(0, at)
const value = at === -1 ? '' : text.slice(at + 1)
cookie.attributes.push({ name: name.trim().toLowerCase(), value: value.trim() })
}
return cookie
}
// The draft uses the last attribute with a given name.
function lastAttribute(cookie, name) {
const matches = cookie.attributes.filter(function (attribute) { return attribute.name === name })
return matches.length ? matches.at(-1) : undefined
}
export function hasAttribute(cookie, name) {
return lastAttribute(cookie, name) !== undefined
}
// draft-22 section 5.4: browsers match a prefix case-insensitively.
export function findPrefix(name) {
const lower = name.toLowerCase()
if (lower.startsWith('__host-')) return '__Host-'
if (lower.startsWith('__secure-')) return '__Secure-'
return ''
}
export function baseName(name) {
return name.slice(findPrefix(name).length)
}
export function kindOf(cookie) {
return KIND_BY_BASE_NAME[baseName(cookie.name)]
}
// A leading dot is ignored, and an empty Domain leaves the cookie host-only.
export function readDomain(cookie) {
const attribute = lastAttribute(cookie, 'domain')
if (!attribute) return ''
const value = attribute.value.startsWith('.') ? attribute.value.slice(1) : attribute.value
return value.toLowerCase()
}
export function isHostOnly(cookie) {
return readDomain(cookie) === ''
}
// RFC 6265 section 5.1.4: with no usable Path, the browser uses the
// directory of the request path.
export function defaultPath(requestPath) {
if (!requestPath.startsWith('/')) return '/'
const lastSlash = requestPath.lastIndexOf('/')
return lastSlash === 0 ? '/' : requestPath.slice(0, lastSlash)
}
export function effectivePath(cookie, requestPath) {
const attribute = lastAttribute(cookie, 'path')
if (!attribute || !attribute.value.startsWith('/')) return defaultPath(requestPath)
return attribute.value
}
// Strict, Lax and None are the known values; anything else counts as Default.
export function readSameSite(cookie) {
const attribute = lastAttribute(cookie, 'samesite')
if (!attribute) return 'Default'
const known = ['Strict', 'Lax', 'None']
const match = known.find(function (value) { return value.toLowerCase() === attribute.value.toLowerCase() })
return match || 'Default'
}
export function readMaxAge(cookie) {
const attribute = lastAttribute(cookie, 'max-age')
return attribute ? Number(attribute.value) : undefined
}
export function isExpiredNow(cookie) {
const maxAge = readMaxAge(cookie)
if (maxAge !== undefined) return maxAge <= 0
const expires = lastAttribute(cookie, 'expires')
return expires !== undefined && Date.parse(expires.value) < Date.now()
}
function makeLine(label, sent, expected, matches) {
return { label: label, sent: sent, expected: expected, matches: matches }
}
function presence(isPresent) {
return isPresent ? 'present' : 'absent'
}
function describeLifetime(cookie) {
const maxAge = lastAttribute(cookie, 'max-age')
const expires = lastAttribute(cookie, 'expires')
if (maxAge) return 'Max-Age=' + maxAge.value
if (expires) return 'Expires=' + expires.value
return 'none (session cookie)'
}
function checkLifetime(cookie, wanted) {
const sent = describeLifetime(cookie)
if (wanted === 'session') {
const isSessionCookie = !hasAttribute(cookie, 'max-age') && !hasAttribute(cookie, 'expires')
return makeLine('Lifetime', sent, 'none (session cookie)', isSessionCookie)
}
const maxAge = readMaxAge(cookie)
const withinLimit = maxAge !== undefined && maxAge > 0 && maxAge <= LIFETIME_LIMIT_SECONDS
return makeLine('Lifetime', sent, 'Max-Age, 400 days or less', withinLimit)
}
function describePath(cookie, requestPath) {
const attribute = lastAttribute(cookie, 'path')
if (attribute) return attribute.value
return 'absent, so ' + defaultPath(requestPath)
}
// One line per attribute: what the header sent, what the table expects for
// this kind of cookie, and whether they match.
export function checkAgainstTable(cookie, requestPath) {
const expected = DECISION_TABLE[kindOf(cookie)]
const prefix = findPrefix(cookie.name)
const sameSite = readSameSite(cookie)
const bytes = Buffer.byteLength(cookie.name + cookie.value)
return [
makeLine('Prefix', prefix || 'none', expected.prefix, prefix === expected.prefix),
makeLine('Secure', presence(hasAttribute(cookie, 'secure')), presence(expected.secure), hasAttribute(cookie, 'secure') === expected.secure),
makeLine('HttpOnly', presence(hasAttribute(cookie, 'httponly')), presence(expected.httpOnly), hasAttribute(cookie, 'httponly') === expected.httpOnly),
makeLine('SameSite', sameSite === 'Default' ? 'absent' : sameSite, expected.sameSite.join(' or '), expected.sameSite.includes(sameSite)),
makeLine('Domain', readDomain(cookie) || 'absent (host-only)', expected.domain || 'absent (host-only)', readDomain(cookie) === expected.domain),
makeLine('Path', describePath(cookie, requestPath), expected.path, effectivePath(cookie, requestPath) === expected.path),
checkLifetime(cookie, expected.lifetime),
makeLine('Partitioned', presence(hasAttribute(cookie, 'partitioned')), presence(expected.partitioned), hasAttribute(cookie, 'partitioned') === expected.partitioned),
makeLine('Size', bytes + ' bytes', SIZE_LIMIT_BYTES + ' or fewer', bytes <= SIZE_LIMIT_BYTES),
]
}
function makeRule(text, holds) {
return { text: text, holds: holds }
}
// Rules from the draft's storage model (section 5.7). A browser that follows
// the draft ignores a cookie that breaks one of them.
// context.secureOrigin: the response URL is https.
// context.crossSiteSubresource: the response answers a cross-site request
// that is not a top-level navigation, such as an iframe on another site.
export function checkStorageRules(cookie, context) {
const secure = hasAttribute(cookie, 'secure')
const sameSite = readSameSite(cookie)
const prefix = findPrefix(cookie.name)
const rules = [makeRule('Secure only from an https response (step 13)', !secure || context.secureOrigin)]
if (context.crossSiteSubresource) rules.push(makeRule('SameSite=None on a cross-site subresource response (step 18)', sameSite === 'None'))
if (sameSite === 'None') rules.push(makeRule('SameSite=None comes with Secure (step 19)', secure))
if (prefix === '__Secure-') rules.push(makeRule('__Secure- name has Secure (step 20)', secure))
if (prefix === '__Host-') {
rules.push(makeRule('__Host- name has Secure (step 21)', secure))
rules.push(makeRule('__Host- name has no Domain attribute (step 21)', isHostOnly(cookie)))
rules.push(makeRule('__Host- name has a Path attribute of / (step 21)', hasAttribute(cookie, 'path') && lastAttribute(cookie, 'path').value === '/'))
}
return rules
}
// Section 4.1.3 gives servers the case-sensitive spelling. Browsers accept
// other capitalisations (section 5.4), so this is a rule for the server only.
export function checkPrefixSpelling(cookie) {
const prefix = findPrefix(cookie.name)
if (!prefix) return []
return [makeRule('prefix spelled exactly ' + prefix + ' (section 4.1.3)', cookie.name.startsWith(prefix))]
}
// Partitioned is not in draft-22. MDN's Set-Cookie reference says a
// Partitioned cookie must also be set with Secure.
export function checkPartitionedRule(cookie) {
if (!hasAttribute(cookie, 'partitioned')) return []
return [makeRule('Partitioned comes with Secure (MDN Set-Cookie)', hasAttribute(cookie, 'secure'))]
}
// draft-22 sections 5.1.3 and 5.8.3: a host-only cookie goes only to the host
// that set it; a Domain cookie goes to that domain and every host under it.
export function isInScopeForHost(cookie, setByHost, host) {
if (isHostOnly(cookie)) return host === setByHost
const domain = readDomain(cookie)
return host === domain || host.endsWith('.' + domain)
}
// A sibling host can set a cookie of the same name with Domain=example.com,
// and the browser includes it in requests to the host that set the original
// (draft-22 section 8.6). When the original is host-only, the store keeps
// both, because they differ in domain and host-only flag. When the original
// also has Domain=example.com and the same path, the sibling's cookie
// replaces it (section 5.7, steps 23 and 24).
// A __Host- name cannot carry a Domain attribute (section 4.1.3.2).
export function canSiblingPlantName(cookie) {
return findPrefix(cookie.name) !== '__Host-'
}
// RFC 6265 section 3.1: a server removes a cookie only if the Path and the
// Domain attribute match the values used when the cookie was created.
// draft-22 section 5.7 step 23 replaces a stored cookie only when the name,
// domain, host-only flag and path are all the same.
export function compareClearing(setCookie, setPath, clearCookie, clearPath) {
const result = {
nameMatches: clearCookie.name === setCookie.name,
pathMatches: effectivePath(clearCookie, clearPath) === effectivePath(setCookie, setPath),
domainMatches: readDomain(clearCookie) === readDomain(setCookie),
expired: isExpiredNow(clearCookie),
}
result.clears = result.nameMatches && result.pathMatches && result.domainMatches && result.expired
return result
}
================================================================
FILE 3 OF 5: cookie-flows.mjs
================================================================
// cookie-flows.mjs: sends the requests of the login, logout and cross-site
// flows to one version of the lab site and collects every Set-Cookie header.
// The client connects to 127.0.0.1 over plain http and names the invented
// host in the Host header. Each step also records the https URL it stands
// for, and the checker judges the headers as if they came from that URL.
import { request as httpRequest } from 'node:http'
import { APP_HOST, WIDGET_HOST, startLabSite } from './cookie-lab-site.mjs'
import { baseName, compareClearing, parseSetCookie } from './cookie-rules.mjs'
export const SIBLING_HOSTS = ['app.example.com', 'api.app.example.com', 'shop.example.com', 'blog.example.com', 'example.com']
// The cookies logout is meant to clear, by name without a prefix. The
// remember-this-device cookie stays on purpose: removing a device is a
// separate action.
export const LOGOUT_CLEARS = ['sid', 'csrf', 'signed_in']
const FLOW_STEPS = {
login: [
{ method: 'POST', host: APP_HOST, path: '/account/login', body: 'remember=yes' },
{ method: 'GET', host: APP_HOST, path: '/' },
],
logout: [{ method: 'POST', host: APP_HOST, path: '/account/logout', body: '' }],
crossSite: [{ method: 'GET', host: WIDGET_HOST, path: '/embed', embeddedIn: 'https://partner.example.org/' }],
}
function sendRequest(port, step) {
return new Promise(function (resolve, reject) {
const headers = { Host: step.host }
if (step.body !== undefined) headers['Content-Type'] = 'application/x-www-form-urlencoded'
const options = { host: '127.0.0.1', port: port, method: step.method, path: step.path, headers: headers }
const outgoing = httpRequest(options, function (response) {
response.resume()
// Node.js gives every Set-Cookie header as one entry in an array.
response.on('end', function () { resolve(response.headers['set-cookie'] || []) })
})
outgoing.on('error', reject)
outgoing.end(step.body || '')
})
}
async function runStep(port, step) {
const headerTexts = await sendRequest(port, step)
return {
method: step.method,
path: step.path,
host: step.host,
url: 'https://' + step.host + step.path,
embeddedIn: step.embeddedIn || '',
context: { secureOrigin: true, crossSiteSubresource: Boolean(step.embeddedIn) },
cookies: headerTexts.map(parseSetCookie),
}
}
// Runs every flow against one version and returns the steps by flow name.
export async function collectFlows(versionName) {
const site = await startLabSite(versionName)
const flows = {}
try {
for (const flowName of Object.keys(FLOW_STEPS)) {
flows[flowName] = []
for (const step of FLOW_STEPS[flowName]) flows[flowName].push(await runStep(site.port, step))
}
} finally {
site.server.close()
}
return flows
}
function findByBaseName(steps, name) {
for (const step of steps) {
const cookie = step.cookies.find(function (candidate) { return baseName(candidate.name) === name })
if (cookie) return { cookie: cookie, path: step.path }
}
return undefined
}
// For each cookie logout should clear: how it was set at login, how logout
// cleared it, and whether the clearing header matches.
export function checkLogout(flows) {
return LOGOUT_CLEARS.map(function (name) {
const set = findByBaseName(flows.login, name)
const clear = findByBaseName(flows.logout, name)
if (!set) return { name: name, set: undefined, clear: clear, comparison: undefined }
const comparison = clear ? compareClearing(set.cookie, set.path, clear.cookie, clear.path) : undefined
return { name: name, set: set, clear: clear, comparison: comparison }
})
}
================================================================
FILE 4 OF 5: run-flows.mjs
================================================================
// run-flows.mjs: runs the login, logout, subdomain and cross-site flows
// against the careless version and then the careful version, and prints every
// Set-Cookie header with what the checker found. It reports on header text
// only; what a browser stores is for your browser's developer tools to show.
// Run: node run-flows.mjs
import { APP_HOST } from './cookie-lab-site.mjs'
import { SIBLING_HOSTS, checkLogout, collectFlows } from './cookie-flows.mjs'
import {
DECISION_TABLE, canSiblingPlantName, checkAgainstTable, checkPartitionedRule, checkPrefixSpelling,
checkStorageRules, effectivePath, isInScopeForHost, kindOf, readDomain,
} from './cookie-rules.mjs'
function printTableLines(cookie, requestPath) {
console.log(' ' + 'Attribute'.padEnd(12) + 'Sent'.padEnd(32) + 'Decision table'.padEnd(28) + 'Result')
let differences = 0
for (const line of checkAgainstTable(cookie, requestPath)) {
if (!line.matches) differences++
console.log(' ' + line.label.padEnd(12) + line.sent.padEnd(32) + line.expected.padEnd(28) + (line.matches ? 'ok' : 'DIFFERS'))
}
return differences
}
function printRules(cookie, context) {
const rules = checkStorageRules(cookie, context).concat(checkPartitionedRule(cookie), checkPrefixSpelling(cookie))
console.log(' Rules the header must meet (draft-22 section 5.7 unless named):')
let broken = 0
for (const rule of rules) {
if (!rule.holds) broken++
console.log(' ' + (rule.holds ? 'holds ' : 'BROKEN ') + rule.text)
}
return broken
}
function printCookie(cookie, step, compareWithTable) {
console.log(' Set-Cookie: ' + cookie.header)
let problems = 0
if (compareWithTable) {
console.log(' Kind: ' + DECISION_TABLE[kindOf(cookie)].label)
problems += printTableLines(cookie, step.path)
}
problems += printRules(cookie, step.context)
return problems
}
function printStep(step, compareWithTable) {
const where = step.embeddedIn ? ' (in an iframe on ' + step.embeddedIn + ')' : ''
console.log(step.method + ' ' + step.url + where)
let problems = 0
for (const cookie of step.cookies) problems += printCookie(cookie, step, compareWithTable)
return problems
}
function describeScope(cookie, path) {
return 'Domain ' + (readDomain(cookie) || 'absent (host-only)') + ', Path ' + effectivePath(cookie, path)
}
function printLogoutChecks(flows) {
console.log(' Does each clearing header match the cookie set at login?')
let notCleared = 0
for (const item of checkLogout(flows)) {
console.log(' ' + item.name)
console.log(' set at login: ' + (item.set ? item.set.cookie.name + ', ' + describeScope(item.set.cookie, item.set.path) : 'not set'))
if (!item.clear) {
notCleared++
console.log(' cleared with: no clearing header')
console.log(' Result: NOT CLEARED, nothing in the logout response replaces this cookie')
continue
}
const comparison = item.comparison
console.log(' cleared with: ' + item.clear.cookie.name + ', ' + describeScope(item.clear.cookie, item.clear.path))
console.log(' name ' + yesNo(comparison.nameMatches) + ', Path ' + yesNo(comparison.pathMatches) +
', Domain ' + yesNo(comparison.domainMatches) + ', expiry in the past: ' + (comparison.expired ? 'yes' : 'NO'))
if (!comparison.clears) notCleared++
console.log(' Result: ' + (comparison.clears ? 'clears it' : 'NOT CLEARED, see what DIFFERS above (RFC 6265 section 3.1)'))
}
return notCleared
}
function yesNo(value) {
return value ? 'matches' : 'DIFFERS'
}
function printSubdomainScope(flows) {
console.log('Scope of each login cookie under the draft (sections 5.1.3 and 5.8.3), worked out from the header text:')
let sharedBeyondPlan = 0
for (const step of flows.login) {
for (const cookie of step.cookies) {
const hosts = SIBLING_HOSTS.filter(function (host) { return isInScopeForHost(cookie, APP_HOST, host) })
const isMeantToShare = kindOf(cookie) === 'sharedHint'
if (!isMeantToShare && hosts.length > 1) sharedBeyondPlan++
console.log(' ' + cookie.name)
console.log(' in scope for: ' + hosts.join(', '))
console.log(' a sibling subdomain can set a cookie of this name that ' + APP_HOST + ' receives: ' + (canSiblingPlantName(cookie) ? 'yes' : 'no'))
}
}
return sharedBeyondPlan
}
async function runVersion(versionName) {
const flows = await collectFlows(versionName)
console.log('================ ' + versionName.toUpperCase() + ' VERSION ================')
console.log('')
console.log('FLOW 1: LOGIN')
let problems = 0
for (const step of flows.login) problems += printStep(step, true)
console.log('')
console.log('FLOW 2: LOGOUT')
for (const step of flows.logout) problems += printStep(step, false)
const notCleared = printLogoutChecks(flows)
console.log('')
console.log('FLOW 3: SUBDOMAINS')
const sharedBeyondPlan = printSubdomainScope(flows)
console.log('')
console.log('FLOW 4: CROSS-SITE')
for (const step of flows.crossSite) problems += printStep(step, true)
console.log('')
console.log('SUMMARY FOR THE ' + versionName.toUpperCase() + ' VERSION')
console.log(' Attribute differences and broken rules: ' + problems)
console.log(' Cookies logout does not clear: ' + notCleared)
console.log(' Cookies in scope beyond ' + APP_HOST + ' that are not meant to be shared: ' + sharedBeyondPlan)
console.log('')
}
await runVersion('careless')
await runVersion('careful')
================================================================
FILE 5 OF 5: cookie-flags.test.mjs
================================================================
// cookie-flags.test.mjs: the decision table and the rules as a regression test.
// Run: node cookie-flags.test.mjs (careful version: every test passes)
// node cookie-flags.test.mjs careless (careless version: the flow tests fail)
// The first test checks the checker itself against the specification's own
// examples, so it passes for both versions.
import assert from 'node:assert/strict'
import { before, test } from 'node:test'
import { APP_HOST } from './cookie-lab-site.mjs'
import { SIBLING_HOSTS, checkLogout, collectFlows } from './cookie-flows.mjs'
import {
baseName, checkAgainstTable, checkPartitionedRule, checkPrefixSpelling, checkStorageRules,
isInScopeForHost, kindOf, parseSetCookie,
} from './cookie-rules.mjs'
const versionName = process.argv[2] || 'careful'
// draft-ietf-httpbis-rfc6265bis-22 section 5.4: headers a conforming browser
// rejects, then headers it accepts when they come from a secure origin.
const DRAFT_REJECTED = [
'__Secure-SID=12345; Domain=site.example',
'__secure-SID=12345; Domain=site.example',
'__SECURE-SID=12345; Domain=site.example',
'__Host-SID=12345',
'__host-SID=12345; Secure',
'__host-SID=12345; Domain=site.example',
'__HOST-SID=12345; Domain=site.example; Path=/',
'__Host-SID=12345; Secure; Domain=site.example; Path=/',
'__host-SID=12345; Secure; Domain=site.example; Path=/',
'__HOST-SID=12345; Secure; Domain=site.example; Path=/',
]
const DRAFT_ACCEPTED = [
'__Secure-SID=12345; Domain=site.example; Secure',
'__secure-SID=12345; Domain=site.example; Secure',
'__SECURE-SID=12345; Domain=site.example; Secure',
'__Host-SID=12345; Secure; Path=/',
'__host-SID=12345; Secure; Path=/',
'__HOST-SID=12345; Secure; Path=/',
]
const SECURE_ORIGIN = { secureOrigin: true, crossSiteSubresource: false }
let flows
before(async function () {
flows = await collectFlows(versionName)
})
function wouldBeStored(headerText) {
return checkStorageRules(parseSetCookie(headerText), SECURE_ORIGIN).every(function (rule) { return rule.holds })
}
// The attributes that differ from the decision table, as "Label: sent".
function listDifferences(cookie, requestPath) {
return checkAgainstTable(cookie, requestPath)
.filter(function (line) { return !line.matches })
.map(function (line) { return line.label + ': ' + line.sent })
}
function listBrokenRules(cookie, context) {
return checkStorageRules(cookie, context).concat(checkPartitionedRule(cookie), checkPrefixSpelling(cookie))
.filter(function (rule) { return !rule.holds })
.map(function (rule) { return rule.text })
}
function findCookie(steps, kind) {
for (const step of steps) {
const cookie = step.cookies.find(function (candidate) { return kindOf(candidate) === kind })
if (cookie) return { cookie: cookie, step: step }
}
throw new Error('No ' + kind + ' cookie was set')
}
function assertMatchesTable(steps, kind) {
const found = findCookie(steps, kind)
assert.deepEqual(listDifferences(found.cookie, found.step.path), [], found.cookie.header)
assert.deepEqual(listBrokenRules(found.cookie, found.step.context), [], found.cookie.header)
}
test('checker: prefix rules agree with the 16 examples in draft-22 section 5.4', function () {
for (const header of DRAFT_REJECTED) assert.equal(wouldBeStored(header), false, header)
for (const header of DRAFT_ACCEPTED) assert.equal(wouldBeStored(header), true, header)
})
test('login: the session cookie matches the decision table', function () {
assertMatchesTable(flows.login, 'session')
})
test('login: the anti-forgery token cookie matches the decision table', function () {
assertMatchesTable(flows.login, 'antiForgery')
})
test('login: the remember-this-device cookie matches the decision table', function () {
assertMatchesTable(flows.login, 'rememberDevice')
})
test('login: the preference cookie matches the decision table', function () {
assertMatchesTable(flows.login, 'preference')
})
test('login: the cookie shared across subdomains matches the decision table', function () {
assertMatchesTable(flows.login, 'sharedHint')
})
test('logout: each clearing header matches the name, Path and Domain the cookie was set with', function () {
const notCleared = checkLogout(flows)
.filter(function (item) { return !item.comparison || !item.comparison.clears })
.map(function (item) { return item.name })
assert.deepEqual(notCleared, [])
for (const step of flows.logout) {
for (const cookie of step.cookies) assert.deepEqual(listBrokenRules(cookie, step.context), [], cookie.header)
}
})
test('subdomains: only the cookie meant for sharing reaches hosts other than ' + APP_HOST, function () {
const sharedBeyondPlan = []
for (const step of flows.login) {
for (const cookie of step.cookies) {
if (kindOf(cookie) === 'sharedHint') continue
const otherHosts = SIBLING_HOSTS.filter(function (host) { return host !== APP_HOST && isInScopeForHost(cookie, APP_HOST, host) })
if (otherHosts.length) sharedBeyondPlan.push(baseName(cookie.name))
}
}
assert.deepEqual(sharedBeyondPlan, [])
})
test('cross-site: the embedded widget cookie matches the decision table', function () {
assertMatchesTable(flows.crossSite, 'widget')
})
================================================================
PART 3: RUN THE FOUR FLOWS AGAINST BOTH VERSIONS
================================================================
Command: node run-flows.mjs
================ CARELESS VERSION ================
FLOW 1: LOGIN
POST https://app.example.com/account/login
Set-Cookie: sid=e1227d0fbd0ca9c383e67c09a63850cd; Domain=example.com; HttpOnly
Kind: session cookie
Attribute Sent Decision table Result
Prefix none __Host- DIFFERS
Secure absent present DIFFERS
HttpOnly present present ok
SameSite absent Strict or Lax DIFFERS
Domain example.com absent (host-only) DIFFERS
Path absent, so /account / DIFFERS
Lifetime none (session cookie) none (session cookie) ok
Partitioned absent absent ok
Size 35 bytes 4096 or fewer ok
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
Set-Cookie: csrf=59bbcfe6407187442bc9876c2f4342b0
Kind: anti-forgery token cookie
Attribute Sent Decision table Result
Prefix none __Host- DIFFERS
Secure absent present DIFFERS
HttpOnly absent present DIFFERS
SameSite absent Strict or Lax DIFFERS
Domain absent (host-only) absent (host-only) ok
Path absent, so /account / DIFFERS
Lifetime none (session cookie) none (session cookie) ok
Partitioned absent absent ok
Size 36 bytes 4096 or fewer ok
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
Set-Cookie: remember=734b70765c80e85d725f98eaa31bfc28; Max-Age=315360000
Kind: remember-this-device cookie
Attribute Sent Decision table Result
Prefix none __Host- DIFFERS
Secure absent present DIFFERS
HttpOnly absent present DIFFERS
SameSite absent Strict DIFFERS
Domain absent (host-only) absent (host-only) ok
Path absent, so /account / DIFFERS
Lifetime Max-Age=315360000 Max-Age, 400 days or less DIFFERS
Partitioned absent absent ok
Size 40 bytes 4096 or fewer ok
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
Set-Cookie: signed_in=yes; Domain=example.com
Kind: cookie shared across subdomains on purpose
Attribute Sent Decision table Result
Prefix none __Secure- DIFFERS
Secure absent present DIFFERS
HttpOnly absent present DIFFERS
SameSite absent Lax or Strict DIFFERS
Domain example.com example.com ok
Path absent, so /account / DIFFERS
Lifetime none (session cookie) none (session cookie) ok
Partitioned absent absent ok
Size 12 bytes 4096 or fewer ok
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
GET https://app.example.com/
Set-Cookie: theme=dark
Kind: preference cookie that script reads
Attribute Sent Decision table Result
Prefix none __Host- DIFFERS
Secure absent present DIFFERS
HttpOnly absent absent ok
SameSite absent Lax DIFFERS
Domain absent (host-only) absent (host-only) ok
Path absent, so / / ok
Lifetime none (session cookie) Max-Age, 400 days or less DIFFERS
Partitioned absent absent ok
Size 9 bytes 4096 or fewer ok
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
FLOW 2: LOGOUT
POST https://app.example.com/account/logout
Set-Cookie: sid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
Set-Cookie: signed_in=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
Does each clearing header match the cookie set at login?
sid
set at login: sid, Domain example.com, Path /account
cleared with: sid, Domain absent (host-only), Path /
name matches, Path DIFFERS, Domain DIFFERS, expiry in the past: yes
Result: NOT CLEARED, see what DIFFERS above (RFC 6265 section 3.1)
csrf
set at login: csrf, Domain absent (host-only), Path /account
cleared with: no clearing header
Result: NOT CLEARED, nothing in the logout response replaces this cookie
signed_in
set at login: signed_in, Domain example.com, Path /account
cleared with: signed_in, Domain absent (host-only), Path /
name matches, Path DIFFERS, Domain DIFFERS, expiry in the past: yes
Result: NOT CLEARED, see what DIFFERS above (RFC 6265 section 3.1)
FLOW 3: SUBDOMAINS
Scope of each login cookie under the draft (sections 5.1.3 and 5.8.3), worked out from the header text:
sid
in scope for: app.example.com, api.app.example.com, shop.example.com, blog.example.com, example.com
a sibling subdomain can set a cookie of this name that app.example.com receives: yes
csrf
in scope for: app.example.com
a sibling subdomain can set a cookie of this name that app.example.com receives: yes
remember
in scope for: app.example.com
a sibling subdomain can set a cookie of this name that app.example.com receives: yes
signed_in
in scope for: app.example.com, api.app.example.com, shop.example.com, blog.example.com, example.com
a sibling subdomain can set a cookie of this name that app.example.com receives: yes
theme
in scope for: app.example.com
a sibling subdomain can set a cookie of this name that app.example.com receives: yes
FLOW 4: CROSS-SITE
GET https://widget.example.net/embed (in an iframe on https://partner.example.org/)
Set-Cookie: widget_session=78faaab325e07bf3e8dc5e3b94d92fdb; SameSite=None
Kind: embedded widget cookie (cross-site)
Attribute Sent Decision table Result
Prefix none __Host- DIFFERS
Secure absent present DIFFERS
HttpOnly absent present DIFFERS
SameSite None None ok
Domain absent (host-only) absent (host-only) ok
Path absent, so / / ok
Lifetime none (session cookie) none (session cookie) ok
Partitioned absent present DIFFERS
Size 46 bytes 4096 or fewer ok
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
holds SameSite=None on a cross-site subresource response (step 18)
BROKEN SameSite=None comes with Secure (step 19)
SUMMARY FOR THE CARELESS VERSION
Attribute differences and broken rules: 30
Cookies logout does not clear: 3
Cookies in scope beyond app.example.com that are not meant to be shared: 1
================ CAREFUL VERSION ================
FLOW 1: LOGIN
POST https://app.example.com/account/login
Set-Cookie: __Host-sid=55938e2b041bdaa010281e397dff324f; Path=/; Secure; HttpOnly; SameSite=Lax
Kind: session cookie
Attribute Sent Decision table Result
Prefix __Host- __Host- ok
Secure present present ok
HttpOnly present present ok
SameSite Lax Strict or Lax ok
Domain absent (host-only) absent (host-only) ok
Path / / ok
Lifetime none (session cookie) none (session cookie) ok
Partitioned absent absent ok
Size 42 bytes 4096 or fewer ok
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
holds __Host- name has Secure (step 21)
holds __Host- name has no Domain attribute (step 21)
holds __Host- name has a Path attribute of / (step 21)
holds prefix spelled exactly __Host- (section 4.1.3)
Set-Cookie: __Host-csrf=6cb500ab887c38a44f6a41677a89393a; Path=/; Secure; HttpOnly; SameSite=Strict
Kind: anti-forgery token cookie
Attribute Sent Decision table Result
Prefix __Host- __Host- ok
Secure present present ok
HttpOnly present present ok
SameSite Strict Strict or Lax ok
Domain absent (host-only) absent (host-only) ok
Path / / ok
Lifetime none (session cookie) none (session cookie) ok
Partitioned absent absent ok
Size 43 bytes 4096 or fewer ok
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
holds __Host- name has Secure (step 21)
holds __Host- name has no Domain attribute (step 21)
holds __Host- name has a Path attribute of / (step 21)
holds prefix spelled exactly __Host- (section 4.1.3)
Set-Cookie: __Host-remember=88d937c5df053147ca95a9f009a42ec7; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=2592000
Kind: remember-this-device cookie
Attribute Sent Decision table Result
Prefix __Host- __Host- ok
Secure present present ok
HttpOnly present present ok
SameSite Strict Strict ok
Domain absent (host-only) absent (host-only) ok
Path / / ok
Lifetime Max-Age=2592000 Max-Age, 400 days or less ok
Partitioned absent absent ok
Size 47 bytes 4096 or fewer ok
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
holds __Host- name has Secure (step 21)
holds __Host- name has no Domain attribute (step 21)
holds __Host- name has a Path attribute of / (step 21)
holds prefix spelled exactly __Host- (section 4.1.3)
Set-Cookie: __Secure-signed_in=yes; Domain=example.com; Path=/; Secure; HttpOnly; SameSite=Lax
Kind: cookie shared across subdomains on purpose
Attribute Sent Decision table Result
Prefix __Secure- __Secure- ok
Secure present present ok
HttpOnly present present ok
SameSite Lax Lax or Strict ok
Domain example.com example.com ok
Path / / ok
Lifetime none (session cookie) none (session cookie) ok
Partitioned absent absent ok
Size 21 bytes 4096 or fewer ok
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
holds __Secure- name has Secure (step 20)
holds prefix spelled exactly __Secure- (section 4.1.3)
GET https://app.example.com/
Set-Cookie: __Host-theme=dark; Path=/; Secure; SameSite=Lax; Max-Age=31536000
Kind: preference cookie that script reads
Attribute Sent Decision table Result
Prefix __Host- __Host- ok
Secure present present ok
HttpOnly absent absent ok
SameSite Lax Lax ok
Domain absent (host-only) absent (host-only) ok
Path / / ok
Lifetime Max-Age=31536000 Max-Age, 400 days or less ok
Partitioned absent absent ok
Size 16 bytes 4096 or fewer ok
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
holds __Host- name has Secure (step 21)
holds __Host- name has no Domain attribute (step 21)
holds __Host- name has a Path attribute of / (step 21)
holds prefix spelled exactly __Host- (section 4.1.3)
FLOW 2: LOGOUT
POST https://app.example.com/account/logout
Set-Cookie: __Host-sid=; Path=/; Secure; HttpOnly; SameSite=Lax; Expires=Thu, 01 Jan 1970 00:00:00 GMT
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
holds __Host- name has Secure (step 21)
holds __Host- name has no Domain attribute (step 21)
holds __Host- name has a Path attribute of / (step 21)
holds prefix spelled exactly __Host- (section 4.1.3)
Set-Cookie: __Host-csrf=; Path=/; Secure; HttpOnly; SameSite=Strict; Expires=Thu, 01 Jan 1970 00:00:00 GMT
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
holds __Host- name has Secure (step 21)
holds __Host- name has no Domain attribute (step 21)
holds __Host- name has a Path attribute of / (step 21)
holds prefix spelled exactly __Host- (section 4.1.3)
Set-Cookie: __Secure-signed_in=; Domain=example.com; Path=/; Secure; HttpOnly; SameSite=Lax; Expires=Thu, 01 Jan 1970 00:00:00 GMT
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
holds __Secure- name has Secure (step 20)
holds prefix spelled exactly __Secure- (section 4.1.3)
Does each clearing header match the cookie set at login?
sid
set at login: __Host-sid, Domain absent (host-only), Path /
cleared with: __Host-sid, Domain absent (host-only), Path /
name matches, Path matches, Domain matches, expiry in the past: yes
Result: clears it
csrf
set at login: __Host-csrf, Domain absent (host-only), Path /
cleared with: __Host-csrf, Domain absent (host-only), Path /
name matches, Path matches, Domain matches, expiry in the past: yes
Result: clears it
signed_in
set at login: __Secure-signed_in, Domain example.com, Path /
cleared with: __Secure-signed_in, Domain example.com, Path /
name matches, Path matches, Domain matches, expiry in the past: yes
Result: clears it
FLOW 3: SUBDOMAINS
Scope of each login cookie under the draft (sections 5.1.3 and 5.8.3), worked out from the header text:
__Host-sid
in scope for: app.example.com
a sibling subdomain can set a cookie of this name that app.example.com receives: no
__Host-csrf
in scope for: app.example.com
a sibling subdomain can set a cookie of this name that app.example.com receives: no
__Host-remember
in scope for: app.example.com
a sibling subdomain can set a cookie of this name that app.example.com receives: no
__Secure-signed_in
in scope for: app.example.com, api.app.example.com, shop.example.com, blog.example.com, example.com
a sibling subdomain can set a cookie of this name that app.example.com receives: yes
__Host-theme
in scope for: app.example.com
a sibling subdomain can set a cookie of this name that app.example.com receives: no
FLOW 4: CROSS-SITE
GET https://widget.example.net/embed (in an iframe on https://partner.example.org/)
Set-Cookie: __Host-widget_session=83587c52d408b97d5d542f2a65446e63; Path=/; Secure; HttpOnly; SameSite=None; Partitioned
Kind: embedded widget cookie (cross-site)
Attribute Sent Decision table Result
Prefix __Host- __Host- ok
Secure present present ok
HttpOnly present present ok
SameSite None None ok
Domain absent (host-only) absent (host-only) ok
Path / / ok
Lifetime none (session cookie) none (session cookie) ok
Partitioned present present ok
Size 53 bytes 4096 or fewer ok
Rules the header must meet (draft-22 section 5.7 unless named):
holds Secure only from an https response (step 13)
holds SameSite=None on a cross-site subresource response (step 18)
holds SameSite=None comes with Secure (step 19)
holds __Host- name has Secure (step 21)
holds __Host- name has no Domain attribute (step 21)
holds __Host- name has a Path attribute of / (step 21)
holds Partitioned comes with Secure (MDN Set-Cookie)
holds prefix spelled exactly __Host- (section 4.1.3)
SUMMARY FOR THE CAREFUL VERSION
Attribute differences and broken rules: 0
Cookies logout does not clear: 0
Cookies in scope beyond app.example.com that are not meant to be shared: 0
Reading the evidence:
Login Every careless cookie differs from its row. The session cookie has no prefix, no Secure and no SameSite, and carries Domain=example.com. Cookies set from /account/login without a Path get /account, the directory of that URL. The remember cookie asks for 315360000 seconds, past the 400-day limit cookie draft 5.5 recommends to browsers. In the careful version every line matches and every rule holds.
Logout The careless sign-out clears sid and signed_in with Path=/ and no Domain, while login set them with Domain=example.com and a Path of /account, so neither header matches, and it sends nothing for csrf. RFC 6265 says a server removes a cookie only if the Path and Domain match the values used when it was created. The careful clearing headers repeat the name, Path and Domain, and still meet the __Host- and __Secure- rules.
Subdomains The careless session cookie is in scope for every host under example.com, worked out from its header with the draft's domain-match rule. In the careful version only the hint meant for sharing reaches beyond app.example.com, and, in a browser that supports prefixes, no sibling subdomain can set a cookie that app.example.com would receive under a __Host- name (cookie draft 4.1.3.2). Where the line about a sibling subdomain says yes, the sibling's cookie is kept beside an original that is host-only, because the two differ in domain and host-only flag, and replaces an original that has Domain=example.com and the same path (cookie draft 5.7, steps 23 and 24).
Cross-site The careless widget cookie sets SameSite=None without Secure, which a browser that follows the draft ignores (section 5.7, step 19). The careful one meets every rule. Whether a browser then stores and sends it in a third-party frame also depends on that browser's third-party cookie handling, which Part 5 shows you how to check.
================================================================
PART 4: THE REGRESSION TEST
================================================================
The first test checks the checker itself against the 16 example headers in cookie draft section 5.4, so it passes for both versions. Each other test covers one cookie or one flow and names the attributes that differ when it fails.
Command: node cookie-flags.test.mjs
✔ checker: prefix rules agree with the 16 examples in draft-22 section 5.4 (11.628791ms)
✔ login: the session cookie matches the decision table (0.751125ms)
✔ login: the anti-forgery token cookie matches the decision table (0.075916ms)
✔ login: the remember-this-device cookie matches the decision table (0.081292ms)
✔ login: the preference cookie matches the decision table (0.070334ms)
✔ login: the cookie shared across subdomains matches the decision table (0.067584ms)
✔ logout: each clearing header matches the name, Path and Domain the cookie was set with (0.163ms)
✔ subdomains: only the cookie meant for sharing reaches hosts other than app.example.com (0.085958ms)
✔ cross-site: the embedded widget cookie matches the decision table (0.080542ms)
ℹ tests 9
ℹ suites 0
ℹ pass 9
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 17.695458
The process exits with code 0.
Command: node cookie-flags.test.mjs careless
✔ checker: prefix rules agree with the 16 examples in draft-22 section 5.4 (11.979667ms)
✖ login: the session cookie matches the decision table (1.853125ms)
✖ login: the anti-forgery token cookie matches the decision table (0.137667ms)
✖ login: the remember-this-device cookie matches the decision table (0.138375ms)
✖ login: the preference cookie matches the decision table (0.107541ms)
✖ login: the cookie shared across subdomains matches the decision table (0.094375ms)
✖ logout: each clearing header matches the name, Path and Domain the cookie was set with (0.182375ms)
✖ subdomains: only the cookie meant for sharing reaches hosts other than app.example.com (0.113125ms)
✖ cross-site: the embedded widget cookie matches the decision table (0.122583ms)
ℹ tests 9
ℹ suites 0
ℹ pass 1
ℹ fail 8
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 19.6475
✖ failing tests:
test at cookie-flags.test.mjs:83:1
✖ login: the session cookie matches the decision table (1.853125ms)
AssertionError [ERR_ASSERTION]: sid=d04027c45e0dc790b57ad73d40feb563; Domain=example.com; HttpOnly
+ actual - expected
+ [
+ 'Prefix: none',
+ 'Secure: absent',
+ 'SameSite: absent',
+ 'Domain: example.com',
+ 'Path: absent, so /account'
+ ]
- []
(stack trace and error object lines removed here)
test at cookie-flags.test.mjs:87:1
✖ login: the anti-forgery token cookie matches the decision table (0.137667ms)
AssertionError [ERR_ASSERTION]: csrf=37c485a40e4c1b9647427533b9e416a1
+ actual - expected
+ [
+ 'Prefix: none',
+ 'Secure: absent',
+ 'HttpOnly: absent',
+ 'SameSite: absent',
+ 'Path: absent, so /account'
+ ]
- []
(stack trace and error object lines removed here)
test at cookie-flags.test.mjs:91:1
✖ login: the remember-this-device cookie matches the decision table (0.138375ms)
AssertionError [ERR_ASSERTION]: remember=4588ee31b82a689fdbc2fd2444bd085e; Max-Age=315360000
+ actual - expected
+ [
+ 'Prefix: none',
+ 'Secure: absent',
+ 'HttpOnly: absent',
+ 'SameSite: absent',
+ 'Path: absent, so /account',
+ 'Lifetime: Max-Age=315360000'
+ ]
- []
(stack trace and error object lines removed here)
test at cookie-flags.test.mjs:95:1
✖ login: the preference cookie matches the decision table (0.107541ms)
AssertionError [ERR_ASSERTION]: theme=dark
+ actual - expected
+ [
+ 'Prefix: none',
+ 'Secure: absent',
+ 'SameSite: absent',
+ 'Lifetime: none (session cookie)'
+ ]
- []
(stack trace and error object lines removed here)
test at cookie-flags.test.mjs:99:1
✖ login: the cookie shared across subdomains matches the decision table (0.094375ms)
AssertionError [ERR_ASSERTION]: signed_in=yes; Domain=example.com
+ actual - expected
+ [
+ 'Prefix: none',
+ 'Secure: absent',
+ 'HttpOnly: absent',
+ 'SameSite: absent',
+ 'Path: absent, so /account'
+ ]
- []
(stack trace and error object lines removed here)
test at cookie-flags.test.mjs:103:1
✖ logout: each clearing header matches the name, Path and Domain the cookie was set with (0.182375ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
+ [
+ 'sid',
+ 'csrf',
+ 'signed_in'
+ ]
- []
(stack trace and error object lines removed here)
test at cookie-flags.test.mjs:113:1
✖ subdomains: only the cookie meant for sharing reaches hosts other than app.example.com (0.113125ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
+ [
+ 'sid'
+ ]
- []
(stack trace and error object lines removed here)
test at cookie-flags.test.mjs:125:1
✖ cross-site: the embedded widget cookie matches the decision table (0.122583ms)
AssertionError [ERR_ASSERTION]: widget_session=c73c99622c2157d52658b2201bdfbec9; SameSite=None
+ actual - expected
+ [
+ 'Prefix: none',
+ 'Secure: absent',
+ 'HttpOnly: absent',
+ 'Partitioned: absent'
+ ]
- []
(stack trace and error object lines removed here)
The process exits with code 1, so a pipeline step running the test fails.
================================================================
PART 5: CHECK WHAT YOUR OWN BROWSER STORES AND SENDS
The checker cannot do this part. Use a staging or local copy of your own site, a test account, and your browser's developer tools. MDN's cookies guide names the Storage Inspector in Firefox Developer Tools and the Application panel in Chrome Developer Tools for seeing stored cookies; the Network panel shows each request's Cookie header and each response's Set-Cookie headers.
Login
1. Clear your site's cookies, open the developer tools and sign in. Select the sign-in response in the Network panel, copy each Set-Cookie header and compare it with its row in Part 1.
2. Open the stored cookies view and find each cookie. Compare the Domain, Path, expiry, HttpOnly, Secure and SameSite shown there with the header you copied. If a cookie from a header is not stored, check the header against the rules at the end of Part 1, then your browser's cookie settings.
3. Load a page that needs the session, select that request, and confirm its Cookie header carries the session cookie.
Logout
4. Sign out and select the sign-out response. For each cookie it should clear, the Set-Cookie header should carry the same name, Path and Domain the cookie was set with, and an expiry in the past.
5. Open the stored cookies view again. Each cleared cookie should be gone. One still listed with its old value was not matched by the clearing header.
6. Clearing the cookie is the browser half of sign-out. Whether the server still accepts the old value is a separate check, covered in the session management guide.
Subdomains
7. In the stored cookies view, note the Domain each of your cookies shows.
8. Open a page on a sibling subdomain you run, such as your shop or blog, select its request in the Network panel and read the Cookie header. Only cookies you set with a Domain attribute on purpose should be in it.
9. If a cookie set without a Domain attribute reaches a subdomain, record the browser and its version: RFC 6265 warns that some user agents treat an absent Domain attribute as if it named the current host.
Cross-site
10. Embed your widget in a test page on another site you control and open that page. Select the widget's responses in the Network panel and check the widget cookie's Set-Cookie header against row 6.
11. Check the stored cookies view for the widget's host, then select a later request the widget makes and see whether its Cookie header carries the cookie.
12. Repeat steps 10 and 11 in each browser your visitors use, with its default settings. The cookie draft says most user agents now limit third-party cookies in a variety of ways. Where a browser does not store the cookie, or stores it and does not send it, record the browser, its version and its third-party cookie setting.
Your browser is the evidence in this part. Write down what it showed, not what the table expects.
================================================================
PART 6: POINT THE TEST AT YOUR OWN SITE
1. Copy cookie-rules.mjs, cookie-flows.mjs and cookie-flags.test.mjs into your project's tests.
2. In cookie-flows.mjs, replace the lab site with a staging or local copy of your own: sign in with a test account, load a page, sign out, and load your widget's embed address, keeping each response's Set-Cookie headers and the request path.
3. In cookie-rules.mjs, map each of your cookie names to a row in KIND_BY_BASE_NAME, and change DECISION_TABLE only where your decision differs from Part 1, with the reason written beside the change.
4. In cookie-flows.mjs, list the cookies your sign-out should clear in LOGOUT_CLEARS.
5. Run the test in the pipeline that deploys your site. When a test fails, Node's test runner sets the exit code to 1, so the step fails.
6. Run it only against systems you own or are authorised in writing to test.
================================================================
PART 7: A COOKIE REGISTER TO KEEP
One entry per cookie your site sets, including cookies your own script sets and cookies set by third-party code on your pages. Keep it next to the code and update it when a cookie changes. The OWASP session sheet asks you to define all cookies the application uses, their name and why they are needed.
Name:
Set by (host and path, or the script that sets it):
Owner (your code, your framework, or a named third party):
Purpose, in one sentence:
Row of the decision table it follows:
Header as sent, with the value removed:
Read by (server, your script, or both):
Hosts it is meant to reach:
Lifetime:
Cleared by (sign-out, a settings change, or nothing):
Holds personal or sensitive data (no, or what):
Listed in the privacy notice (yes or no):
Last checked (date, and by whom):
Example entry, from the lab's careful version:
Name: __Host-sid
Set by: app.example.com, POST /account/login
Owner: our code
Purpose: identifies the signed-in session
Row of the decision table: row 1, session cookie
Header as sent: __Host-sid=(value removed); Path=/; Secure; HttpOnly; SameSite=Lax
Read by: server
Hosts it is meant to reach: app.example.com only
Lifetime: session cookie, no Expires or Max-Age
Cleared by: sign-out, with the same name and Path=/
Holds personal or sensitive data: no, a random value with the session data on the server
Listed in the privacy notice: yes
Last checked: the date of your own checkWhat each attribute narrows, and why the defaults are not the safe choice
Each attribute narrows one thing about a cookie.
Read together, they answer five questions.
- Who can read it. HttpOnly forbids page script from reading the cookie (MDN Set-Cookie). Without it, script on the page can read and change it.
- Over what connection. Secure limits the cookie to secure channels, typically HTTPS (RFC 6265 4.1.2.5).
- To which hosts. Domain widens the cookie from the one host that set it to a whole domain and its subdomains (RFC 6265 4.1.2.3).
- To which paths. Path limits the cookie to URLs at or below a path, as a matter of scope rather than security (RFC 6265 4.1.2.4).
- For how long. Expires gives a date and Max-Age a number of seconds; with neither, the browser keeps the cookie until the current session is over, as the browser defines it (RFC 6265 4.1.2.1 and 4.1.2.2).
- In which cross-site situations. SameSite decides whether the cookie goes with cross-site requests (cookie draft 4.1.2.7), and Partitioned asks the browser to store it separately for each top-level site your content is embedded in (MDN Set-Cookie; MDN CHIPS).
Why leaving attributes out is not the safe choice for a session cookie
Leaving an attribute out does not give you the cautious setting across the board. Two defaults are narrow. With no Domain the cookie goes only to the host that set it, and with no Path it is limited to the directory of the URL that set it (RFC 6265 4.1.2.3 and 4.1.2.4).
The others are wide. With no Secure the cookie travels over plain HTTP as well as HTTPS. With no HttpOnly, script can read it.
With no SameSite the result depends on the browser: MDN says some browsers use Lax as the default value, and the CSRF guide sets out how they differ.
The cookie draft puts the principle in its security considerations: by default, cookies provide neither confidentiality nor integrity against network attackers, even when used with HTTPS, so a cookie needs to state any protective attribute explicitly. Its example is a cookie set as a=b with no Secure attribute, which is therefore accessible on both secure and insecure connections, whatever connection it was created on (cookie draft 8.1).
RFC 6750, the OAuth bearer token standard, says bearer tokens must not be stored in cookies that can be sent in the clear, and calls that the default transmission mode for cookies.
A session cookie needs the same care: the OWASP Session Management Cheat Sheet says that once a session is authenticated, its ID is temporarily equivalent to the strongest authentication method the application uses.
So for a session cookie, every attribute that is wide by default has to be set on purpose, and the narrow defaults are worth keeping.
Secure: keeping the cookie off plain HTTP
RFC 6265 says a cookie with the Secure attribute is included in a request only if the request is transmitted over a secure channel, typically HTTPS, and the cookie draft keeps that wording.
MDN adds that sites on plain http: cannot set cookies with Secure, and that a Secure cookie is never sent with unsecured HTTP except on localhost, an exception its cookies guide says is not supported by Safari.
Serving the site over HTTPS only is not a substitute for the attribute. The OWASP Session Management Cheat Sheet explains that forcing a site to use only HTTPS, even with plain HTTP closed on the server, does not protect against session ID disclosure if the session cookie lacks Secure: the browser can be deceived into disclosing the session ID over an unencrypted HTTP connection, because an attacker who can intercept and manipulate the victim's traffic can inject an unencrypted HTTP reference to the site that forces the browser to submit the session ID in the clear.
The cookie draft's webmail example makes the same point: the browser includes the cookies in the redirected plain-HTTP request even if the server is not listening for HTTP connections, and the attacker can intercept and replay them.
It concludes that if a server does not set Secure, the protection provided by the secure channel will be largely moot (cookie draft 8.3).
What Secure does not do matters as much. RFC 6265 says it protects only the cookie's confidentiality: an active network attacker can overwrite Secure cookies from an insecure channel, disrupting their integrity. The cookie draft narrows that gap for browsers that follow it. A response over an insecure connection cannot set a Secure cookie, and cannot set a non-Secure cookie that would overlay an existing Secure cookie of the same name, which the draft describes as some mitigation against cookie-fixing attacks (cookie draft 5.7, steps 13 and 16).
MDN also warns not to assume Secure prevents all access: someone with access to the client's hard disk, or script on the page when HttpOnly is not set, can still read and change the cookie.
For whole-domain transport rules, HSTS is the companion control, and the Domain section below says when the sources require it.
HttpOnly: keeping the cookie away from page script
RFC 6265 says HttpOnly limits the cookie to HTTP requests: it tells the browser to leave the cookie out when giving cookies to non-HTTP APIs, such as a browser API that exposes cookies to scripts.
It is independent of Secure, so a cookie can carry both. What HttpOnly means when script is injected, and what it does not stop, is covered in the XSS guide.
The cookie draft gives it a second job. A browser that follows the draft ignores an HttpOnly cookie that script tries to create, and ignores a cookie from script that would replace a stored HttpOnly cookie with the same name, domain, host-only flag and path (cookie draft 5.7, steps 15 and 23). So HttpOnly also keeps page script from overwriting the cookie.
ASVS 5.0 requirement 3.3.4, at Level 2, asks for more than the flag. A cookie whose value is not meant for client-side script, such as a session token, must have HttpOnly set, and the same value must only reach the browser through the Set-Cookie header.
A session token that also comes back in a JSON body, or is written into the page, does not meet the requirement, whatever flags the cookie carries.
Leave HttpOnly off only for a cookie your own script has to read, such as a theme choice, and keep such a cookie free of anything sensitive. ASVS 5.0 requirement 14.3.3, at Level 2, asks that data in browser storage, cookies included, contains no sensitive data apart from session tokens.
SameSite in brief: which cross-site requests carry the cookie
SameSite controls whether a cookie goes with cross-site requests.
With Strict it goes only with same-site requests, with Lax it also goes with cross-site top-level navigations that use a safe method, and with None it goes with both (cookie draft 4.1.2.7 and 5.6.7.1). MDN says None also needs the Secure attribute, and a browser that follows the draft ignores a None cookie without it (cookie draft 5.7, step 19).
How SameSite behaves against forged requests, what counts as the same site, and how browsers treat a cookie with no SameSite value are the CSRF guide's subject.
Two rules from the standards are enough to choose a value. ASVS 5.0 requirement 3.3.2, at Level 2, asks that each cookie's SameSite value is set according to the purpose of the cookie. The OWASP Session Management Cheat Sheet says session cookies must set Strict, which it prefers, or Lax explicitly, and must not rely on the browser default, which it says varies across browsers and versions. The decision table applies both rules, cookie by cookie.
SameSite also limits where a cookie can be set, not only where it is sent. The cookie draft says cookies that assert Lax or Strict cannot be set in responses to cross-site subresource requests or cross-site nested navigations, though they can be set on any top-level navigation (cookie draft 4.1.2.7).
That is why a widget inside another site's page needs None. The draft says content intended for embedding in cross-site contexts will not have access to same-site cookies, and that cookies required in those situations should be marked None (cookie draft 8.8.3).
Domain: why leaving it out is narrower than setting it
The Domain attribute names the hosts a cookie goes to.
RFC 6265's example: with Domain=example.com, the browser includes the cookie in requests to example.com, www.example.com and www.corp.example.com. If the server leaves the attribute out, the browser returns the cookie only to the origin server. MDN calls that a host-only cookie and says it is more restrictive than setting the host name, because the cookie is not made available to subdomains of the host.
Setting Domain=app.example.com from app.example.com therefore widens the cookie to every host under app.example.com, while leaving it out keeps the cookie on app.example.com alone.
A server can name only its own domain or a parent of it. MDN's example: a response from api.example.com can set Domain=api.example.com or Domain=example.com, but not Domain=beta.api.example.com, Domain=other.example.com or Domain=com, because a public suffix is not allowed either, and cookies that break these rules are ignored.
A leading dot, as in .example.com, is ignored. RFC 6265 carries a warning that the cookie draft repeats: some existing user agents treat an absent Domain attribute as if it named the current host, and would send a cookie set by example.com to www.example.com as well. Part 5 of the asset shows how to see what your own browser does.
A wide Domain carries risk in both directions. A cookie set for example.com reaches every subdomain, and the OWASP Session Management Cheat Sheet says a too permissive Domain lets an attacker attack session IDs across hosts on the same domain: its example is that vulnerabilities in www.example.com might allow an attacker to get access to the session IDs from secure.example.com.
In the other direction, the cookie draft says cookies give no integrity guarantee between sibling domains. foo.site.example can set a cookie with Domain=site.example, possibly overwriting one bar.site.example set, and in the worst case bar.site.example will be unable to tell it from a cookie it set itself (cookie draft 8.6).
The cheat sheet recommends leaving Domain unset on session cookies and not mixing web applications of different security levels on the same domain.
When a cookie does need to reach several subdomains, as in row 5 of the decision table, set Domain to the parent you control on purpose, give the cookie a __Secure- name, keep anything that grants access out of it, and treat its value as untrusted input on every host that reads it.
WSTG-SESS-09, OWASP's session hijacking test, says full HSTS adoption is required when session cookies are issued with the Domain attribute set, and ASVS 5.0 requirement 3.4.1 asks, from Level 2, for an HSTS policy that applies to all subdomains.
Path: scope, not a security boundary
Path limits a cookie to part of a site.
The browser includes the cookie only when the path of the request matches the cookie's Path or is a subdirectory of it, with the slash as the directory separator (RFC 6265 4.1.2.4). MDN's example: with Path=/docs, the request paths /docs, /docs/, /docs/Web/ and /docs/Web/HTTP match, and /, /docsets and /fr/docs do not.
Leave Path out and the browser uses the directory of the request URL's path as the default (RFC 6265 4.1.2.4 and 5.1.4). That default is easy to miss. In the lab, cookies the careless version sets from /account/login without a Path get the path /account, so a sign-out that clears them with Path=/ does not match them.
Path is not a security measure. RFC 6265 says that although it seems useful for isolating cookies between paths on one host, the Path attribute cannot be relied upon for security. The cookie draft gives two reasons. Some user agents expose cookies through non-HTTP APIs such as document.cookie without isolating resources received from different paths, so a page on one path might be able to read cookies stored for another (cookie draft 8.5).
And the browser accepts an arbitrary Path in a Set-Cookie header, so a response for /foo/bar can set a cookie for /qux (cookie draft 8.6).
Its conclusion is that servers should not both run mutually distrusting services on different paths of the same host and use cookies to store security-sensitive information. MDN says the path attribute is not intended as a security measure.
Use Path to keep a cookie out of parts of a site that do not need it. WSTG-SESS-02, OWASP's cookie attributes test, warns that a Path set too loosely could leave an application open to attacks by other applications on the same server. Put applications that should not trust each other on separate hostnames instead: ASVS 5.0 requirement 3.5.4, at Level 2, asks for separate applications on different hostnames so they can rely on the same-origin policy and hostname-based restrictions on cookies.
A __Host- cookie has to use Path=/ in any case. Ports do not separate cookies either: the cookie draft says a cookie readable by a service on one port is also readable by a service on another port of the same server, and a cookie writable on one port is also writable on another (cookie draft 8.5).
Expires and Max-Age: how long the browser keeps a cookie
Expires gives the date and time a cookie expires, and Max-Age the number of seconds until it does.
Both state a maximum lifetime, not a promise: RFC 6265 says the browser is not required to keep the cookie that long, and that user agents often evict cookies due to memory pressure or privacy concerns. When a cookie has both, Max-Age takes precedence.
When it has neither, the browser keeps it until the current session is over, as the browser defines it (RFC 6265 4.1.2.1 and 4.1.2.2), and MDN calls it a session cookie.
Max-Age is the easier one to get right. An Expires date is read against the browser's clock, which may differ from the server's, and the cookie draft says servers must not depend on cookies being evicted exactly at the date and time of the server's clock (cookie draft 4.1.2.1).
MDN's cookies guide calls Max-Age less error-prone for that reason, and its Set-Cookie reference says Firefox and Chromium-based browsers adjust for clock difference using the response's Date header. RFC 6265 also notes that some existing user agents do not support Max-Age and ignore it.
Long lifetimes are capped. The cookie draft says a browser must limit the lifetime of a cookie set with Expires or Max-Age, that the limit should not be more than 400 days in the future, and that a longer value must be reduced to the limit (cookie draft 5.5).
It also asks servers to select reasonable expiration periods based on the purpose of the cookie rather than gratuitously long ones (cookie draft 7.4). The careless version of the lab's remember-this-device cookie asks for far more than 400 days, and the checker flags it.
A cookie's expiry is an instruction to the browser, not a session control. A copy of the value can be sent whatever the expiry says, so the server has to enforce its own limits; the session management guide covers timeouts.
Removing a cookie uses the same attributes. RFC 6265's example removes a cookie by sending it again with an Expires date in the past, and says the server will succeed only if the Path and Domain attributes match the values used when the cookie was created.
RFC 6265 and the cookie draft both give a server's Max-Age, in their grammar, as a number starting with a digit from 1 to 9. MDN's Set-Cookie reference says a zero or negative Max-Age expires the cookie immediately, and the draft's rules for browsers treat zero or less as expired (cookie draft 5.6.2). The logout flow in the lab shows what a mismatched Path or Domain does.
What your framework sets by default
Frameworks set some attributes for you and leave others off, and their defaults differ.
Two examples, from each project's own documentation as read on 14 November 2026:
- express-session for Node.js: the README gives the session cookie's default settings as path '/', httpOnly true, secure false and maxAge null. By default SameSite is not set and no Domain is set, and the cookie is named connect.sid. The README calls secure: true a recommended option, says it requires an HTTPS-enabled website, and says that if you use it behind a proxy you need to set Express's trust proxy setting.
- Django 6.1: SESSION_COOKIE_SECURE defaults to False, SESSION_COOKIE_HTTPONLY to True, SESSION_COOKIE_SAMESITE to 'Lax', SESSION_COOKIE_DOMAIN to None and SESSION_COOKIE_PATH to '/'. For the CSRF cookie, CSRF_COOKIE_SECURE and CSRF_COOKIE_HTTPONLY default to False and CSRF_COOKIE_SAMESITE to 'Lax'. The settings reference says leaving SESSION_COOKIE_SECURE off isn't a good idea, because an attacker could capture an unencrypted session cookie with a packet sniffer and use the cookie to hijack the user's session.
Read the headers your production site sends
In both frameworks Secure is off until you turn it on, so a production site has to set it in configuration. The Next.js authentication guide recommends setting session cookies on the server with the HttpOnly, Secure and SameSite options, an expiry and a path. Whatever the framework, check the Set-Cookie headers your production site sends, because the headers are what browsers act on.
The OWASP Session Management Cheat Sheet also recommends changing a framework's default session cookie name to a generic one, because names such as PHPSESSID, JSESSIONID and ASP.NET_SessionId can reveal the technology behind the site. A generic name with a __Host- prefix, as in the lab's __Host-sid, does both jobs.
Running the cookie lab on your own machine
The lab is an illustration.
An invented site, app.example.com with a widget host at widget.example.net, sends its cookies in a careless version and a careful version. The server binds to 127.0.0.1, lets the system pick a free port, keeps nothing between requests and uses only modules that ship with Node.js, so there is nothing to install.
It was written and run on Node.js 26.0.0, and every output in the asset was copied from that run. Use it for learning and for checking the cookies your own site sets.
Be exact about what it proves. A scripted client sends the requests of four flows, login, logout, subdomains and cross-site, over plain HTTP to 127.0.0.1, naming the invented host in each request and recording the https URL each step stands for. The checker reads every Set-Cookie header that comes back and reports, attribute by attribute, what is present, what the decision table expects for that cookie, and whether the prefix rules and the cookie draft's other storage rules hold for that header text, judged as if it came from that https URL.
It is not a browser.
It stores no cookies and cannot show what any browser keeps or sends; Part 5 of the asset gives the steps to see that in your own browser's developer tools.
- Save the five files into an empty folder and open a terminal there.
- Run node run-flows.mjs. It prints every Set-Cookie header from the four flows for the careless version and then the careful version, with the checker's findings and a summary. The careless version has 30 attribute differences or broken rules, 3 cookies its sign-out does not clear and 1 cookie in scope beyond app.example.com that is not meant to be shared. The careful version has none of each.
- Run node cookie-flags.test.mjs. Node's built-in test runner runs nine tests against the careful version and all pass. Run node cookie-flags.test.mjs careless and eight fail, each naming the attributes that differ. The Node.js documentation says the runner sets the exit code to 1 when any test fails, so a pipeline step running the test fails.
What each flow checks
Login: the sign-in response and the first page set five cookies, one for each of rows 1 to 5 of the decision table, and each is compared with its row. Logout: for each cookie sign-out should clear, the clearing header is compared with the cookie as it was set.
It has to repeat the name, Path and Domain, because RFC 6265 says a server removes a cookie only if the Path and Domain match the values used when it was created, and the cookie draft replaces a stored cookie only when the name, domain, host-only flag and path all match (cookie draft 5.7, step 23).
Subdomains: for each login cookie, the hosts it is in scope for under the draft's domain-match rule, and whether a sibling subdomain could set a cookie of the same name that app.example.com would receive.
Under the draft's storage model, such a cookie is kept beside an original that is host-only, because the two differ in domain and host-only flag, and replaces an original that has Domain=example.com and the same path (cookie draft 5.7, steps 23 and 24).
Cross-site: the widget cookie set in an iframe on another site, compared with row 6 and with the draft's rules for cross-site responses.
For subdomain and cross-site behaviour, the lab shows the headers and what the specification says follows from them. What a browser actually stores and sends depends on that browser and its settings, so Part 5 of the asset lists steps to confirm it on your own site, in each browser you care about.
Where an outside test fits
Your own checks cover the cookies you know about.
The Clever Ops website security check, which does not sign in, reviews the cookie settings anyone can see under WSTG-SESS-02, where a good result is Secure on every cookie, HttpOnly on any cookie that identifies a session, and a SameSite value chosen deliberately rather than left to the browser.
It reads the cookies issued before sign-in. A web application and API penetration test covers authentication and sessions, and an authenticated test follows the session through sign-in, use, sign-out and timeout.
Each finding comes with evidence, a fix written for your stack and the criteria the retest will use. If Clever Ops built or hosts your site, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
Frequently asked questions
Setting each cookie's attributes so the browser sends it only where, when and to whom it should. Secure keeps it off plain HTTP, HttpOnly keeps it from page script, SameSite limits cross-site requests, Domain and Path set its scope, Expires or Max-Age its lifetime, and the __Host- and __Secure- prefixes let the server rely on some of those attributes. The cookie draft says that by default cookies provide neither confidentiality nor integrity against network attackers, so each protective attribute has to be stated.
The decision table's session row: a __Host- name with Path=/, Secure, HttpOnly and SameSite set to Lax or Strict, no Domain attribute, and no Expires or Max-Age unless the cookie has to outlive a browser restart. WSTG-SESS-02 gives __Host-SID with path=/, Secure, HttpOnly and SameSite=Strict as its most secure configuration, and the OWASP Session Management Cheat Sheet recommends the __Host- prefix for session IDs.
It keeps the cookie out of reach of page script. RFC 6265 says the browser omits it when providing cookies to non-HTTP APIs, and MDN gives document.cookie as the example. The cookie is still sent with requests that script makes. ASVS 5.0 requirement 3.3.4 asks for it on any cookie whose value is not meant for script, such as a session token.
__Secure- requires the Secure attribute. __Host- requires Secure, a Path of / and no Domain attribute, which locks the cookie to the host that set it. A browser that supports prefixes rejects a prefixed cookie that breaks its rules, and the cookie draft requires browsers to match the prefix case-insensitively. ASVS 5.0 requirement 3.3.3 asks for __Host- unless a cookie is explicitly designed to be shared with other hosts.
Only if the cookie has to reach other hosts. Leaving Domain out makes the cookie host-only, which MDN calls more restrictive than setting the host name. Setting it sends the cookie to that domain and all its subdomains, and the cookie draft warns that a sibling subdomain can set a cookie that another host may be unable to tell from its own.
No. RFC 6265 says the Path attribute cannot be relied upon for security. The cookie draft explains that in some user agents script on one path may be able to read cookies stored for another, and that a response can set a cookie for any path. Put applications that should not trust each other on separate hostnames.
A clearing header removes only a cookie with the same name, Path and Domain: RFC 6265 says the server succeeds only if the Path and Domain match the values used when the cookie was created. A cookie set without a Path gets the directory of the URL that set it, so check the path it actually has. For a __Host- or __Secure- cookie, the clearing header has to meet the prefix rules too. And clearing the cookie does not end the session on the server.
Cookies set with the Partitioned attribute, which MDN says are stored using partitioned storage and must also be Secure. MDN's CHIPS page says they are double-keyed, by the origin that sets them and by the top-level page, so a widget embedded on two sites gets a separate cookie on each. MDN marks the feature Baseline 2025, newly available since December 2025, and says it might not work in older devices or browsers.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.