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

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.

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 |:

FlagEffect
HTTP_COOKIE_SECUREAdds Secure: the browser sends the cookie only over HTTPS. Use it when the server is behind a TLS proxy.
HTTP_COOKIE_SCRIPTLeaves out HttpOnly, so the page's JavaScript can read the cookie. Never use it for a cookie that identifies a user.
HTTP_COOKIE_STRICTSameSite=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 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.

Cookies come from the client

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.

The session cookie

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

NameValueMeaning
HTTP_MAX_COOKIES50Most cookies read from a request; the others are ignored.
HTTP_COOKIE_SECURE1Flag of Cookies.set: adds Secure.
HTTP_COOKIE_SCRIPT2Flag of Cookies.set: leaves out HttpOnly.
HTTP_COOKIE_STRICT4Flag of Cookies.set: SameSite=Strict instead of Lax.
HTTP_SESSION_COOKIE"sid"Name of the cookie that carries the session id.

Classes

class
Cookies

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 &CookiesRemove

Functions

def Cookies() -> Cookies

Creates an empty set of cookies. Not needed in routes, which use req.cookies.

def CookiesGet(self: Cookies, name: str) -> str
req.cookies.get(name): the value of a cookie the client sent, "" if it did not send it.
def CookiesHas(self: Cookies, name: str) -> int
req.cookies.has(name): 1 if the client sent the cookie, even with an empty value, 0 otherwise.
def CookiesSet(self: Cookies, name: str, value: str, max_age: int, flags: int) -> int
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.
def CookiesRemove(self: Cookies, name: str) -> int
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.