Skip to content

Cookies, sessions and CORS

Cookies, sessions, and what Spindle checks on a request before your route runs.

Declare a cookie once, by name and wiretype description, and use it to read and to set. This page counts your visits:

(* A cookie declared once, and used both to read it and to set it: the page
counts your visits. *)
open Spindle.Syntax
let visits = Spindle.Cookie.named "visits" Wiretype.int
let count seen set_cookie =
let n = Option.value seen ~default:0 + 1 in
set_cookie (Spindle.Cookie.make visits n);
Ok (Printf.sprintf "Visit number %d." n)
let routes =
[
Spindle.get Spindle.Path.root Spindle.Returns.text
(let+ seen = Spindle.Cookie.optional visits
and+ set_cookie = Spindle.set_cookie in
count seen set_cookie);
]
let () =
Spindle.Log.setup ();
Eio_main.run @@ fun env -> Spindle.serve env routes
Terminal window
$ curl -i -c jar -b jar localhost:8080/
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
set-cookie: visits=1; Path=/; HttpOnly; SameSite=Lax
...
Visit number 1.
$ curl -c jar -b jar localhost:8080/
Visit number 2.
  • Cookie.optional reads it (None when absent) and Cookie.required refuses without it. A value that does not read – one an older deploy wrote, say – is absent too, so a stale cookie never locks anyone out.
  • Cookie.make defaults to Path=/; HttpOnly; SameSite=Lax. A plain cookie lasts until the browser closes unless you give ~max_age_s (seconds); a signed or encrypted one is given Max-Age from its own ~max_age (below). Cookie.clear removes one.
  • Spindle adds Secure itself on every host except a loopback one (localhost, 127.0.0.1, ::1), where Safari would silently drop a Secure cookie sent over plain http. Behind a proxy that ends TLS, list the proxy in ~trusted_proxies so that its word that the browser used https is believed (below).
  • Any text is a value. What a cookie cannot hold – a space, quote, comma, semicolon, backslash or control character – is percent-encoded, and so is %, and reading decodes it: Cookie.make theme "Kim Li" is written theme=Kim%20Li. A word, a tag or a token keeps its spelling, so a script reading document.cookie sees it as written, and decodes the rest with decodeURIComponent.

Declare a cookie signed (readable, but tamper-proof) or encrypted (sealed), then read and set it as any other. The keys they are sealed under are the server’s, given where it starts, so the cookies and the routes that read them are values like any other:

let prefs =
Spindle.Cookie.encrypted ~max_age:Mtime.Span.(30 * day) "prefs" prefs_json
let who =
Spindle.Cookie.signed ~max_age:Mtime.Span.(8 * hour) "who" Wiretype.string
let () =
match Sys.getenv_opt "COOKIE_SECRET" with
| None -> prerr_endline "COOKIE_SECRET is not set."
| Some secret -> (
match Spindle.Key.of_secret secret with
| Ok key ->
Eio_main.run @@ fun env ->
Spindle.serve env ~keys:(Spindle.Key.ring key []) routes
| Error sentence -> prerr_endline sentence)
  • No keys, no start. A route that reads a signed or encrypted cookie in a server given no ~keys stops it before it listens, naming the route; one that only sets such a cookie is answered 500, logged. A test gives its own: Spindle.Test.app ~keys routes.
  • Key.of_secret answers Error for a secret under 32 bytes. Read the secret yourself, at startup.
  • Rotating a key: Key.ring newest retired signs with newest and reads with any, so put the new key first and the old one after it.
  • A cookie that fails its signature, its seal or its age is absent (None), never an error.
  • ~max_age is required, an Mtime.Span.t. The server checks it on every read, not only the browser, so a copied cookie stops working when it expires. Cookie.make writes it as Max-Age, rounded up to whole seconds; passing ~max_age_s to make can make that shorter, never longer.
  • A signed or encrypted cookie holds any value its description writes, since what is sent is encoded as base64url, as a plain cookie holds any text, percent-encoded.
  • Key.sign/Key.verify and Key.seal/Key.unseal do the same for anything else, such as a token in a link; a handler reads the server’s ring as Spindle.keys. They use keys derived apart from the cookies’ keys, so nothing you sign or seal with them can ever be passed off as a cookie.

Spindle.Session keeps a visit’s data on the server; its cookie holds only a random id. A session is a dependency: a route reads it, and is handed the session its request’s cookie names.

(* A session kept on the server: signing in keeps who you are, the page says
it back, and signing out ends it. The cookie holds only a random id.
Signing in rotates the id, so one somebody planted in the browser before
signs nobody in after; signing out deletes the session, so a copy of the
cookie signs nobody in either.
curl -c jar -b jar -X POST localhost:8080/sign-in/kim
curl -c jar -b jar localhost:8080/me
curl -c jar -b jar -X POST localhost:8080/sign-out *)
open Spindle.Syntax
type visit = { user : string } [@@deriving wiretype]
(* Kept in this process's memory, and in the database with
Spindle_sqlite.Session.store or Spindle_postgres.Session.store. *)
let session =
Spindle.Session.create
~store:(Spindle.Dep.return (Spindle.Session.memory ()))
~idle:Mtime.Span.(14 * day)
~absolute:Mtime.Span.(90 * day)
visit_json
let user = Spindle.Path.string "user"
let routes =
[
Spindle.post
Spindle.Path.(s "sign-in" / user)
Spindle.Returns.text
(let+ user = Spindle.param user and+ session = session in
let* () = Spindle.Session.rotate session in
let* () = Spindle.Session.put session { user } in
Ok "Signed in.\n");
Spindle.get
Spindle.Path.(s "me")
Spindle.Returns.text
(let+ session = session in
let* visit = Spindle.Session.get session in
match visit with
| Some { user } -> Ok (Printf.sprintf "You are %s.\n" user)
| None -> Ok "Nobody is signed in.\n");
Spindle.post
Spindle.Path.(s "sign-out")
Spindle.Returns.text
(let+ session = session in
let* () = Spindle.Session.destroy session in
Ok "Signed out.\n");
]
let () =
Spindle.Log.setup ();
Eio_main.run @@ fun env -> Spindle.serve env routes
Terminal window
$ curl -c jar -b jar -X POST localhost:8080/sign-in/kim
Signed in.
$ curl -c jar -b jar localhost:8080/me
You are kim.
$ curl -c jar -b jar -X POST localhost:8080/sign-out
Signed out.
$ curl -c jar -b jar localhost:8080/me
Nobody is signed in.
Call What it does
get the session’s data, if its cookie names one within both limits
put replaces the data, or starts a session holding it, with its cookie
rotate moves the session to a new id, keeping its data: at sign-in
destroy deletes the session and clears its cookie: sign-out

Each answers a result whose Error is a refusal: a store that fails is a 500, its words in the log and none on the wire, so each call goes on with let* beside the handler’s own.

  • Sign-in rotates, so an id somebody planted in the browser before signs them into nothing after. rotate and put end in the same place in either order, and rotate with no session does nothing.

  • A session is the request’s. Every use of it in one request is the same session, so what a put wrote a later get reads, and the store is asked once.

  • A session ends idle after it was last used, or absolute after it began, whichever comes first, on the request’s clock. The cookie is named session unless you pass ~cookie, and its Max-Age is absolute, rounded up to whole seconds.

  • Ended sessions are swept for you. Nobody comes back for a session that ended, so the first request to read one ten minutes after the last sweep deletes a batch of them, and the next request another while there are more: the store never fills with old visits, and no request waits on more than a batch. Several servers on one database share the work.

  • Where it is kept is ~store, a dependency like any other. Session.memory () lives in one process and ends with it. Spindle_sqlite.Session.store db, or Spindle_postgres.Session.store db, keeps sessions in your database, read through the pool’s resource:

    let session =
    Spindle.Session.create
    ~store:(Spindle_sqlite.Session.store db)
    ~idle:Mtime.Span.(14 * day)
    ~absolute:Mtime.Span.(90 * day)
    visit_json

    Its table, spindle_sessions, is a migration the package installs, applied with rowtype-migrate up --source spindle-sqlite (or spindle-postgres) before the server starts (Databases).

Spindle.client_ip is the address of whoever connected. Behind a reverse proxy, list the proxy in Spindle.serve ~trusted_proxies (addresses or CIDR ranges, such as 10.0.0.0/8; none by default), and the client is the address the proxy forwarded for. ~proxy_header names the header it writes: X_forwarded_for (the default) or Forwarded. The same header gives the host and whether the browser used https.

  • Cross-site writes are refused by default. A request by any method but GET, HEAD and OPTIONS that a browser sent from another site is 403 cross_origin. Requests from curl, apps and other servers pass. ~trusted_origins allows other sites; ~check_origin:false turns the check off.

  • Spindle.json accepts only JSON: a body whose Content-Type is not application/json (or application/...+json) is 415.

  • Another site’s page may call your routes only if you allow it:

    Spindle.serve env
    ~cors:
    (Spindle.Cors.origins ~credentials:true [ "https://app.example.com" ])
    routes

    Spindle answers the preflight itself and names an allowed origin in Access-Control-Allow-Origin, or answers * under Spindle.Cors.any (), which allows no cookies; an origin you did not allow is told nothing. An allowed origin also passes the forgery check.

    • ~allow_headers lists the headers a request may send: authorization and content-type unless you say otherwise. A page that sends any other header fails the preflight, and the browser says only that the request was blocked.
    • ~expose lists the response headers the page’s script may read (none by default).
    • ~max_age_s is how long a browser keeps a preflight’s answer (600 seconds).

    A route’s ~cors is its policy in place of the app’s, so an API can allow a site while the pages allow none. Routes that share a policy share a maker:

    let app_site =
    Spindle.Cors.origins ~credentials:true [ "https://app.example.com" ]
    let api_get = Spindle.get ~cors:app_site
    let api_post = Spindle.post ~cors:app_site

    ~cors:Spindle.Cors.none on a route allows no site under an app that allows one.

    Spindle.Cors.any () takes no ~credentials: a policy letting every site act as the signed-in person does not compile. Under Cors.any (), a write from another site passes only with no credential the browser attaches by itself: no Cookie, and no Authorization in a scheme a browser keeps – Basic, Digest, Negotiate, NTLM. A token the page sets itself, such as Authorization: Bearer ..., is served.