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 using a separate encryption key per cookie, 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 some other session implementations, the session is stored as a plain ruby hash, and does not convert 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.

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

Required Keyword Arguments

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 argument. The secret argument 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.

Optional Keyword Arguments

cookie_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. 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.

env_key

The key in ‘env` where the session should be located. Defaults to "rack.session", the default key for sessions in Rack.

key

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

max_idle_seconds

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.

max_seconds

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.

old_secret

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

pad_size

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

parser

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

:serializer

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

:skip_within

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).

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 by default use the following format:

urlsafe_base64("\1" + random_data + IV + encrypted session data + HMAC)

where:

version

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

random_data

32 bytes, used for generating the per-cookie secret

IV

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

encrypted session data

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

HMAC

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

where:

bitmap

2 bytes in little endian format, lower 12 bits storing number of padding bytes. Bits 13-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.

padding

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

serialized data

>=2 bytes of serialized data in JSON format.

Constants

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, :env_key=>'rack.session'}.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  
SESSION_VERSION_NUM = 'roda.session.version'.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
201 def self.configure(app, opts=OPTS)
202   RodaPlugins.check_supported_opts("the sessions plugin", opts, PLUGIN_ARGUMENTS)
203 
204   if opts.has_key?(:per_cookie_cipher_secret)
205     RodaPlugins.warn("Roda 4 will default to per cookie cipher secrets, remove the per_cookie_cipher_secret argument", uplevel: 1)
206   end
207 
208   if opts.has_key?(:upgrade_from_rack_session_cookie_secret) || opts.has_key?(:upgrade_from_rack_session_cookie_key) || opts.has_key?(:upgrade_from_rack_session_cookie_options)
209     RodaPlugins.warn("Support for upgrading rack session cookie sessions will be removed in Roda 4, remove the upgrade_from_rack_session_cookie_* arguments.", uplevel: 1)
210   end
211 
212   if opts.has_key?(:gzip_over)
213     RodaPlugins.warn("Support for compressing session data will be removed in Roda 4, remove the gzip_over argument.", uplevel: 1)
214   end
215 
216   opts = (app.sessions_opts || {:key => 'roda.session'.freeze, :max_seconds=>86400*30, :max_idle_seconds=>86400*7, :pad_size=>32, :skip_within=>3600, :env_key=>'rack.session'}).merge(opts)
217   config = Config.new(*opts.values_at(*Config.members))
218   co = config.cookie_options = {:httponly=>true, :path=>'/'.freeze, :same_site=>:lax}.merge(config.cookie_options || OPTS).freeze
219   config.remove_cookie_options = co.merge(:max_age=>'0', :expires=>Time.at(0))
220   config.parser ||= app.json_parser
221   config.serializer ||= app.json_serializer
222 
223   opts[:per_cookie_cipher_secret] = true unless opts.has_key?(:per_cookie_cipher_secret)
224 
225   if opts[:upgrade_from_rack_session_cookie_secret]
226     opts[:upgrade_from_rack_session_cookie_key] ||= 'rack.session'
227     rsco = opts[:upgrade_from_rack_session_cookie_options] = Hash[opts[:upgrade_from_rack_session_cookie_options] || OPTS]
228     rsco[:path] ||= co[:path]
229     rsco[:domain] ||= co[:domain]
230   end
231 
232   secret = opts[:secret]
233   config.cipher_secret, config.hmac_secret = split_secret(:secret, secret)
234   if old_secret = opts[:old_secret]
235     config.old_cipher_secret, config.old_hmac_secret = split_secret(:old_secret, old_secret)
236   end
237 
238   case config.pad_size
239   when nil
240     # no changes
241   when Integer
242     raise RodaError, "invalid :pad_size: #{config.pad_size}, must be >=2, < 4096" unless config.pad_size >= 2 && config.pad_size < 4096
243   else
244     raise RodaError, "invalid pad_size argument: #{config.pad_size.inspect}, must be Integer or nil"
245   end
246   
247   app.opts[:sessions] = config.to_h.merge(opts).freeze
248   app.opts[:sessions_config] = config.freeze
249   app.opts[:sessions_convert_symbols] = true unless app.opts.has_key?(:sessions_convert_symbols)
250 end
load_dependencies(app, opts=OPTS, **)
[show source]
    # File lib/roda/plugins/sessions.rb
195 def self.load_dependencies(app, opts=OPTS, **)
196   app.plugin :_base64
197   app.plugin :_json
198 end
split_secret(name, secret)

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

[show source]
    # File lib/roda/plugins/sessions.rb
187 def self.split_secret(name, secret)
188   raise RodaError, "sessions plugin :#{name} option must be a String" unless secret.is_a?(String)
189   raise RodaError, "invalid sessions plugin :#{name} option length: #{secret.bytesize}, must be >=64" unless secret.bytesize >= 64
190   hmac_secret = secret = secret.b
191   cipher_secret = secret.slice!(0, 32)
192   [cipher_secret.freeze, hmac_secret.freeze]
193 end