module Roda::RodaPlugins::Sessions

  1. lib/roda/plugins/sessions.rb

The sessions plugin adds support for sessions using cookies. It is the recommended way to support sessions in Roda applications.

The session cookies are encrypted with AES-256-CTR and then signed with HMAC-SHA-256. By default, session data is padded to reduce information leaked based on the session size.

Sessions are serialized via JSON, so session information should only store data that allows roundtrips via JSON (String, Integer, Float, Array, Hash, true, false, and nil). In particular, note that Symbol does not round trip via JSON, so symbols should not be used in sessions when this plugin is used. This plugin sets the :sessions_convert_symbols application option to true if it hasn't been set yet, for better integration with plugins that can use either symbol or string session or flash keys. Unlike Rack::Session::Cookie, the session is stored as a plain ruby hash, and does not convert all keys to strings.

All sessions are timestamped and session expiration is enabled by default, with sessions being valid for 30 days maximum and 7 days since last use by default. Session creation time is reset whenever the session is empty when serialized and also whenever clear_session is called while processing the request.

Session secrets can be rotated. See options below.

The sessions plugin can transparently upgrade sessions from Rack::Session::Cookie if the default Rack::Session::Cookie coder and HMAC are used, see options below. It is recommended to only enable transparent upgrades for a brief transition period, and remove support for them once old sessions have converted or timed out.

If the final cookie is too large (>=4096 bytes), a Roda::RodaPlugins::Sessions::CookieTooLarge exception will be raised.

Required Options

The session cookies this plugin uses are both encrypted and signed, so two separate secrets are used internally. However, for ease of use, these secrets are combined into a single :secret option. The :secret option must be a string of at least 64 bytes and should be randomly generated. The first 32 bytes are used as the secret for the cipher, any remaining bytes are used for the secret for the HMAC.

Other Options


Any cookie options to set on the session cookie. By default, uses httponly: true, path: '/', same_site: :lax so that the cookie is not accessible to javascript, allowed for all paths, and will not be used for cross-site non-GET requests that. If the :secure option is not present in the hash, then secure: true is also set if the request is made over HTTPS. If this option is given, it will be merged into the default cookie options.


For session data over this many bytes, compress it with the deflate algorithm (default: nil, so never compress). Note that compression should not be enabled if you are storing data in the session derived from user input and also storing sensitive data in the session.


The cookie name to use (default: 'roda.session')


The maximum number of seconds to allow for total session lifetime, starting with when the session was originally created. Default is 86400*30 (30 days). Can be set to nil to disable session lifetime checks.


The maximum number of seconds to allow since the session was last updated. Default is 86400*7 (7 days). Can be set to nil to disable session idleness checks.


The previous secret to use, allowing for secret rotation. Must be a string of at least 64 bytes if given.


Pad session data (after possible compression, before encryption), to a multiple of this many bytes (default: 32). This can be between 2-4096 bytes, or nil to disable padding.


The parser for the serialized session data (default: JSON.method(:parse)).


The serializer for the session data (default :to_json.to_proc).


If the last update time for the session cookie is less than this number of seconds from the current time, and the session has not been modified, do not set a new session cookie (default: 3600).


The cookie name to use for transparently upgrading from Rack::Session:Cookie (defaults to 'rack.session').


The secret for the HMAC-SHA1 signature when allowing transparent upgrades from Rack::Session::Cookie. Using this option is only recommended during a short transition period, and is not enabled by default as it lowers security.


Options to pass when deleting the cookie used by Rack::Session::Cookie after converting it to use the session cookies used by this plugin.

Not a Rack Middleware

Unlike some other approaches to sessions, the sessions plugin does not use a rack middleware, so session information is not available to other rack middleware, only to the application itself, with the session not being loaded from the cookie until the session method is called.

If you need rack middleware to access the session information, then require 'roda/session_middleware' and use RodaSessionMiddleware. RodaSessionMiddleware passes the options given to this plugin.

Session Cookie Cryptography/Format

Session cookies created by this plugin use the following format:

urlsafe_base64(version + IV + auth tag + encrypted session data + HMAC)



1 byte, currently must be 0, other values reserved for future expansion.


16 bytes, initialization vector for AES-256-CTR cipher.

encrypted session data

>=12 bytes of data encrypted with AES-256-CTR cipher, see below.


32 bytes, HMAC-SHA-256 of all preceding data plus cookie key (so that a cookie value for a different key cannot be used even if the secret is the same).

The encrypted session data uses the following format:

bitmap + creation time + update time + padding + serialized data



2 bytes in little endian format, lower 12 bits storing number of padding bytes, 13th bit storing whether serialized data is compressed with deflate. Bits 14-16 reserved for future expansion.

creation time

4 byte integer in unsigned little endian format, storing unix timestamp since session initially created.

update time

4 byte integer in unsigned little endian format, storing unix timestamp since session last updated.


>=0 padding bytes specified in bitmap, filled with random data, can be ignored.

serialized data

>=2 bytes of serialized data in JSON format. If the bitmap indicates deflate compression, this contains the deflate compressed data.


Public Class

  1. configure
  2. split_secret


DEFAULT_COOKIE_OPTIONS = {:httponly=>true, :path=>'/'.freeze, :same_site=>:lax}.freeze  
DEFAULT_OPTIONS = {:key => 'roda.session'.freeze, :max_seconds=>86400*30, :max_idle_seconds=>86400*7, :pad_size=>32, :gzip_over=>nil, :skip_within=>3600}.freeze  
DEFLATE_BIT = 0x1000  
PADDING_MASK = 0x0fff  
SESSION_CREATED_AT = 'roda.session.created_at'.freeze  
SESSION_DELETE_RACK_COOKIE = 'roda.session.delete_rack_session_cookie'.freeze  
SESSION_SERIALIZED = 'roda.session.serialized'.freeze  
SESSION_UPDATED_AT = 'roda.session.updated_at'.freeze  

Public Class methods

configure (app, opts=OPTS)

Configure the plugin, see Sessions for details on options.

[show source]
    # File lib/roda/plugins/sessions.rb
161 def self.configure(app, opts=OPTS)
162   plugin_opts = opts
163   opts = (app.opts[:sessions] || DEFAULT_OPTIONS).merge(opts)
164   co = opts[:cookie_options] = DEFAULT_COOKIE_OPTIONS.merge(opts[:cookie_options] || OPTS).freeze
165   opts[:remove_cookie_options] = co.merge(:max_age=>'0', :expires=>
166   opts[:parser] ||= app.opts[:json_parser] || JSON.method(:parse)
167   opts[:serializer] ||= app.opts[:json_serializer] || :to_json.to_proc
169   if opts[:upgrade_from_rack_session_cookie_secret]
170     opts[:upgrade_from_rack_session_cookie_key] ||= 'rack.session'
171     rsco = opts[:upgrade_from_rack_session_cookie_options] = Hash[opts[:upgrade_from_rack_session_cookie_options] || OPTS]
172     rsco[:path] ||= co[:path]
173     rsco[:domain] ||= co[:domain]
174   end
176   opts[:cipher_secret], opts[:hmac_secret] = split_secret(:secret, opts[:secret])
177   opts[:old_cipher_secret], opts[:old_hmac_secret] = (split_secret(:old_secret, opts[:old_secret]) if opts[:old_secret])
179   case opts[:pad_size]
180   when nil
181     # no changes
182   when Integer
183     raise RodaError, "invalid :pad_size: #{opts[:pad_size]}, must be >=2, < 4096" unless opts[:pad_size] >= 2 && opts[:pad_size] < 4096
184   else
185     raise RodaError, "invalid :pad_size option: #{opts[:pad_size].inspect}, must be Integer or nil"
186   end
188   app.opts[:sessions] = opts.freeze
189   app.opts[:sessions_convert_symbols] = true unless app.opts.has_key?(:sessions_convert_symbols)
190 end
split_secret (name, secret)

Split given secret into a cipher secret and an hmac secret.

[show source]
    # File lib/roda/plugins/sessions.rb
152 def self.split_secret(name, secret)
153   raise RodaError, "sessions plugin :#{name} option must be a String" unless secret.is_a?(String)
154   raise RodaError, "invalid sessions plugin :#{name} option length: #{secret.bytesize}, must be >=64" unless secret.bytesize >= 64
155   hmac_secret = secret = secret.dup.force_encoding('BINARY')
156   cipher_secret = secret.slice!(0, 32)
157   [cipher_secret.freeze, hmac_secret.freeze]
158 end