std::sessions
Sessions for server-rendered web apps: a value of the app’s own type that lives across requests in one cookie, encrypted and authenticated with AES-256-GCM, so a browser can neither read nor change it.
with_session is middleware that hands the handler the request’s
session, by type, beside the request. The handler reads
session.value, and to change it builds a new session with
Session.set, Session.clear or Session.add_flash and writes it onto
its response with sessions.write:
fn sign_in(request: Request, session: Session<Visit>) -> Response next = session |> Session.set(Visit{user_id: 7}) |> Session.add_flash("Welcome back.") Response.redirect(request, "/", Status.see_other) |> sessions.write(next) end routes = [ Route.to( "POST /sign-in", sign_in |> sessions.with_session(App.sessions), ), ]
A response that writes nothing leaves the cookie as it is. A cookie that was changed, sealed under a key the store does not hold, or has expired reads as no session, never as an error.
The key comes from a secret the app holds, read in boot:
secret = Map.get(startup.env, "SESSION_SECRET") |> Maybe.to_result("SESSION_SECRET is not set")? store = CookieStore{key: SessionKey.derive(secret)?}
Import with import std::sessions.
Exports
Section titled “Exports”Cross-site request forgery
Section titled “Cross-site request forgery”There is no CSRF token. Put http.cross_origin_protection in the
stack: it refuses a POST, PUT, PATCH or DELETE that a browser
says came from another origin, by Sec-Fetch-Site or else Origin,
which every current browser sends and a page cannot forge. The session
cookie is SameSite=Lax as well, so a browser leaves it off a
cross-site form post even where those headers are missing. Keep GET
and HEAD free of changes, since both checks let them through.
What a cookie session cannot do
Section titled “What a cookie session cannot do”The whole value travels in the cookie, so it must stay under about 4 KB
sealed: write returns 500 for one over 4,096 bytes. Keep an id in the
session and the data in a database. A copy of the cookie stays valid
until it expires, so Session.clear signs one browser out but cannot
revoke a stolen copy; a short max_age or idle_timeout bounds that.
type SessionKey
Section titled “type SessionKey”type SessionKey Bytes
opaque — construction surface is private to its defining module
A 32-byte AES-256 key that seals session cookies. Its Debug shows
nothing of it.
SessionKey.derive
Section titled “SessionKey.derive”fn derive(secret: String) -> Result<SessionKey, String>
type function on SessionKey
The key for secret, which must hold at least 32 bytes, such as 32
random bytes in base64 (openssl rand -base64 32). The key is the
secret’s HMAC-SHA256, so a secret of any length gives a key of the
right size; a shorter secret is an Err, since it would be easy to
guess.
import std::sessions.SessionKey
assert SessionKey.derive("6Zb0mXbJ4f0rS2sQm0JzRj1tYk8H3v9c") |> Result.is_ok()
assert SessionKey.derive("hunter2") == Err("a session secret needs at least 32 bytes, got 7")
SessionKey.inspect
Section titled “SessionKey.inspect”impl Debug for SessionKey
fn inspect(value: SessionKey) -> String
impl Debug.inspect
struct CookieStore
Section titled “struct CookieStore”struct CookieStore key: SessionKey previous_keys: List<SessionKey> = [] name: String = "session" max_age: Duration = Duration.hours(14 * 24) idle_timeout: Maybe<Duration> = None secure: Bool = True path: String = "/" domain: Maybe<String> = None end
Where sessions are kept: one cookie per browser, sealed under key.
The cookie is HttpOnly, SameSite=Lax and, unless secure is
turned off, Secure.
CookieStore.inspect
Section titled “CookieStore.inspect”impl Debug for CookieStore
fn inspect(value: CookieStore) -> String
impl Debug.inspect
struct Session
Section titled “struct Session”struct Session<T> value: Maybe<T> flash: List<String> state: SessionState end
A request’s session: value, the app’s T, or None when the
request carried no session, and the flash messages the previous
response left for this one. The functions on Session build a changed
session, and sessions.write puts it on a response.
Session.new
Section titled “Session.new”fn new<T>(store: CookieStore) -> Session<T>
type function on Session
An empty session in store, for calling a handler that takes a
session directly in a test. with_session makes the session a
handler is given.
import std::sessions.{CookieStore, Session, SessionKey}
store = CookieStore{key: SessionKey.derive("a test secret of 32 bytes or more")!}
session: Session<Int> = Session.new(store) |> Session.set(7)
assert session.value == Some(7)
Session.set
Section titled “Session.set”fn set<T>(session: Session<T>, value: T) -> Session<T>
type function on Session
The session holding value. A session that held none starts its
max_age now.
Session.clear
Section titled “Session.clear”fn clear<T>(session: Session<T>) -> Session<T>
type function on Session
The session holding no value, as at signing out. Written, it deletes the cookie, unless it carries a flash message.
Session.add_flash
Section titled “Session.add_flash”fn add_flash<T>(session: Session<T>, message: String) -> Session<T>
type function on Session
The session with message added to the flash messages the next
request reads.
Session.renew
Section titled “Session.renew”fn renew<T>(session: Session<T>) -> Session<T>
type function on Session
The session with its max_age started again now, as at signing in
when a session already held a value.
Session.inspect
Section titled “Session.inspect”impl Debug for Session<T>
fn inspect<T>(value: Session<T>) -> String where T: Debug
impl Debug.inspect
struct SessionState
Section titled “struct SessionState”struct SessionState
opaque — construction surface is private to its defining module
What a Session carries besides its value: its store, when it began
and was last written, and the flash messages to write.
SessionState.inspect
Section titled “SessionState.inspect”impl Debug for SessionState
fn inspect(value: SessionState) -> String
impl Debug.inspect
sessions.with_session
Section titled “sessions.with_session”fn with_session<T>(handler: (Request, Session<T>) -> ToResponse, store: CookieStore) -> (Request) -> Response where T: ToJson and FromJson
Middleware that reads the request’s session from its cookie and hands
it to handler. The cookie is written only when the response says so
with write, or to take away flash messages this request read, to move
an idle timeout along, or to delete a cookie that did not open.
import std::http.{Body, Method, Request, Response}
import std::http::testing
import std::sessions.{self, CookieStore, Session, SessionKey}
store = CookieStore{key: SessionKey.derive("a test secret of 32 bytes or more")!}
count = fn _: Request, session: Session<Int> ->
n = Maybe.with_default(session.value, 0) + 1
Response{body: Body.Text("${n}")} |> sessions.write(Session.set(session, n))
end
app = count |> sessions.with_session(store)
first = app(testing.request(Method.Get, "/"))
assert Response.text(first) == Ok("1")
cookie = List.first(Response.cookies(first))!
assert cookie.http_only and cookie.secure
again = Request.add_cookie(testing.request(Method.Get, "/"), cookie)
assert Response.text(app(again)) == Ok("2")
sessions.write
Section titled “sessions.write”fn write<T>(response: Response, session: Session<T>) -> Response where T: ToJson
response with a Set-Cookie header that holds session, in place
of any the response already sets for the session’s cookie. A session
with no value and no flash message deletes the cookie. A sealed cookie
over 4,096 bytes gets 500 Internal Server Error, since a
browser would drop it.
import std::http.Response
import std::sessions.{self, CookieStore, Session, SessionKey}
store = CookieStore{key: SessionKey.derive("a test secret of 32 bytes or more")!, secure: False}
session: Session<String> = Session.new(store)
saved = sessions.write(Response{}, Session.set(session, "ada"))
cookie = List.first(Response.cookies(saved))!
assert cookie.name == "session" and cookie.path == Some("/") and not cookie.secure
cleared = sessions.write(Response{}, Session.clear(session))
assert Headers.get(cleared.headers, "Set-Cookie")
== Some("session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax")