libstd/http/cookies
The cookies of a request and of its response. Every request that reaches a route or a middleware carries a Cookies object in req.cookies: it holds the cookies the browser sent, and collects the ones to send back with the response. A cookie the server sends is HttpOnly and SameSite=Lax unless asked otherwise, and a name or a value that could break the response header is refused.
#include <libstd/http>
Part of libstd/http, which includes it (the source is libstd/http/cookies.tryc). libstd/http/session uses it for the sid cookie of the sessions.
Example
A counter kept by the browser: each visit reads the cookie, adds one and sends it back; /forget deletes it.
#include <libstd/http>
def visit(self: HttpServer, req: HttpRequest) -> str:
n = 0 as long
if req.cookies.has("visits"):
n = str_to_long(req.cookies.get("visits"))
n = n + 1
req.cookies.set("visits", itoa(n), 3600, 0)
req.content_type = "text/plain; charset=utf-8"
return "visit number " + itoa(n) + "\n"
def forget(self: HttpServer, req: HttpRequest) -> str:
req.cookies.remove("visits")
req.content_type = "text/plain; charset=utf-8"
return "forgotten\n"
server = HttpServer(127, 0, 0, 1, 8000)
server.addMapsFunction("/visit", visit)
server.addMapsFunction("/forget", forget)
server.run()
curl -i -c jar -b jar http://127.0.0.1:8000/visit
curl -c jar -b jar http://127.0.0.1:8000/visit
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 15
Connection: keep-alive
Set-Cookie: visits=1; Path=/; Max-Age=3600; HttpOnly; SameSite=Lax
visit number 1
visit number 2
curl -i -c jar -b jar http://127.0.0.1:8000/forget
curl -c jar -b jar http://127.0.0.1:8000/visit
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 10
Connection: keep-alive
Set-Cookie: visits=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax
forgotten
visit number 1
curl keeps the cookies in the file jar (-c writes it, -b sends it), as a browser would.
Reading cookies
req.cookies.get(name)returns the value the client sent,""if it sent none;req.cookies.has(name)tells the two cases apart, since a cookie can also be sent with an empty value. Names are case-sensitive.- The
Cookieheader is read once, when the request arrives. SeveralCookieheaders in one request are read as one. Pairs without=and pairs with an invalid name are skipped. When a name appears twice the first value is kept. Quotes around a value are removed. Only the firstHTTP_MAX_COOKIES(50) cookies are read; the rest of the header is ignored. - Values are not decoded: a value sent as
a%20breads asa%20b.
Sending cookies
req.cookies.set(name, value, max_age, flags) adds a Set-Cookie header to the response. A route sets cookies, and so can a middleware in both phases. Setting the same name again in the same request replaces the earlier one, so a middleware in the after phase can override what the route set.
- Lifetime.
max_ageis in seconds:3600is an hour,31536000a year. A negative value makes a session cookie, withoutMax-Age, which the browser drops when it closes.0deletes the cookie. - Scope. Every cookie gets
Path=/: the browser sends it with every request to the site. - What
getsees.getkeeps returning what the client sent, not what this request has set. The value set here reachesgetwith the next request:
def color(self: HttpServer, req: HttpRequest) -> str:
req.cookies.set("color", "green", 3600, 0)
req.content_type = "text/plain; charset=utf-8"
return "sent by the client: '" + req.cookies.get("color") + "'\n"
curl http://127.0.0.1:8000/color
curl -H 'Cookie: color=red' http://127.0.0.1:8000/color
sent by the client: ''
sent by the client: 'red'
Deleting cookies
req.cookies.remove(name) asks the browser to delete a cookie: it sends the name with an empty value, Max-Age=0 and Path=/. That matches every cookie written by set, which all have Path=/. A cookie that another server wrote with another path cannot be deleted this way.
Attributes and flags
By default a cookie gets HttpOnly, so JavaScript in the page cannot read it and a script injected into the page cannot steal it. It also gets SameSite=Lax: requests that other sites start do not carry it, except plain link navigation. flags changes these defaults. Pass 0, or combine the flags with |:
| Flag | Effect |
|---|---|
HTTP_COOKIE_SECURE | Adds Secure: the browser sends the cookie only over HTTPS. Use it when the server is behind a TLS proxy. |
HTTP_COOKIE_SCRIPT | Leaves out HttpOnly, so the page's JavaScript can read the cookie. Never use it for a cookie that identifies a user. |
HTTP_COOKIE_STRICT | SameSite=Strict instead of Lax: the cookie is not sent even when another site links to this one. |
A preference that the page's JavaScript also reads, such as a color theme, is the case for HTTP_COOKIE_SCRIPT:
def set_theme(self: HttpServer, req: HttpRequest) -> str:
theme = req.getQuery()
if theme != "light" and theme != "dark":
req.status = 400
return "<p>Use /theme?light or /theme?dark</p>"
req.cookies.set("theme", theme, 31536000, HTTP_COOKIE_SCRIPT)
return "<p>Theme: " + theme + ". <a href=\"/\">Back</a></p>"
def home(self: HttpServer, req: HttpRequest) -> str:
theme = req.cookies.get("theme")
if theme != "dark":
theme = "light"
return "<body class=\"" + theme + "\"><p>Current theme: " + theme + "</p></body>"
curl -i -c jar 'http://127.0.0.1:8000/theme?dark'
curl -b jar http://127.0.0.1:8000/
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 40
Connection: keep-alive
Set-Cookie: theme=dark; Path=/; Max-Age=31536000; SameSite=Lax
<p>Theme: dark. <a href="/">Back</a></p>
<body class="dark"><p>Current theme: dark</p></body>
home does not put the cookie into the page as it arrives: anything that is not dark becomes light. A request with Cookie: theme=<script> gets the light page.
Behind HTTPS, a preference that only this site should send:
req.cookies.set("layout", "compact", 31536000, HTTP_COOKIE_SECURE | HTTP_COOKIE_STRICT)
Set-Cookie: layout=compact; Path=/; Max-Age=31536000; HttpOnly; SameSite=Strict; Secure
Validation
set returns -1 and sends nothing when the name is not a valid token, or when the value could break the header:
- a name must not be empty, and must not contain spaces, control characters, bytes above 126 or
( ) < > @ , ; : \ " / [ ] ? = { }; - a value must not contain spaces, control characters, bytes above 126,
",,,;or\. The empty value is valid.
A value copied from the request therefore cannot add headers to the response. Check the result when the value comes from the client:
def remember(self: HttpServer, req: HttpRequest) -> str:
req.content_type = "text/plain; charset=utf-8"
if req.cookies.set("last_search", req.getQuery(), 86400, 0) < 0:
req.status = 400
return "not stored\n"
return "stored\n"
curl 'http://127.0.0.1:8000/remember?tryc+compiler'
curl 'http://127.0.0.1:8000/remember?a;b'
stored
not stored
To keep free text in a cookie, encode it first (hex, base64url) and decode it when you read it back.
A client can send any cookie with any value. Do not store in a cookie anything the server must trust, such as a user id or a role: store a random identifier there and keep the data on the server. libstd/http/session does exactly that. Check every value you read before you use it, as home does above.
When sessions are on, the cookie named HTTP_SESSION_COOKIE (sid) belongs to libstd/http/session, which sets and deletes it. Routes can read it, but should not set or remove it themselves: use req.sessionDestroy() to end a session.
Constants
| Name | Value | Meaning |
|---|---|---|
HTTP_MAX_COOKIES | 50 | Most cookies read from a request; the others are ignored. |
HTTP_COOKIE_SECURE | 1 | Flag of Cookies.set: adds Secure. |
HTTP_COOKIE_SCRIPT | 2 | Flag of Cookies.set: leaves out HttpOnly. |
HTTP_COOKIE_STRICT | 4 | Flag of Cookies.set: SameSite=Strict instead of Lax. |
HTTP_SESSION_COOKIE | "sid" | Name of the cookie that carries the session id. |
Classes
The cookies of one request. incoming maps each name the client sent to its value. outgoing maps each name written by set or remove to its Set-Cookie line, sent with the response. Every HttpRequest contains one, req.cookies.
incoming Sdict
outgoing Sdict
get &CookiesGet
has &CookiesHas
set &CookiesSet
remove &CookiesRemoveFunctions
Creates an empty set of cookies. Not needed in routes, which use req.cookies.
req.cookies.get(name): the value of a cookie the client sent, "" if it did not send it.req.cookies.has(name): 1 if the client sent the cookie, even with an empty value, 0 otherwise.req.cookies.set(name, value, max_age, flags): sends a cookie with the response, with Path=/, HttpOnly and SameSite=Lax unless flags says otherwise. A negative max_age makes a session cookie, and 0 deletes the cookie. Returns 0, or -1 if the name or the value is not valid; nothing is sent in that case.req.cookies.remove(name): asks the client to delete a cookie (Max-Age=0, Path=/, matching the cookies written by set). Returns 0, or -1 if the name is not valid.Internal helpers
Used by the functions above and by libstd/http; not meant to be called directly.
- def http_cookies_init(self: Cookies) -> None
- def http_cookie_valid_name(name: str) -> int
- def http_cookie_valid_value(value: str) -> int
- def http_cookies_parse(self: Cookies, header: str) -> None
- def http_set_cookie_lines(self: Cookies) -> str