Cookies, sessions and CORS
GuidesCookies, sessions, and what Spindle checks on a request before your route runs.
Reading and setting cookies
Section titled “Reading and setting cookies”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$ curl -i -c jar -b jar localhost:8080/HTTP/1.1 200 OKcontent-type: text/plain; charset=utf-8set-cookie: visits=1; Path=/; HttpOnly; SameSite=Lax...
Visit number 1.
$ curl -c jar -b jar localhost:8080/Visit number 2.Cookie.optionalreads it (Nonewhen absent) andCookie.requiredrefuses 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.makedefaults toPath=/; HttpOnly; SameSite=Lax. A plain cookie lasts until the browser closes unless you give~max_age_s(seconds); a signed or encrypted one is givenMax-Agefrom its own~max_age(below).Cookie.clearremoves one.- Spindle adds
Secureitself on every host except a loopback one (localhost,127.0.0.1,::1), where Safari would silently drop aSecurecookie sent over plain http. Behind a proxy that ends TLS, list the proxy in~trusted_proxiesso that its word that the browser usedhttpsis 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 writtentheme=Kim%20Li. A word, a tag or a token keeps its spelling, so a script readingdocument.cookiesees it as written, and decodes the rest withdecodeURIComponent.
Signed and encrypted cookies
Section titled “Signed and encrypted cookies”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
~keysstops it before it listens, naming the route; one that only sets such a cookie is answered500, logged. A test gives its own:Spindle.Test.app ~keys routes. Key.of_secretanswersErrorfor a secret under 32 bytes. Read the secret yourself, at startup.- Rotating a key:
Key.ring newest retiredsigns withnewestand 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_ageis required, anMtime.Span.t. The server checks it on every read, not only the browser, so a copied cookie stops working when it expires.Cookie.makewrites it asMax-Age, rounded up to whole seconds; passing~max_age_stomakecan 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.verifyandKey.seal/Key.unsealdo the same for anything else, such as a token in a link; a handler reads the server’s ring asSpindle.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.
Sessions
Section titled “Sessions”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$ curl -c jar -b jar -X POST localhost:8080/sign-in/kimSigned in.
$ curl -c jar -b jar localhost:8080/meYou are kim.
$ curl -c jar -b jar -X POST localhost:8080/sign-outSigned out.
$ curl -c jar -b jar localhost:8080/meNobody 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.
rotateandputend in the same place in either order, androtatewith no session does nothing. -
A session is the request’s. Every use of it in one request is the same session, so what a
putwrote a latergetreads, and the store is asked once. -
A session ends
idleafter it was last used, orabsoluteafter it began, whichever comes first, on the request’s clock. The cookie is namedsessionunless you pass~cookie, and itsMax-Ageisabsolute, 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, orSpindle_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_jsonIts table,
spindle_sessions, is a migration the package installs, applied withrowtype-migrate up --source spindle-sqlite(orspindle-postgres) before the server starts (Databases).
The client’s IP address
Section titled “The client’s IP address”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.
CSRF and CORS
Section titled “CSRF and CORS”-
Cross-site writes are refused by default. A request by any method but
GET,HEADandOPTIONSthat a browser sent from another site is403 cross_origin. Requests from curl, apps and other servers pass.~trusted_originsallows other sites;~check_origin:falseturns the check off. -
Spindle.jsonaccepts only JSON: a body whoseContent-Typeis notapplication/json(orapplication/...+json) is415. -
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" ])routesSpindle answers the preflight itself and names an allowed origin in
Access-Control-Allow-Origin, or answers*underSpindle.Cors.any (), which allows no cookies; an origin you did not allow is told nothing. An allowed origin also passes the forgery check.~allow_headerslists the headers a request may send:authorizationandcontent-typeunless you say otherwise. A page that sends any other header fails the preflight, and the browser says only that the request was blocked.~exposelists the response headers the page’s script may read (none by default).~max_age_sis how long a browser keeps a preflight’s answer (600 seconds).
A route’s
~corsis 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_sitelet api_post = Spindle.post ~cors:app_site~cors:Spindle.Cors.noneon 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. UnderCors.any (), a write from another site passes only with no credential the browser attaches by itself: noCookie, and noAuthorizationin a scheme a browser keeps –Basic,Digest,Negotiate,NTLM. A token the page sets itself, such asAuthorization: Bearer ..., is served.
