Sessions
suggest changeHTTP is stateless: every request arrives on its own, and the server has no built-in way to know that two requests came from the same browser. A session gives you that link. The server hands the browser a cookie, the browser sends it back on every request, and the server uses it to find "this user's data": who is logged in, what is in the cart, which flash message to show.
In Ruby web apps, sessions are handled by Rack middleware, so they work the same way in plain Rack, Sinatra, Hanami and Rails. Since Rack 3 the session middleware lives in a separate gem, rack-session:
gem install rack rack-session rack-test sinatra
There are two ways to store a session:
Cookie store (Rack::Session::Cookie) |
Server-side store (Pool, Redis, SQL) |
|
|---|---|---|
| Where the data lives | encrypted inside the cookie | on the server; the cookie holds only a random id |
| Size limit | about 4 KB | effectively none |
| Extra infrastructure | none | memory, Redis, a database table |
| Works across many servers | yes, if they share the secret | yes, if they share the store |
| Revoke a session on the server | not directly | delete the record |
The examples below were run with Ruby 4.0, rack 3.2, rack-session 2.1 and Sinatra 4.2.
Cookies: the building block
A session is built on a cookie, so start with plain cookies. Rack::Response#set_cookie writes a Set-Cookie header, and Rack::Request#cookies reads the cookies the browser sent back:
require 'rack'
require 'rack/mock'
app = lambda do |env|
req = Rack::Request.new(env)
visits = req.cookies['visits'].to_i + 1
res = Rack::Response.new("visit number #{visits}\n")
res.set_cookie('visits', {
value: visits.to_s,
path: '/',
max_age: 60 * 60 * 24 * 30, # 30 days
httponly: true,
secure: true,
same_site: :lax
})
res.finish
end
r1 = Rack::MockRequest.new(app).get('/')
puts r1.body
puts r1.headers['set-cookie']
# The browser sends the cookie back on the next request
r2 = Rack::MockRequest.new(app).get('/', 'HTTP_COOKIE' => 'visits=1')
puts r2.body
visit number 1
visits=1; path=/; max-age=2592000; secure; httponly; samesite=lax
visit number 2
The attributes matter for security:
httponly: truehides the cookie from JavaScript, so an XSS bug can't read it.secure: truesends the cookie only over HTTPS.same_site: :laxstops the browser from sending the cookie on most cross-site requests, which blocks a large class of CSRF attacks.max_age/expiresmake the cookie persistent. Without them it is a "session cookie" that the browser drops when it closes.
A plain cookie is fully under the user's control. Anyone can edit visits=1 to visits=1000, or user_id=42 to user_id=1. Never trust a cookie value unless you have signed or encrypted it.
Signing a cookie by hand
Signing makes tampering detectable. You append an HMAC of the value, computed with a secret only the server knows. The sketch below shows the idea that every session library builds on:
require 'openssl'
require 'base64'
require 'json'
class SignedCookie
def initialize(secret) = @secret = secret
def dump(data)
payload = Base64.urlsafe_encode64(JSON.generate(data), padding: false)
"#{payload}--#{sign(payload)}"
end
def load(cookie)
payload, sig = cookie.to_s.split('--', 2)
return nil unless payload && sig
return nil unless OpenSSL.fixed_length_secure_compare(sign(payload), sig)
JSON.parse(Base64.urlsafe_decode64(payload))
rescue ArgumentError, JSON::ParserError
nil
end
private
def sign(payload) = OpenSSL::HMAC.hexdigest('SHA256', @secret, payload)
end
signer = SignedCookie.new('x' * 64)
cookie = signer.dump({ 'user_id' => 42 })
puts cookie
p signer.load(cookie)
# An attacker edits the payload to become user 1
forged_payload = Base64.urlsafe_encode64('{"user_id":1}', padding: false)
forged = "#{forged_payload}--#{cookie.split('--').last}"
p signer.load(forged)
eyJ1c2VyX2lkIjo0Mn0--403f5ff4961fc1ceada3524e9d94820ed164c70a09a54a5cd9e606071ecc6ff3
{"user_id" => 42}
nil
Two details are easy to get wrong. Compare signatures with a constant-time function (OpenSSL.fixed_length_secure_compare or Rack::Utils.secure_compare), not ==. And remember that a signed cookie is still readable: eyJ1c2VyX2lkIjo0Mn0 is just Base64 for {"user_id":42}. Signing protects integrity but not confidentiality. base64 became a bundled gem in Ruby 3.4, so under Bundler you have to add it to your Gemfile. In practice, use the session middleware below instead of writing your own. See also Cryptography.
Cookie sessions with Rack::Session::Cookie
Rack::Session::Cookie serializes the whole session hash, then encrypts and authenticates it with AES-256 before putting it in the cookie. Your app sees a plain hash in env['rack.session']:
require 'rack'
require 'rack/session'
require 'rack/test'
require 'securerandom'
SECRET = SecureRandom.random_bytes(64) # in production: ENV.fetch('SESSION_SECRET')
counter = lambda do |env|
session = env['rack.session']
session['count'] = session.fetch('count', 0) + 1
[200, { 'content-type' => 'text/plain' }, ["count=#{session['count']}\n"]]
end
app = Rack::Builder.new do
use Rack::Session::Cookie,
key: 'app.session',
secrets: SECRET,
serialize_json: true,
same_site: :lax,
httponly: true,
expire_after: 60 * 60 * 24 * 14 # 14 days
run counter
end
include Rack::Test::Methods
define_method(:app) { app }
get '/'
puts last_response.body
get '/'
puts last_response.body
puts last_response.headers['set-cookie'][0, 70] + '...'
# Tampering with the cookie gives a fresh, empty session
set_cookie 'app.session=garbage'
get '/'
puts last_response.body
count=1
count=2
app.session=Al6jgXyAnkNa8KDGX%2Bv1kztQjaVHYww78M8jmE7sLndCvZHFoQKKODFI...
count=1
Options worth knowing:
secrets:must be at least 64 bytes. Pass an array ([new_secret, old_secret]) to rotate keys. New cookies are encrypted with the first key, and old cookies still decrypt with the others.serialize_json: truestores the session as JSON instead ofMarshal. Only JSON types survive the round trip (symbol keys come back as strings), but a leaked secret can't be turned into remote code execution throughMarshal.load.expire_after:sets the cookie's expiry. Rack refreshes it on every response that writes the session.key:is the cookie name (the default israck.session).
Load the secret from the environment, never from source code, and keep it identical on all servers. Generate one with ruby -rsecurerandom -e 'puts SecureRandom.hex(64)'. If the secret changes, every user is logged out.
The browser drops cookies larger than about 4 KB, so Rack refuses to write them:
require 'rack'
require 'rack/session'
require 'rack/mock'
require 'securerandom'
app = Rack::Session::Cookie.new(
->(env) { env['rack.session']['cart'] = 'x' * 5000; [200, {}, ['ok']] },
secrets: SecureRandom.random_bytes(64)
)
res = Rack::MockRequest.new(app).get('/')
puts "set-cookie present: #{!res.headers['set-cookie'].nil?}"
puts res.errors
set-cookie present: false
Warning! Rack::Session::Cookie data size exceeds 4K.
Warning! Rack::Session::Cookie failed to save session. Content dropped.
Keep cookie sessions small: a user id, a CSRF token, a flash message. Put carts, search results and other bulky data in a database and store only their id in the session.
Sessions in Sinatra
Sinatra wraps the same middleware. enable :sessions turns it on, and session returns the hash. Here is a login flow:
# app.rb
require 'sinatra'
require 'securerandom'
USERS = { 'alice' => 'wonderland' } # use bcrypt-hashed passwords in real code
enable :sessions
set :session_secret, ENV.fetch('SESSION_SECRET') { SecureRandom.hex(64) }
set :sessions, key: 'myapp.session', same_site: :lax, httponly: true,
expire_after: 60 * 60 * 8 # 8 hours
helpers do
def current_user = session[:user]
def require_login!
halt 401, "please log in\n" unless current_user
end
end
post '/login' do
user, password = params.values_at('user', 'password')
halt 403, "bad credentials\n" unless USERS[user] && Rack::Utils.secure_compare(USERS[user], password.to_s)
# new session id after login prevents session fixation
request.session_options[:renew] = true
session[:user] = user
session[:logged_in_at] = Time.now.to_i
"welcome, #{user}\n"
end
get '/profile' do
require_login!
"profile of #{current_user}\n"
end
post '/logout' do
session.clear
"bye\n"
end
A test with rack-test, which keeps a cookie jar between requests the way a browser does:
# test_app.rb
ENV['APP_ENV'] = 'test'
require 'minitest/autorun'
require 'rack/test'
require_relative 'app'
class SessionTest < Minitest::Test
include Rack::Test::Methods
def app = Sinatra::Application
def login(password = 'wonderland')
post '/login', user: 'alice', password: password
end
def test_profile_requires_login
get '/profile'
assert_equal 401, last_response.status
end
def test_bad_password
login('nope')
assert_equal 403, last_response.status
end
def test_login_then_profile
login
get '/profile'
assert_equal "profile of alice\n", last_response.body
end
def test_logout_ends_session
login
post '/logout'
get '/profile'
assert_equal 401, last_response.status
end
def test_cookie_flags
login
cookie = last_response.headers['set-cookie']
assert_match(/httponly/i, cookie)
assert_match(/samesite=lax/i, cookie)
end
end
5 runs, 8 assertions, 0 failures, 0 errors, 0 skips
Some notes on the app:
request.session_options[:renew] = truegives the session a new id on login. This defeats session fixation, where an attacker plants a known session id in the victim's browser before they log in. Renew on every privilege change: login, logout, switching to an admin role.- With the cookie store, logout is
session.clear. That writes an empty session back to the browser. Don't usesession_options[:drop] = truewith the cookie store: it skips writing the cookie, so the browser keeps the old, logged-in one. - Sinatra's default session coder is
Marshal, so symbol keys likesession[:user]work. Addserialize_json: trueto the:sessionshash if you prefer JSON, and switch to string keys. - Without
set :session_secret, Sinatra generates a random secret on each boot. Sessions then break whenever the app restarts or runs on more than one process.
For real password checks, use bcrypt as shown in Password hashing and Authentication.
The revocation problem
A cookie session is self-contained: any copy of a valid cookie works until it expires, even after the user clicks "log out". A server-side store doesn't have this weakness, because logout deletes the record that the cookie points to:
require 'rack'
require 'rack/session'
require 'rack/test'
require 'securerandom'
# A tiny app: POST /login, POST /logout, GET /me
APP = lambda do |env|
req = Rack::Request.new(env)
case [req.request_method, req.path_info]
in ['POST', '/login']
req.session_options[:renew] = true
req.session['user'] = 'alice'
[200, {}, ["logged in\n"]]
in ['POST', '/logout']
req.session.clear
req.session_options[:drop] = true
[200, {}, ["logged out\n"]]
in ['GET', '/me']
[200, {}, ["user=#{req.session['user'].inspect}\n"]]
end
end
def replay_after_logout(store, **opts)
app = Rack::Builder.new do
use store, key: 'sid', **opts
run APP
end
browser = Rack::Test::Session.new(Rack::MockSession.new(app))
browser.post '/login'
stolen = browser.last_response.headers['set-cookie'][/sid=[^;]+/]
browser.post '/logout'
# an attacker who copied the cookie before logout replays it
attacker = Rack::Test::Session.new(Rack::MockSession.new(app))
attacker.get '/me', {}, 'HTTP_COOKIE' => stolen
puts "#{store.name.ljust(24)} #{attacker.last_response.body}"
end
replay_after_logout(Rack::Session::Cookie, secrets: SecureRandom.random_bytes(64))
replay_after_logout(Rack::Session::Pool)
Rack::Session::Cookie user="alice"
Rack::Session::Pool user=nil
With Rack::Session::Pool the cookie holds only a random session id, and the data stays in a hash in server memory. Pool is fine for development and single-process apps. It loses every session on restart and isn't shared between processes.
If you keep cookie sessions but need "log out everywhere" (after a password change, for example), store a per-user version number in the session and in the database, and bump it to invalidate every existing cookie:
User = Struct.new(:id, :name, :session_version)
USERS = { 1 => User.new(1, 'alice', 1) }
def log_in(session, user)
session['user_id'] = user.id
session['ver'] = user.session_version
end
def current_user(session)
user = USERS[session['user_id']]
return nil unless user && session['ver'] == user.session_version
user
end
def log_out_everywhere(user) = user.session_version += 1
laptop = {}
phone = {}
log_in(laptop, USERS[1])
log_in(phone, USERS[1])
puts current_user(phone)&.name.inspect
log_out_everywhere(USERS[1]) # e.g. after a password change
puts current_user(phone)&.name.inspect
puts current_user(laptop)&.name.inspect
"alice"
nil
nil
A custom server-side store
To keep sessions in Redis, Memcached or SQL, subclass Rack::Session::Abstract::PersistedSecure and implement three methods. Gems such as redis-session-store and activerecord-session_store do exactly this. The example below uses an in-memory key-value store with TTLs as a stand-in for Redis:
require 'rack'
require 'rack/session/abstract/id'
require 'rack/test'
require 'json'
# Stand-in for Redis/Memcached/SQL: key -> [json, expires_at]
class KVStore
def initialize
@data = {}
@lock = Mutex.new
end
def set(key, value, ttl:)
@lock.synchronize { @data[key] = [value, Time.now + ttl] }
end
def get(key)
@lock.synchronize do
value, expires_at = @data[key]
return nil unless value
if Time.now > expires_at
@data.delete(key)
return nil
end
value
end
end
def del(key) = @lock.synchronize { @data.delete(key) }
def keys = @lock.synchronize { @data.keys }
end
class KVSessionStore < Rack::Session::Abstract::PersistedSecure
def initialize(app, store:, ttl: 3600, **options)
super(app, options)
@store = store
@ttl = ttl
end
# Return [sid, session_hash]; create a new sid when none is valid.
def find_session(_req, sid)
if sid && (json = @store.get(key_for(sid)))
[sid, JSON.parse(json)]
else
[generate_sid, {}]
end
end
# Return the sid on success, false on failure.
def write_session(_req, sid, session, _options)
@store.set(key_for(sid), JSON.generate(session), ttl: @ttl)
sid
end
# Return a fresh sid, or nil when the session is dropped.
def delete_session(_req, sid, options)
@store.del(key_for(sid))
generate_sid unless options[:drop]
end
private
# Store under the hashed id, so a leaked store does not leak cookie values.
def key_for(sid) = "session:#{sid.private_id}"
end
kv = KVStore.new
app = Rack::Builder.new do
use KVSessionStore, store: kv, ttl: 1800, key: 'sid', httponly: true, same_site: :lax
run lambda { |env|
req = Rack::Request.new(env)
req.session_options[:renew] = true if req.path_info == '/login'
req.session['hits'] = req.session.fetch('hits', 0) + 1
[200, {}, ["hits=#{req.session['hits']}\n"]]
}
end
browser = Rack::Test::Session.new(Rack::MockSession.new(app))
sid = -> { browser.last_response.headers['set-cookie'].to_s[/sid=([^;]+)/, 1] }
browser.get '/'
puts browser.last_response.body, "cookie sid: #{sid.call[0, 20]}..."
before = sid.call
browser.get '/login'
puts browser.last_response.body, "cookie sid: #{sid.call[0, 20]}..."
puts "sid changed on login: #{before != sid.call}"
puts "keys in store: #{kv.keys.size}"
puts "stored as: #{kv.keys.first[0, 22]}..."
hits=1
cookie sid: 7705cca23394c338c95b...
hits=2
cookie sid: 486cc38ed65fdd20ec46...
sid changed on login: true
keys in store: 1
stored as: session:2::43a91367fda...
What the code shows:
sidis aRack::Session::SessionId.sid.public_idis the random value in the cookie, andsid.private_idis a SHA-256 hash of it (prefixed with2::). Key records byprivate_id, so that someone who can read your Redis or sessions table can't use the keys as cookies.find_sessionmust always return a usable[sid, hash]pair, creating a new id when the cookie is missing, unknown or expired.delete_sessionruns on:renew(it must return a new sid) and on:drop(it returnsnil). Here:dropreally does end the session, because the data is gone from the store.- The TTL in the store gives you server-side expiry that a user can't extend by editing the cookie's
expiresattribute.
Flash messages and timeouts
A flash is a message that survives exactly one redirect ("Saved!", "Wrong password"). It is simply a session entry that you delete when you read it. Timeouts are timestamps in the session that a before filter checks:
ENV['APP_ENV'] = 'test'
require 'sinatra/base'
require 'rack/test'
require 'securerandom'
class App < Sinatra::Base
IDLE_TIMEOUT = 30 * 60 # 30 minutes without a request
ABSOLUTE_TIMEOUT = 12 * 60 * 60 # 12 hours after login
enable :sessions
set :session_secret, SecureRandom.hex(64)
helpers do
# flash: a value that survives exactly one redirect
def flash(type, message) = session[:flash] = { type => message }
def take_flash = session.delete(:flash)
end
before do
now = Time.now.to_i
if session[:user]
idle = now - session[:seen_at].to_i > IDLE_TIMEOUT
stale = now - session[:logged_in_at].to_i > ABSOLUTE_TIMEOUT
if idle || stale
session.clear
flash :notice, 'Your session expired, please log in again.'
end
end
session[:seen_at] = now
end
post '/login' do
request.session_options[:renew] = true
session[:user] = params[:user]
session[:logged_in_at] = Time.now.to_i
flash :success, "Welcome back, #{params[:user]}!"
redirect '/'
end
get '/' do
msg = take_flash&.map { |type, text| "[#{type}] #{text}" }&.first
"#{msg || '(no flash)'} | user=#{session[:user].inspect}\n"
end
# test-only helper to simulate time passing
post '/age' do
session[:seen_at] -= Integer(params[:seconds])
'ok'
end
end
browser = Rack::Test::Session.new(Rack::MockSession.new(App))
browser.post '/login', user: 'alice'
puts browser.last_response.status
browser.follow_redirect!
print browser.last_response.body
browser.get '/'
print browser.last_response.body
browser.post '/age', seconds: 31 * 60
browser.get '/'
print browser.last_response.body
302
[success] Welcome back, alice! | user="alice"
(no flash) | user="alice"
[notice] Your session expired, please log in again. | user=nil
Use two timeouts. The idle timeout ends sessions that were abandoned on a shared computer. The absolute timeout puts an upper bound on how long a stolen cookie stays useful. Both are checked on the server against values inside the encrypted session, so the client can't extend them.
Tips
- Store identifiers, not objects. Put
session[:user_id] = user.idin the session and load the user from the database on each request, so changes (a ban, a new role) take effect immediately. - Always set
httponly,same_site: :lax(or:strict) and, in production,secure: true. Serve the whole site over HTTPS. SameSiteisn't complete CSRF protection. For forms, also use a CSRF token, for exampleRack::Protection::AuthenticityToken(use Rack::Protection::AuthenticityTokenin Sinatra). See Application security.- Renew the session id on login and logout, and enforce idle and absolute timeouts on the server.
- Prefer JSON serialization for sessions.
Marshalturns a leaked secret into code execution. - Rotate secrets by putting the new one first in the
secrets:array and removing the old one once every cookie encrypted with it has expired. - For stateless JSON APIs, a bearer token (see Authentication and REST APIs) is usually a better fit than a cookie session.