RFC 2965

HTTP State Management Mechanism

πŸ“… published October 2000, from ietf

HTTP State Management Mechanism πŸͺ

Okay bestie, this is RFC 2965, titled "HTTP State Management Mechanism" πŸŽ€. It's a Standards Track document from the Network Working Group, dated October 2000, and it obsoletes RFC 2109 (more on that in the Abstract ✨). The authors are D. Kristol of Bell Laboratories, Lucent Technologies, and L. Montulli of Epinions.com, Inc. πŸ’…


Status of this Memo πŸ“œ

This doc specifies an Internet standards track protocol for the Internet community, and it's asking for discussion and suggestions for improvements πŸ¦‹. For the standardization state and status of this protocol, check the current edition of the "Internet Official Protocol Standards" (STD 1). Distribution of this memo is unlimited 🌈.

Copyright (C) The Internet Society (2000). All Rights Reserved.

IESG Note 🧚

The IESG points out that this mechanism uses the .local top-level domain (TLD) behind the scenes whenever it handles host names that don't contain any dots πŸ‘€. It also says this mechanism might not work the way you'd expect if an actual .local TLD ever gets registered πŸ’€.

Abstract 🌸

This doc is all about creating a stateful session with Hypertext Transfer Protocol (HTTP) requests and responses ✨. It describes three new headers, Cookie, Cookie2, and Set-Cookie2, which carry state information between participating origin servers and user agents 🫢. The method here is different from Netscape's Cookie proposal [Netscape], but it can interoperate with HTTP/1.0 user agents that use Netscape's method. (See the HISTORICAL section.) πŸ’œ

This doc reflects implementation experience with RFC 2109, and it obsoletes that RFC πŸ™ˆ.

1. Terminology πŸ“š

The terms user agent, client, server, proxy, origin server, and http_URL have the same meaning as in the HTTP/1.1 specification [RFC2616]. The terms abs_path and absoluteURI have the same meaning as in the URI Syntax specification [RFC2396] πŸ“.

Host name (HN) means either the host domain name (HDN) or the numeric Internet Protocol (IP) address of a host. The fully qualified domain name is preferred, and using numeric IP addresses is strongly discouraged πŸ™…β€β™€οΈ.

The terms request-host and request-URI refer to the values the client would send to the server as, respectively, the host (but not port) and abs_path portions of the absoluteURI (http_URL) of the HTTP request line. Note that request-host is a HN πŸ’….

The term effective host name is related to host name. If a host name contains no dots, the effective host name is that name with the string .local appended to it. Otherwise, the effective host name is the same as the host name. Note that all effective host names contain at least one dot πŸ§šβ€β™€οΈ.

The term request-port refers to the port portion of the absoluteURI (http_URL) of the HTTP request line. If the absoluteURI has no explicit port, the request-port is the HTTP default, 80. The request-port of a cookie is the request-port of the request in which a Set-Cookie2 response header was returned to the user agent πŸŽ€.

Host names can be specified either as an IP address or a HDN string. Sometimes we compare one host name with another. (Such comparisons SHALL be case-insensitive.) Host A's name domain-matches host B's if:

  • their host name strings string-compare equal; or
  • A is a HDN string and has the form NB, where N is a non-empty name string, B has the form .B', and B' is a HDN string. (So, x.y.com domain-matches .Y.com but not Y.com.)

Note that domain-match is not a commutative operation: a.b.c.com domain-matches .c.com, but not the reverse πŸ”„.

The reach R of a host name H is defined as follows:

  • If:
    • H is the host domain name of a host; and,
    • H has the form A.B; and
    • A has no embedded (that is, interior) dots; and
    • B has at least one embedded dot, or B is the string "local". then the reach of H is .B.
  • Otherwise, the reach of H is H.

For two strings that represent paths, P1 and P2, P1 path-matches P2 if P2 is a prefix of P1 (including the case where P1 and P2 string-compare equal). So the string /tec/waldo path-matches /tec πŸ›€οΈ.

Because it was used in Netscape's original implementation of state management, this doc uses the term cookie to refer to the state information that passes between an origin server and user agent, and that gets stored by the user agent πŸͺ✨.

1.1. Requirements πŸ”‘

The key words "MAY", "MUST", "MUST NOT", "OPTIONAL", "RECOMMENDED", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT" in this document are to be interpreted as described in RFC 2119 [RFC2119]. That's the official vibe check for the whole doc πŸ’–.

2. State and Sessions 🌈

This doc describes a way to create stateful sessions with HTTP requests and responses. Right now, HTTP servers respond to each client request without relating that request to previous or subsequent requests 😭. The state management mechanism lets clients and servers that want to swap state information put HTTP requests and responses into a bigger context, which this doc calls a "session" πŸ›οΈ. This context might be used to create, for example, a "shopping cart", where user selections can be collected before purchase, or a magazine browsing system, where a user's previous reading affects which offerings get shown πŸ“–.

Neither clients nor servers are required to support cookies. A server MAY refuse to provide content to a client that does not return the cookies it sends πŸ™…β€β™€οΈ. No cookies, no content, periodt πŸ’….

3. Description πŸ¦‹

Here's the plan: an origin server sends state information to the user agent, and the user agent returns that state information to the origin server πŸ”. The goal is to have minimal impact on HTTP and user agents 🫧.

3.1. Syntax: General 🧩

The two state management headers, Set-Cookie2 and Cookie, have common syntactic properties involving attribute-value pairs. The following grammar uses the notation, and the tokens DIGIT (decimal digits), token (informally, a sequence of non-special, non-white space characters), and http_URL from the HTTP/1.1 specification [RFC2616] to describe their syntax πŸ“:

av-pairs    =     av-pair *(";" av-pair)
av-pair     =     attr ["=" value]              ; optional value
attr        =     token
value       =     token | quoted-string

Attributes (names) (attr) are case-insensitive 🀫. White space is permitted between tokens. Note that while the above syntax description shows value as optional, most attrs require them πŸ‘€.

NOTE: The syntax above allows whitespace between the attribute and the = sign. Not me being extra, it's literally in the spec πŸ’….

3.2. Origin Server Role πŸ¦‹

3.2.1. General πŸŽ€

okay so the origin server is the one who starts a session, if it's into that πŸ’…. to do it, it sends an extra response header back to the client called Set-Cookie2. (we'll get the deets later bestie 🫢)

when a user agent keeps a session going, it sends a Cookie request header (see below) to the origin server. the origin server MAY ignore that header, or it MAY use it to check the current state of the session ✨. it MAY send a Set-Cookie2 response header back to the client with the same info or different info, or it MAY send no Set-Cookie2 header at all πŸ™ˆ. the origin server basically ends a session by sending the client a Set-Cookie2 header with Max-Age=0 πŸ’€ (that's the big "bye" move).

Servers MAY return Set-Cookie2 response headers with any response. User agents SHOULD send Cookie request headers with every request, subject to the other rules we're about to get into 🌸.

An origin server MAY include multiple Set-Cookie2 headers in a response. ngl, an intervening gateway could fold multiple headers like that into a single header πŸ‘€, so keep that in mind.

3.2.2. Set-Cookie2 Syntax πŸ’–

the syntax for the Set-Cookie2 response header is:

set-cookie      =       "Set-Cookie2:" cookies
cookies         =       1#cookie
cookie          =       NAME "=" VALUE *(";" set-cookie-av)
NAME            =       attr
VALUE           =       value
set-cookie-av   =       "Comment" "=" value
                |       "CommentURL" "=" <"> http_URL <">
                |       "Discard"
                |       "Domain" "=" value
                |       "Max-Age" "=" value
                |       "Path" "=" value
                |       "Port" [ "=" <"> portlist <"> ]
                |       "Secure"
                |       "Version" "=" 1*DIGIT
portlist        =       1#portnum
portnum         =       1*DIGIT

okay so informally, the Set-Cookie2 response header is the token Set-Cookie2:, followed by a comma-separated list of one or more cookies. Each cookie starts with a NAME=VALUE pair, then zero or more semi-colon-separated attribute-value pairs. the attribute-value pair syntax was shown earlier, and the specific attributes plus what their values mean come next 🧚. The NAME=VALUE pair MUST come first in each cookie. the others can show up in any order if they're there. if an attribute shows up more than once in a cookie, the client SHALL only use the value tied to the first appearance of that attribute, and a client MUST ignore the values after the first one 🫠.

the NAME of a cookie MAY be the same as one of the attributes in this spec. but since the cookie's NAME has to come first in a Set-Cookie2 response header, the NAME and its VALUE can't get mixed up with an attribute-value pair πŸ™Œ.

NAME=VALUE: REQUIRED. the name of the state info (the "cookie") is NAME, and its value is VALUE. NAMEs that begin with $ are reserved and MUST NOT be used by applications 🚫.

the VALUE is opaque to the user agent. it can be whatever the origin server picks to send, possibly in a server-selected printable ASCII encoding. "opaque" means the content only matters to the origin server πŸ•΅οΈβ€β™€οΈ. and the content may actually be readable by anyone who looks at the Set-Cookie2 header, so don't count on it being secret just cuz it's opaque πŸ‘€.

Comment=value: OPTIONAL. cookies can be used to derive or store private info about a user, so the Comment attribute lets an origin server document how it plans to use the cookie πŸ“. the user can look at that info to decide whether to start or continue a session with this cookie. Characters in value MUST be in UTF-8 encoding. [RFC2279]

CommentURL="http_URL": OPTIONAL. same energy as Comment, since cookies can be used for private info too. the CommentURL attribute lets an origin server document its plans for the cookie, but through a URL. the user can check the info at that URL to decide whether to start or continue a session with this cookie πŸ”—.

Discard: OPTIONAL. the Discard attribute tells the user agent to throw the cookie out unconditionally when the user agent terminates πŸ—‘οΈ.

Domain=value: OPTIONAL. the Domain attribute says which domain the cookie is valid for. if an explicitly specified value doesn't start with a dot, the user agent adds a leading dot for you πŸͺ„.

Max-Age=value: OPTIONAL. the value of Max-Age is delta-seconds, which is the lifetime of the cookie in seconds, as a decimal non-negative integer ⏳. to handle cached cookies correctly, a client SHOULD calculate the age of the cookie using the age calculation rules in the HTTP/1.1 specification [RFC2616]. once the age is greater than delta-seconds, the client SHOULD discard the cookie. a value of zero means the cookie SHOULD be discarded immediately πŸ’€.

Path=value: OPTIONAL. the Path attribute specifies the subset of URLs on the origin server that this cookie applies to πŸ›£οΈ.

Port[="portlist"]: OPTIONAL. the Port attribute restricts which port a cookie can be returned to in a Cookie request header πŸšͺ. be careful, though: the syntax REQUIREs quotes around the OPTIONAL portlist, even if there's only one portnum in the portlist 🎯.

Secure: OPTIONAL. the Secure attribute (no value needed) tells the user agent to use only (unspecified) secure means to contact the origin server whenever it sends this cookie back, to protect the confidentially and authenticity of the info in the cookie πŸ”.

the user agent (possibly with user interaction) MAY determine what level of security it considers appropriate for "secure" cookies. the Secure attribute should be considered security advice from the server to the user agent, basically saying it's in the session's interest to protect the cookie contents πŸ›‘οΈ. when the user agent sends a "secure" cookie back to a server, it SHOULD use no less than the same level of security that was used when it got the cookie from the server πŸ”’.

Version=value: REQUIRED. the Version attribute is a decimal integer that identifies the version of the state management spec the cookie follows. for this spec, Version=1 applies πŸ”’.

3.2.3. Controlling Caching 🧁

an origin server has to be aware of how caching might affect both the returned resource and the Set-Cookie2 header. caching "public" documents is desirable 🌍. for example, if the origin server wants to use a public document, like a "front door" page, as a sentinel to mark the start of a session (one that needs a Set-Cookie2 response header generated), the page SHOULD be stored in caches "pre-expired" so the origin server will still see further requests πŸšͺ✨. "Private documents" (the ones with info that's strictly private to a session) SHOULD NOT be cached in shared caches πŸ™…β€β™€οΈ.

if the cookie is meant for a single user, the Set-Cookie2 header SHOULD NOT be cached. a Set-Cookie2 header meant to be shared by multiple users MAY be cached 🀝.

the origin server SHOULD send the following additional HTTP/1.1 response headers, depending on the situation πŸ’…:

To suppress caching of the Set-Cookie2 header:

Cache-control: no-cache="set-cookie2"

and then one of the following:

To suppress caching of a private document in shared caches:

Cache-control: private

To allow caching of a document and require that it be validated before it's returned to the client:

Cache-Control: must-revalidate, max-age=0

To allow caching of a document, but require that proxy caches (not user agent caches) validate it before returning it to the client:

Cache-Control: proxy-revalidate, max-age=0

To allow caching of a document and request that it be validated before it's returned to the client (by "pre-expiring" it):

Cache-control: max-age=0

heads up, not all caches will revalidate the document in every case πŸ₯².

HTTP/1.1 servers MUST send Expires: old-date (where old-date is a date long in the past) on responses containing Set-Cookie2 response headers, unless they know for certain (by out-of-band means) that there are no HTTP/1.0 proxies in the response chain πŸ•°οΈ. HTTP/1.1 servers MAY send other Cache-Control directives that permit caching by HTTP/1.1 proxies in addition to the Expires: old-date directive. the Cache-Control directive will override Expires: old-date for HTTP/1.1 proxies, so that's the main thing to remember πŸ’œ.

3.3. User Agent Role 🌸

3.3.1. Interpreting Set-Cookie2 πŸŽ€

okay so the user agent keeps its own separate track of state info that arrives via Set-Cookie2 response headers from each origin server (servers get told apart by name or IP address and port) 🧚. The user agent MUST ignore attribute-value pairs whose attribute it does not recognize πŸ™ˆ. When an optional attribute is missing, these defaults kick in:

  • Discard: The default behavior is dictated by the presence or absence of a Max-Age attribute.
  • Domain: Defaults to the effective request-host. (Note that because there is no dot at the beginning of effective request-host, the default Domain can only domain-match itself. πŸ’…)
  • Max-Age: The default behavior is to discard the cookie when the user agent exits.
  • Path: Defaults to the path of the request URL that generated the Set-Cookie2 response, up to and including the right-most /.
  • Port: The default behavior is that a cookie MAY be returned to any request-port.
  • Secure: If absent, the user agent MAY send the cookie over an insecure channel.

3.3.2. Rejecting Cookies 🚫

ngl this part is so important, because it's the security bouncer πŸ”₯. To prevent possible security or privacy violations, a user agent rejects a cookie according to the rules below. The goal is to limit the set of servers for which a cookie is valid, based on the values of the Path, Domain, and Port attributes and the request-URI, request-host and request-port. πŸ’–

A user agent rejects (SHALL NOT store its information) if the Version attribute is missing. Moreover, a user agent rejects (SHALL NOT store its information) if any of the following is true of the attributes explicitly present in the Set-Cookie2 response header:

  • The value for the Path attribute is not a prefix of the request-URI.
  • The value for the Domain attribute contains no embedded dots, and the value is not .local.
  • The effective host name that derives from the request-host does not domain-match the Domain attribute.
  • The request-host is a HDN (not IP address) and has the form HD, where D is the value of the Domain attribute, and H is a string that contains one or more dots.
  • The Port attribute has a "port-list", and the request-port was not in the list.

Examples, because I live for examples πŸ“:

  • A Set-Cookie2 from request-host y.x.foo.com for Domain=.foo.com would be rejected, because H is y.x and contains a dot. πŸ™…β€β™€οΈ
  • A Set-Cookie2 from request-host x.foo.com for Domain=.foo.com would be accepted. ✨
  • A Set-Cookie2 with Domain=.com or Domain=.com. will always be rejected, because there is no embedded dot. πŸ’€
  • A Set-Cookie2 with Domain=ajax.com will be accepted, and the value for Domain will be taken to be .ajax.com, because a dot gets prepended to the value. πŸ¦‹
  • A Set-Cookie2 with Port="80,8000" will be accepted if the request was made to port 80 or 8000 and will be rejected otherwise. πŸŽ€
  • A Set-Cookie2 from request-host example for Domain=.local will be accepted, because the effective host name for the request-host is example.local, and example.local domain-matches .local. πŸ‘‘

okay this is where it gets spicy 🌢️. If a user agent receives a Set-Cookie2 response header whose NAME is the same as that of a cookie it has previously stored, the new cookie supersedes the old when two things are true: the old and new Domain attribute values compare equal, using a case-insensitive string-compare; and, the old and new Path attribute values string-compare equal (case-sensitive). However, if the Set-Cookie2 has a value for Max-Age of zero, the (old and new) cookie is discarded. Otherwise a cookie persists (resources permitting) until whichever happens first, and then gets discarded: its Max-Age lifetime is exceeded; or, if the Discard attribute is set, the user agent terminates the session. ⏳

Because user agents have finite space in which to store cookies, they MAY also discard older cookies to make space for newer ones, using, for example, a least-recently-used algorithm, along with constraints on the maximum number of cookies that each origin server may set. 🧹

If a Set-Cookie2 response header includes a Comment attribute, the user agent SHOULD store that information in a human-readable form with the cookie and SHOULD display the comment text as part of a cookie inspection user interface. πŸ“

If a Set-Cookie2 response header includes a CommentURL attribute, the user agent SHOULD store that information in a human-readable form with the cookie, or, preferably, SHOULD allow the user to follow the http_URL link as part of a cookie inspection user interface. πŸ”—

The cookie inspection user interface may include a facility whereby a user can decide, at the time the user agent receives the Set-Cookie2 response header, whether or not to accept the cookie. A potentially confusing situation could arise if the following sequence occurs:

  • the user agent receives a cookie that contains a CommentURL attribute;
  • the user agent's cookie inspection interface is configured so that it presents a dialog to the user before the user agent accepts the cookie;
  • the dialog allows the user to follow the CommentURL link when the user agent receives the cookie; and,
  • when the user follows the CommentURL link, the origin server (or another server, via other links in the returned content) returns another cookie.
⚠️ bestie, this is the tricky bit. The user agent SHOULD NOT send any cookies in this context. The user agent MAY discard any cookie it receives in this context that the user has not, through some user agent mechanism, deemed acceptable.

User agents SHOULD allow the user to control cookie destruction, but they MUST NOT extend the cookie's lifetime beyond that controlled by the Discard and Max-Age attributes. An infrequently-used cookie may function as a "preferences file" for network applications, and a user may wish to keep it even if it is the least-recently-used cookie. One possible implementation would be an interface that allows the permanent storage of a cookie through a checkbox (or, conversely, its immediate destruction). πŸŽ›οΈ

Privacy considerations dictate that the user have considerable control over cookie management. The PRIVACY section contains more information. πŸ”

3.3.4. Sending Cookies to the Origin Server πŸ“€

When it sends a request to an origin server, the user agent includes a Cookie request header if it has stored cookies that are applicable to the request, based on:

  • the request-host and request-port;
  • the request-URI;
  • the cookie's age.

The syntax for the header is:

cookie          =  "Cookie:" cookie-version 1*((";" | ",") cookie-value)
cookie-value    =  NAME "=" VALUE [";" path] [";" domain] [";" port]
cookie-version  =  "$Version" "=" value
NAME            =  attr
VALUE           =  value
path            =  "$Path" "=" value
domain          =  "$Domain" "=" value
port            =  "$Port" [ "=" <"> value <"> ]

Okay so the value of the cookie-version attribute MUST be the value from the Version attribute of the matching Set-Cookie2 response header πŸ’– If there's no Version, it's 0. The path attribute MUST be the value from the Path attribute of that Set-Cookie2 response header, if there was one. If there wasn't, the attribute SHOULD be left out of the Cookie request header πŸŽ€ Same energy for domain: MUST copy the Domain attribute from the Set-Cookie2 response header if it had one, and if it didn't, the attribute SHOULD be omitted from the Cookie request header ✨

The port attribute in the Cookie request header MUST mirror the Port attribute from the Set-Cookie2 response header, if that one had it πŸ¦‹ So the port attribute MUST be there if the Port attribute was in the Set-Cookie2 header, and it MUST have the same value, if any. And if the Port attribute was missing from Set-Cookie2, the port attribute likewise MUST be left out of the Cookie request header 🌸

Note that there is neither a Comment nor a CommentURL attribute in the Cookie request header that matches the ones in the Set-Cookie2 response header πŸ™ˆ The user agent does not send the comment info back to the origin server. Literally not its business πŸ’…

The user agent runs the following rules to pick which cookie-values to send in Cookie request headers out of all the cookies it has received. Main character decision-making πŸ‘‘

Domain Selection

The origin server's effective host name MUST domain-match the Domain attribute of the cookie. ✨

Port Selection

There are three possible behaviors, depending on the Port attribute in the Set-Cookie2 response header 🧚

  1. By default (no Port attribute), the cookie MAY be sent to any port.
  2. If the attribute is present but has no value (e.g., Port), the cookie MUST only be sent to the request-port it was received from.
  3. If the attribute has a port-list, the cookie MUST only be returned if the new request-port is one of those listed in port-list.

Path Selection

The request-URI MUST path-match the Path attribute of the cookie. πŸ“

Max-Age Selection

Cookies that have expired should have been discarded and thus are not forwarded to an origin server. Expired cookies are giving gone πŸ’€

If multiple cookies satisfy the criteria above, they are ordered in the Cookie header such that those with more specific Path attributes precede those with less specific. Ordering with respect to other attributes (e.g., Domain) is unspecified. So the more specific Path goes first, and anything else is up for grabs 🌈

Note: For backward compatibility, the separator in the Cookie header is semi-colon (;) everywhere. A server SHOULD also accept comma (,) as the separator between cookie-values for future compatibility 🫢

3.3.5 Identifying What Version is Understood: Cookie2

The Cookie2 request header helps clients and servers that understand different versions of the cookie spec actually talk to each other πŸ’œ When the client sends one or more cookies to an origin server, and at least one of them has a $Version attribute whose value is different from the version the client understands, then the client MUST also send a Cookie2 request header. The syntax is:

cookie2 =       "Cookie2:" cookie-version

Here the value for cookie-version is the highest version of the cookie specification (currently 1) that the client understands πŸ”₯ The client needs to send at most one such request header per request. One is the magic number, bestie 😭

3.3.6 Sending Cookies in Unverifiable Transactions

Users MUST have control over sessions in order to ensure privacy. (See PRIVACY section below.) To keep implementation simple and avoid piling on extra complexity where good safeguards already exist, this document splits transactions into verifiable and unverifiable ones πŸ“ A transaction is verifiable if the user, or a user-designated agent, has the option to review the request-URI before it's used in the transaction. A transaction is unverifiable if the user doesn't have that option. Unverifiable transactions usually happen when a user agent automatically requests inlined or embedded entities, or when it follows redirection (3xx) responses from an origin server. Usually the origin transaction, the one the user starts, is verifiable, and that transaction may directly or indirectly cause the user agent to make unverifiable transactions πŸ¦‹

An unverifiable transaction is to a third-party host if its request-host U does not domain-match the reach R of the request-host O in the origin transaction 🧐

When it makes an unverifiable transaction, a user agent MUST disable all cookie processing (i.e., MUST NOT send cookies, and MUST NOT accept any received cookies) if the transaction is to a third-party host. Full shutdown, no exceptions πŸ™…β€β™€οΈ

This restriction stops a shady service author from using unverifiable transactions to trick a user agent into starting or continuing a session with a server on a different domain πŸ’€ Starting or continuing those sessions could go against the user's privacy expectations, and could also be a security problem. Not it 🚫

User agents MAY offer configurable options that let the user agent, or any autonomous programs the user agent runs, ignore the above rule, so long as these override options default to "off". Off by default is the only way to be 🫢

(N.B. Mechanisms may be proposed that will automate overriding the third-party restrictions under controlled conditions.) πŸ‘€

Lots of current user agents already have a review option that would make many links verifiable 🌸 For instance, some user agents show the URL a link points to when the mouse pointer hovers over it. The user can then decide whether to visit that site before the browser does it for them. (Though current user agents don't do this, a similar technique could work for a form submit button, where the user agent would show the action to be taken if the user selected that button.) Even so, that still wouldn't make every link verifiable. For example, links to automatically loaded images wouldn't normally be subject to "mouse pointer" verification πŸ™ˆ

Plenty of user agents also let a user view the HTML source of a document, or save the source to an external file where another application can view it. That's a crude review mechanism, though, and some users might not think it's acceptable for this purpose πŸ€·β€β™€οΈ

A user agent sends back much of the information from the Set-Cookie2 header to the origin server when the request-URI path-matches the Path attribute of the cookie 🧚 When it gets a Cookie header, the origin server SHOULD treat cookies whose NAMEs start with the prefix $ specially, as an attribute for the cookie. Those $ things are the attributes, not the cookies, babe ✨

3.5 Caching Proxy Role

One reason for keeping state information separate from both a URL and document content is to make the scaling that caching allows actually work πŸš€ To support cookies, a caching proxy MUST obey these rules that are already in the HTTP specification:

  • Honor requests from the cache, if possible, based on cache validity rules.
  • Pass along a Cookie request header in any request that the proxy must make of another server.
  • Return the response to the client. Include any Set-Cookie2 response header.
  • Cache the received response subject to the control of the usual headers, such as Expires,

Cache-control: no-cache

and

Cache-control: private

  • Cache the Set-Cookie2 subject to the control of the usual header,

Cache-control: no-cache="set-cookie2"

(The Set-Cookie2 header should usually not be cached.) πŸ™ƒ

Proxies MUST NOT introduce Set-Cookie2 (Cookie) headers of their own in proxy responses (requests). Proxies don't get to add their own cookies, period πŸ›‘

4. EXAMPLES ✨

4.1 Example 1

Most of the request and response headers have been left out πŸ’… Assume the user agent has no stored cookies.

  1. User Agent -> Server
POST /acme/login HTTP/1.1
[form data]

User identifies self via a form.

  1. Server -> User Agent
HTTP/1.1 200 OK
Set-Cookie2: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"

Cookie reflects user's identity.

  1. User Agent -> Server
POST /acme/pickitem HTTP/1.1
Cookie: $Version="1"; Customer="WILE_E_COYOTE"; $Path="/acme"
[form data]

User selects an item for "shopping basket".

  1. Server -> User Agent
HTTP/1.1 200 OK
Set-Cookie2: Part_Number="Rocket_Launcher_0001"; Version="1";
        Path="/acme"

Shopping basket contains an item.

  1. User Agent -> Server
POST /acme/shipping HTTP/1.1
Cookie: $Version="1";
        Customer="WILE_E_COYOTE"; $Path="/acme";
        Part_Number="Rocket_Launcher_0001"; $Path="/acme"
[form data]

User selects shipping method from form.

  1. Server -> User Agent
HTTP/1.1 200 OK
Set-Cookie2: Shipping="FedEx"; Version="1"; Path="/acme"

New cookie reflects shipping method.

  1. User Agent -> Server
POST /acme/process HTTP/1.1
Cookie: $Version="1";
        Customer="WILE_E_COYOTE"; $Path="/acme";
        Part_Number="Rocket_Launcher_0001"; $Path="/acme";
        Shipping="FedEx"; $Path="/acme"
[form data]

User chooses to process order.

  1. Server -> User Agent
HTTP/1.1 200 OK

Transaction is complete. Order placed, we're all done πŸŽ‰

The user agent makes a series of requests to the origin server, and after each one it gets a new cookie. All the cookies have the same Path attribute and (default) domain. Because the request-URIs all path-match /acme, the Path attribute of each cookie matches too, so each request includes all the cookies received so far πŸ›’

4.2 Example 2

This example shows how the Path attribute works πŸ¦‹ All detail of request and response headers has been left out. Assume the user agent has no stored cookies.

Imagine the user agent got these response headers from earlier requests:

Set-Cookie2: Part_Number="Rocket_Launcher_0001"; Version="1";
        Path="/acme"

and

Set-Cookie2: Part_Number="Riding_Rocket_0023"; Version="1";
        Path="/acme/ammo"

A later request by the user agent to the (same) server for URLs of the form /acme/ammo/... would include this request header:

Cookie: $Version="1";
        Part_Number="Riding_Rocket_0023"; $Path="/acme/ammo";
        Part_Number="Rocket_Launcher_0001"; $Path="/acme"

Notice that the NAME=VALUE pair for the cookie with the more specific Path attribute, /acme/ammo, comes before the one with the less specific Path attribute, /acme. Also notice that the same cookie name shows up more than once πŸ‘‘

A later request by the user agent to the (same) server for a URL of the form /acme/parts/ would include this request header:

Cookie: $Version="1"; Part_Number="Rocket_Launcher_0001";
$Path="/acme"

Here, the second cookie's Path attribute /acme/ammo is not a prefix of the request URL, /acme/parts/, so that cookie doesn't get forwarded to the server πŸ™…β€β™€οΈ

5. IMPLEMENTATION CONSIDERATIONS πŸŽ€

okay so this section is basically the "how to actually build this without tripping over yourself" tips for origin servers that do state management. no cap, the vibe is practical and bestie-coded πŸ’…

5.1. Set-Cookie2 Content

okay so an origin server's content should probably be split up into disjoint application areas πŸ—‚οΈ, and some of those areas need state info and some don't. the cute part is that you can tell the areas apart by their request URLs! πŸ¦‹ then the Set-Cookie2 header can carry that info by setting the Path attribute for each area. it's giving organized and it's giving main character energy πŸ‘‘

the session info can obviously be clear text or encoded text that describes the state πŸ“. but ngl if it gets too big it becomes super unwieldy 😭. so an implementor might choose to make the session info a key that points to a server-side resource instead πŸ”‘. BUT, and this is a big but, using a database brings back some problems this whole state management spec was trying to avoid πŸ’€, namely:

  1. keeping real state on the server side πŸ™ˆ;
  2. how and when to garbage-collect the database entry, in case the user agent ends the session by, for example, exiting 🧹.

5.2. Stateless Pages

caching is literally what keeps the WWW scalable 🌐, so it matters a lot to cut down on the number of documents that have state baked into them πŸ“. for example, if a shopping-basket app always shows a user's current basket contents on every page, those pages can't be cached, because every user's basket is different 🧺. but if each page just has a link that says "Look at My Shopping Basket", the page can be cached πŸ’–. iconic.

5.3. Implementation Limits

real user agents have limits on how many cookies and how big they can be πŸ“¦. in general, user agent cookie support should have no fixed limits 🌈, and they should strive to store as many frequently-used cookies as possible ⭐. furthermore, general-use user agents SHOULD provide each of the following minimum capabilities individually πŸ’œ, although not necessarily all at the same time:

  • at least 300 cookies
  • at least 4096 bytes per cookie (as measured by the characters that comprise the cookie non-terminal in the syntax description of the Set-Cookie2 header, and as received in the Set-Cookie2 header)
  • at least 20 cookies per unique host or domain name

user agents made for specific purposes or for limited-capacity devices SHOULD provide at least 20 cookies of 4096 bytes 🧚, so the user can actually interact with a session-based origin server. bestie, that's the minimum for a smooth experience ✨

the information in a Set-Cookie2 response header MUST be retained in its entirety 🫢. if there isn't enough space to store the cookie for some reason, it MUST be discarded, not truncated 🚫. no half-cookies allowed, periodt πŸ’…

applications should use as few and as small cookies as possible 🌸, and they should cope gracefully with losing a cookie πŸ¦‹.

5.3.1. Denial of Service Attacks

user agents MAY choose to set an upper bound on the number of cookies stored from a given host or domain name, or on the size of the cookie information πŸ›‘οΈ. otherwise a malicious server could try to flood a user agent with tons of cookies, or huge ones, over successive responses 😀, which would force out the cookies the user agent got from other servers πŸ’€. however, the minima specified above SHOULD still be supported πŸŽ€. don't be sus, be protected!

6. PRIVACY πŸ”’

informed consent should guide the design of systems that use cookies 🫢. a user should be able to find out how a web site plans to use the information in a cookie, and should be able to choose whether or not those policies are acceptable ✨. both the user agent and the origin server must assist informed consent πŸ‘‘.

6.1. User Agent Control

an origin server could create a Set-Cookie2 header to track a user's path through the server πŸ•΅οΈβ€β™€οΈ. users may object to this, because it feels like an intrusive pile of info 😭, even if their identity isn't obvious. (identity might become obvious, for example, if a user later fills out a form with identifying info πŸ™ˆ.) this spec therefore REQUIRES that a user agent give the user control over this possible intrusion, though the interface for that control is left unspecified πŸŽ€. however, the control mechanisms provided SHALL at least allow the user:

  • to completely disable the sending and saving of cookies.
  • to determine whether a stateful session is in progress.
  • to control the saving of a cookie on the basis of the cookie's Domain attribute.

such control could be provided, for example, by mechanisms:

  • to notify the user when the user agent is about to send a cookie to the origin server, so they can offer the option not to begin a session 🚦.
  • to display a visual indication that a stateful session is in progress πŸ‘€.
  • to let the user decide which cookies, if any, should be saved when the user closes a window or ends the user agent session πŸ—‘οΈ.
  • to let the user examine and delete the contents of a cookie at any time πŸ”.

a user agent usually starts executing with no remembered state information 🌱. it SHOULD be possible to configure a user agent never to send Cookie headers, in which case it can never sustain state with an origin server πŸ™…β€β™€οΈ. (the user agent would then behave like one that doesn't know how to handle Set-Cookie2 response headers.)

when the user agent stops executing, it SHOULD let the user discard all state information 🧹. alternatively, the user agent MAY ask the user whether state information should be kept; the default should be "no" πŸ™…. if the user chooses to keep state information, it would be restored the next time the user agent runs πŸ”.

NOTE: user agents should probably be cautious about using files to store cookies long-term. if a user runs more than one instance of the user agent, the cookies could get commingled or otherwise corrupted πŸ’€.

6.2. Origin Server Role

an origin server SHOULD promote informed consent by adding CommentURL or Comment information to the cookies it sends πŸ“£. CommentURL is preferred, because it gives you the chance to provide richer info in a bunch of different languages 🌍✨.

6.3. Clear Text

the information in the Set-Cookie2 and Cookie headers is unprotected 😱. as a consequence:

  1. any sensitive information conveyed in them is exposed to intruders πŸ‘€.
  2. a malicious intermediary could alter the headers as they travel in either direction, with unpredictable results πŸ’€.

these facts mean that information of a personal and/or financial nature should only be sent over a secure channel πŸ”. for less sensitive info, or when the content of the header is a database key, an origin server should be vigilant to prevent a bad Cookie value from causing failures πŸ›‘οΈ.

a user agent in a shared user environment poses a further risk πŸ–₯️. using a cookie inspection interface, User B could examine the contents of cookies that were saved when User A used the machine 😳. not safe!

7. SECURITY CONSIDERATIONS ⚠️

7.1. Protocol Design

the restrictions on the value of the Domain attribute, and the rules about unverifiable transactions, are meant to reduce the ways cookies can "leak" to the "wrong" site 🚫. the intent is to restrict cookies to one host, or a closely related set of hosts 🎯. therefore a request-host is limited as to what values it can set for Domain. we consider it acceptable for hosts host1.foo.com and host2.foo.com to share cookies, but not a.com and b.com 🀝.

similarly, a server can set a Path only for cookies that are related to the request-URI πŸ›€οΈ.

proper application design can avoid spoofing attacks from related domains πŸ•ΈοΈ. consider:

  1. user agent makes a request to victim.cracker.edu, gets back cookie session_id="1234", and sets the default domain victim.cracker.edu.
  2. user agent makes a request to spoof.cracker.edu, gets back cookie session-id="1111", with Domain=".cracker.edu".
  3. user agent makes a request to victim.cracker.edu again, and passes
Cookie: $Version="1"; session_id="1234",
        $Version="1"; session_id="1111"; $Domain=".cracker.edu"

the server at victim.cracker.edu should detect that the second cookie was not one it originated, by noticing that the Domain attribute is not for itself, and ignore it πŸ•΅οΈβ€β™€οΈ.

a user agent SHOULD make every attempt to prevent the sharing of session information between hosts that are in different domains 🚧. embedded or inlined objects may cause particularly severe privacy problems if they can be used to share cookies between disparate hosts 😱. for example, a malicious server could embed cookie information for host a.com in a URI for a CGI on host b.com πŸ‘». user agent implementors are strongly encouraged to prevent this sort of exchange whenever possible πŸ™.

7.4. Cookies For Account Information

while it's common practice to use them this way, cookies are not designed or intended to hold authentication information, such as account names and passwords πŸ™…β€β™€οΈ. unless such cookies are exchanged over an encrypted path, the account information they contain is highly vulnerable to snooping and theft πŸ’€πŸ”“. do not put passwords in cookies, bestie!

8. OTHER, SIMILAR, PROPOSALS 🌈

apart from RFC 2109, three other proposals have been made to accomplish similar goals 🧩. this specification began as an amalgam of Kristol's State-Info proposal [DMK95] and Netscape's Cookie proposal [Netscape] 🍼.

Brian Behlendorf proposed a Session-ID header that would be user-agent-initiated and could be used by an origin server to track "clicktrails" 🐾. it would not carry any origin-server-defined state, however. Phillip Hallam-Baker has proposed another client-defined session ID mechanism for similar purposes πŸ’œ.

while both session IDs and cookies can provide a way to sustain stateful sessions, their intended purposes are different, and so the privacy requirements for them are different πŸ€“. a user initiates session IDs to let servers track progress through them, or to tell multiple users apart on a shared machine πŸ‘―. cookies are server-initiated, so the cookie mechanism described here gives users control over something that would otherwise happen without the users' awareness πŸ‘€. furthermore, cookies convey rich, server-selected information, whereas session IDs comprise user-selected, simple information ✨.

9. HISTORICAL πŸ“œ

9.1. Compatibility with Existing Implementations ✨

okay so the old Netscape cookies are still out here πŸ“ and they use plain Set-Cookie (not Set-Cookie2). If a user agent gets BOTH headers for the same cookie in one response, it MUST discard the Set-Cookie info and only keep the Set-Cookie2 info. And if it got a Set-Cookie2 header, it MUST assume the server follows this spec and will understand Cookie request headers that also follow this spec 🫢

new cookies MUST replace both the old-style and new-style versions πŸ‘‘ So if a user agent that follows both this spec and Netscape's original one gets a Set-Cookie2 header, and the NAME and the Domain and Path attributes match a Netscape-style cookie (per the Cookie Management section), that Netscape-style cookie MUST be discarded. The user agent MUST retain only the cookie that follows this spec. Main character energy, no notes πŸ’…

older user agents that don't understand this spec, but do understand Netscape's original one, won't recognize Set-Cookie2 at all. They'll just keep sending and receiving cookies the old way πŸ¦‹

a user agent that supports both this spec and Netscape-style cookies SHOULD send a Cookie request header that follows the older Netscape spec, if it got the cookie in a Set-Cookie header and not a Set-Cookie2 header. BUT it SHOULD also send this request header πŸ™ˆ

Cookie2: $Version="1"

the Cookie2 header basically tells the server "hey, I understand new-style cookies!" 🧚 If the server gets new-style cookies too, it SHOULD keep the stateful session going by sending a Set-Cookie2 response header instead of Set-Cookie. A server that doesn't understand new-style cookies will just ignore the Cookie2 request header. Iconic behavior honestly πŸ’–


9.2. Caching and HTTP/1.0 🌸

okay this one is lowkey scary ngl 😭 Some caches, like the ones that follow HTTP/1.0, are going to cache the Set-Cookie2 and Set-Cookie headers no matter what, because there was no way to stop caching headers before HTTP/1.1. That can cause real security problems πŸ’€

usually the documents an origin server sends along with Set-Cookie2 and Set-Cookie headers are either uncachable or "pre-expired". As long as caches obey the instructions not to cache documents (like Expires: with a date in the past, or Pragma: no-cache for HTTP/1.0, or Cache-control: no-cache for HTTP/1.1), uncachable documents are totally fine πŸŽ€

BUT pre-expired documents can still get stored in caches. They need validation (a conditional GET) on every new request. The problem is some cache operators loosen the rules, and sometimes they serve expired documents without validating them first. Put those together and cookies meant for one user can later get sent to a different user 😱 The Set-Cookie2 and Set-Cookie headers get stored in the cache, and even though the document is stale (expired), the cache returns it for later requests, headers and all. Not it πŸ™…β€β™€οΈ


10. ACKNOWLEDGEMENTS πŸŽ€

this document is really the team effort of the HTTP Working Group of the IETF 🫢 And a big shoutout, in addition to the authors, to these legends: Roy Fielding, Yaron Goland, Marc Hedlund, Ted Hardie, Koen Holtman, Shel Kaphan, Rohit Khare, Foteos Macrides, David W. Morris. πŸ’œ


11. AUTHORS' ADDRESSES πŸ¦‹

David M. Kristol
Bell Laboratories, Lucent Technologies
600 Mountain Ave.  Room 2A-333
Murray Hill, NJ  07974

Phone: (908) 582-2250
Fax: (908) 582-1239
EMail: dmk@bell-labs.com


Lou Montulli
Epinions.com, Inc.
2037 Landings Dr.
Mountain View, CA  94301

EMail: lou@montulli.org

12. REFERENCES πŸ“š

these are all the sources this spec leans on, bestie πŸ€“

[DMK95]    Kristol, D.M., "Proposed HTTP State-Info Mechanism",
           available at <http://portal.research.bell-labs.com/~dmk/state-info.html>,
           September, 1995.

[Netscape] "Persistent Client State -- HTTP Cookies", available at
           <http://www.netscape.com/newsref/std/cookie_spec.html>,
           undated.

[RFC2109]  Kristol, D. and L. Montulli, "HTTP State Management
           Mechanism", RFC 2109, February 1997.

[RFC2119]  Bradner, S., "Key words for use in RFCs to Indicate
           Requirement Levels", BCP 14, RFC 2119, March 1997.

[RFC2279]  Yergeau, F., "UTF-8, a transformation format of Unicode
           and ISO-10646", RFC 2279, January 1998.

[RFC2396]  Berners-Lee, T., Fielding, R. and L. Masinter, "Uniform
           Resource Identifiers (URI): Generic Syntax", RFC 2396,
           August 1998.

[RFC2616]  Fielding, R., Gettys, J., Mogul, J., Frystyk, H. and T.
           Berners-Lee, "Hypertext Transfer Protocol -- HTTP/1.1",
           RFC 2616, June 1999.

the legal bit, kept complete and word for word so nothing gets lost πŸ”’

Copyright (C) The Internet Society (2000).  All Rights Reserved.

This document and translations of it may be copied and furnished to
others, and derivative works that comment on or otherwise explain it
or assist in its implementation may be prepared, copied, published
and distributed, in whole or in part, without restriction of any
kind, provided that the above copyright notice and this paragraph are
included on all such copies and derivative works.  However, this
document itself may not be modified in any way, such as by removing
the copyright notice or references to the Internet Society or other
Internet organizations, except as needed for the purpose of
developing Internet standards in which case the procedures for
copyrights defined in the Internet Standards process must be
followed, or as required to translate it into languages other than
English.

The limited permissions granted above are perpetual and will not be
revoked by the Internet Society or its successors or assigns.

This document and the information contained herein is provided on an
"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.

Acknowledgement 🫢

funding for the RFC Editor function is currently provided by the Internet Society ✨

πŸ“¦ where this page comes from