roda 3.108.0 → 3.110.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. checksums.yaml +4 -4
  2. data/lib/roda/cache.rb +0 -2
  3. data/lib/roda/opts.rb +22 -0
  4. data/lib/roda/plugins/Integer_matcher_max.rb +1 -1
  5. data/lib/roda/plugins/_add_script_name.rb +14 -0
  6. data/lib/roda/plugins/_json.rb +22 -0
  7. data/lib/roda/plugins/_symbol_class_matchers.rb +8 -10
  8. data/lib/roda/plugins/additional_render_engines.rb +5 -1
  9. data/lib/roda/plugins/additional_view_directories.rb +7 -3
  10. data/lib/roda/plugins/assets.rb +179 -151
  11. data/lib/roda/plugins/assets_preloading.rb +26 -10
  12. data/lib/roda/plugins/autoload_hash_branches.rb +9 -3
  13. data/lib/roda/plugins/autoload_named_routes.rb +9 -3
  14. data/lib/roda/plugins/backtracking_array.rb +2 -2
  15. data/lib/roda/plugins/branch_locals.rb +4 -4
  16. data/lib/roda/plugins/break.rb +2 -2
  17. data/lib/roda/plugins/caching.rb +27 -17
  18. data/lib/roda/plugins/capture_erb.rb +19 -12
  19. data/lib/roda/plugins/chunked.rb +42 -34
  20. data/lib/roda/plugins/class_level_routing.rb +10 -5
  21. data/lib/roda/plugins/class_matchers.rb +14 -7
  22. data/lib/roda/plugins/common_logger.rb +27 -5
  23. data/lib/roda/plugins/conditional_sessions.rb +4 -4
  24. data/lib/roda/plugins/content_for.rb +12 -7
  25. data/lib/roda/plugins/content_security_policy.rb +17 -14
  26. data/lib/roda/plugins/cookie_flags.rb +17 -7
  27. data/lib/roda/plugins/cookies.rb +12 -6
  28. data/lib/roda/plugins/csrf.rb +2 -1
  29. data/lib/roda/plugins/custom_block_results.rb +11 -10
  30. data/lib/roda/plugins/custom_matchers.rb +4 -2
  31. data/lib/roda/plugins/default_headers.rb +4 -7
  32. data/lib/roda/plugins/default_status.rb +1 -0
  33. data/lib/roda/plugins/delay_build.rb +1 -1
  34. data/lib/roda/plugins/delegate.rb +7 -6
  35. data/lib/roda/plugins/direct_call.rb +5 -1
  36. data/lib/roda/plugins/disallow_file_uploads.rb +2 -3
  37. data/lib/roda/plugins/drop_body.rb +3 -6
  38. data/lib/roda/plugins/each_part.rb +23 -29
  39. data/lib/roda/plugins/early_hints.rb +4 -4
  40. data/lib/roda/plugins/empty_root.rb +5 -5
  41. data/lib/roda/plugins/environments.rb +11 -15
  42. data/lib/roda/plugins/erb_h.rb +4 -4
  43. data/lib/roda/plugins/error_email.rb +23 -20
  44. data/lib/roda/plugins/error_handler.rb +28 -34
  45. data/lib/roda/plugins/error_mail.rb +31 -16
  46. data/lib/roda/plugins/exception_page.rb +41 -35
  47. data/lib/roda/plugins/filter_common_logger.rb +6 -4
  48. data/lib/roda/plugins/flash.rb +16 -13
  49. data/lib/roda/plugins/freeze_request_response.rb +24 -0
  50. data/lib/roda/plugins/hash_branch_view_subdir.rb +6 -4
  51. data/lib/roda/plugins/hash_branches.rb +7 -5
  52. data/lib/roda/plugins/hash_paths.rb +7 -5
  53. data/lib/roda/plugins/hash_public.rb +11 -7
  54. data/lib/roda/plugins/hash_public_cache.rb +9 -7
  55. data/lib/roda/plugins/hash_routes.rb +6 -4
  56. data/lib/roda/plugins/heartbeat.rb +6 -2
  57. data/lib/roda/plugins/hmac_paths.rb +9 -3
  58. data/lib/roda/plugins/hooks.rb +13 -10
  59. data/lib/roda/plugins/host_authorization.rb +7 -2
  60. data/lib/roda/plugins/host_routing.rb +7 -2
  61. data/lib/roda/plugins/invalid_request_body.rb +20 -4
  62. data/lib/roda/plugins/ip_from_header.rb +5 -1
  63. data/lib/roda/plugins/json.rb +10 -8
  64. data/lib/roda/plugins/json_parser.rb +26 -12
  65. data/lib/roda/plugins/mail_processor.rb +9 -6
  66. data/lib/roda/plugins/mailer.rb +5 -3
  67. data/lib/roda/plugins/match_affix.rb +6 -1
  68. data/lib/roda/plugins/match_hook_args.rb +7 -5
  69. data/lib/roda/plugins/middleware.rb +13 -7
  70. data/lib/roda/plugins/module_include.rb +1 -1
  71. data/lib/roda/plugins/multi_public.rb +6 -2
  72. data/lib/roda/plugins/multi_route.rb +1 -1
  73. data/lib/roda/plugins/multi_run.rb +13 -17
  74. data/lib/roda/plugins/named_routes.rb +8 -6
  75. data/lib/roda/plugins/named_templates.rb +5 -3
  76. data/lib/roda/plugins/path.rb +16 -14
  77. data/lib/roda/plugins/path_rewriter.rb +8 -5
  78. data/lib/roda/plugins/permissions_policy.rb +21 -19
  79. data/lib/roda/plugins/public.rb +22 -10
  80. data/lib/roda/plugins/recheck_precompiled_assets.rb +30 -8
  81. data/lib/roda/plugins/redirect_http_to_https.rb +6 -3
  82. data/lib/roda/plugins/render.rb +37 -49
  83. data/lib/roda/plugins/render_coverage.rb +6 -3
  84. data/lib/roda/plugins/render_locals.rb +13 -7
  85. data/lib/roda/plugins/request_aref.rb +1 -1
  86. data/lib/roda/plugins/response_content_type.rb +7 -3
  87. data/lib/roda/plugins/route_csrf.rb +7 -2
  88. data/lib/roda/plugins/run_append_slash.rb +5 -1
  89. data/lib/roda/plugins/sec_fetch_site_csrf.rb +6 -2
  90. data/lib/roda/plugins/sessions.rb +164 -139
  91. data/lib/roda/plugins/shape_friendly.rb +3 -1
  92. data/lib/roda/plugins/sinatra_helpers.rb +7 -3
  93. data/lib/roda/plugins/status_handler.rb +5 -3
  94. data/lib/roda/plugins/strip_path_prefix.rb +4 -2
  95. data/lib/roda/plugins/symbol_matchers.rb +11 -6
  96. data/lib/roda/plugins/symbol_views.rb +1 -1
  97. data/lib/roda/plugins/timestamp_public.rb +8 -4
  98. data/lib/roda/plugins/type_routing.rb +9 -5
  99. data/lib/roda/plugins/typecast_params.rb +2 -2
  100. data/lib/roda/plugins/typecast_params_sized_integers.rb +1 -1
  101. data/lib/roda/plugins/unescape_path.rb +22 -4
  102. data/lib/roda/plugins/url_escape.rb +2 -14
  103. data/lib/roda/plugins.rb +34 -0
  104. data/lib/roda/request.rb +8 -7
  105. data/lib/roda/response.rb +9 -7
  106. data/lib/roda/version.rb +1 -1
  107. data/lib/roda.rb +37 -23
  108. metadata +7 -3
@@ -31,6 +31,10 @@ class Roda
31
31
  app.opts[:run_append_slash_redirect] = !!opts[:use_redirects]
32
32
  end
33
33
 
34
+ module ClassMethods
35
+ RodaPlugins.opt_attr_reader(self, :run_append_slash_redirect, name: :run_append_slash_redirect?)
36
+ end
37
+
34
38
  module RequestMethods
35
39
  # Calls the given rack app. If the path matches the root of the app but
36
40
  # does not contain a trailing slash, a trailing slash is appended to the
@@ -39,7 +43,7 @@ class Roda
39
43
  # the redirect approach will not be used.
40
44
  def run(*)
41
45
  if @remaining_path.empty?
42
- if scope.opts[:run_append_slash_redirect] && !(path = self.path).start_with?('//')
46
+ if roda_class.run_append_slash_redirect? && !(path = self.path).start_with?('//')
43
47
  redirect("#{path}/")
44
48
  else
45
49
  @remaining_path += '/'
@@ -69,7 +69,7 @@ class Roda
69
69
  class CsrfFailure < RodaError; end
70
70
 
71
71
  def self.configure(app, opts=OPTS, &block)
72
- options = app.opts[:sec_fetch_site_csrf] = (app.opts[:sec_fetch_site_csrf] || DEFAULTS).merge(opts)
72
+ options = app.opts[:sec_fetch_site_csrf] = (app.sec_fetch_site_csrf_opts || DEFAULTS).merge(opts)
73
73
 
74
74
  allowed_values = options[:allowed_values] = ["same-origin"]
75
75
  allowed_values << "same-site" if opts[:allow_same_site]
@@ -94,6 +94,10 @@ class Roda
94
94
  options.freeze
95
95
  end
96
96
 
97
+ module ClassMethods
98
+ RodaPlugins.opt_attr_reader(self, :sec_fetch_site_csrf, name: :sec_fetch_site_csrf_opts)
99
+ end
100
+
97
101
  module InstanceMethods
98
102
  # Check that the Sec-Fetch-Site header is valid, if the request requires it.
99
103
  # If the header is valid or the request does not require the header, return nil.
@@ -101,7 +105,7 @@ class Roda
101
105
  # if a block is not given, use the plugin :csrf_failure option to determine how to
102
106
  # handle it.
103
107
  def check_sec_fetch_site!(&block)
104
- plugin_opts = self.class.opts[:sec_fetch_site_csrf]
108
+ plugin_opts = self.class.sec_fetch_site_csrf_opts
105
109
  return unless plugin_opts[:check_request_methods].include?(request.request_method)
106
110
 
107
111
  sec_fetch_site = env["HTTP_SEC_FETCH_SITE"]
@@ -10,7 +10,6 @@ rescue OpenSSL::Cipher::CipherError
10
10
  # simplecov:enable
11
11
  end
12
12
 
13
- require 'json'
14
13
  require 'securerandom'
15
14
  require 'zlib'
16
15
  require 'rack/utils'
@@ -30,8 +29,8 @@ class Roda
30
29
  # used in sessions when this plugin is used. This plugin sets the
31
30
  # +:sessions_convert_symbols+ application option to +true+ if it hasn't been set yet,
32
31
  # for better integration with plugins that can use either symbol or string session or
33
- # flash keys. Unlike Rack::Session::Cookie, the session is stored as a plain ruby hash,
34
- # and does not convert all keys to strings.
32
+ # flash keys. Unlike some other session implementations, the session is stored as a plain ruby hash,
33
+ # and does not convert keys to strings.
35
34
  #
36
35
  # All sessions are timestamped and session expiration is enabled by default, with sessions
37
36
  # being valid for 30 days maximum and 7 days since last use by default. Session creation time is
@@ -40,67 +39,43 @@ class Roda
40
39
  #
41
40
  # Session secrets can be rotated. See options below.
42
41
  #
43
- # The sessions plugin can transparently upgrade sessions from versions of Rack::Session::Cookie
44
- # shipped with Rack before Rack 3,
45
- # if the default Rack::Session::Cookie coder and HMAC are used, see options below.
46
- # It is recommended to only enable transparent upgrades for a brief transition period,
47
- # and remove support for them once old sessions have converted or timed out.
48
- #
49
42
  # If the final cookie is too large (>=4096 bytes), a Roda::RodaPlugins::Sessions::CookieTooLarge
50
43
  # exception will be raised.
51
44
  #
52
- # = Required Options
45
+ # = Required Keyword Arguments
53
46
  #
54
47
  # The session cookies this plugin uses are both encrypted and signed, so two separate
55
48
  # secrets are used internally. However, for ease of use, these secrets are combined into
56
- # a single +:secret+ option. The +:secret+ option must be a string of at least 64 bytes
49
+ # a single +secret+ argument. The +secret+ argument must be a string of at least 64 bytes
57
50
  # and should be randomly generated. The first 32 bytes are used as the secret for the
58
51
  # cipher, any remaining bytes are used for the secret for the HMAC.
59
52
  #
60
- # = Other Options
53
+ # = Optional Keyword Arguments
61
54
  #
62
- # :cookie_options :: Any cookie options to set on the session cookie. By default, uses
63
- # <tt>httponly: true, path: '/', same_site: :lax</tt> so that the cookie is not accessible
64
- # to javascript, allowed for all paths, and will not be used for cross-site non-GET requests
65
- # that. If the +:secure+ option is not present in the hash, then
66
- # <tt>secure: true</tt> is also set if the request is made over HTTPS. If this option is
67
- # given, it will be merged into the default cookie options.
68
- # :env_key :: The key in `env` where the session should be located. Defaults to <tt>"rack.session"</tt>, the
69
- # default key for sessions in Rack.
70
- # :gzip_over (deprecated) :: For session data over this many bytes, compress it with the deflate algorithm (default: nil,
71
- # so never compress). Note that compression should not be enabled if you are storing data in
72
- # the session derived from user input and also storing sensitive data in the session.
73
- # :key :: The cookie name to use (default: <tt>'roda.session'</tt>)
74
- # :max_seconds :: The maximum number of seconds to allow for total session lifetime, starting with when
75
- # the session was originally created. Default is <tt>86400*30</tt> (30 days). Can be set to
76
- # +nil+ to disable session lifetime checks.
77
- # :max_idle_seconds :: The maximum number of seconds to allow since the session was last updated.
78
- # Default is <tt>86400*7</tt> (7 days). Can be set to nil to disable session idleness
79
- # checks.
80
- # :old_secret :: The previous secret to use, allowing for secret rotation. Must be a string of at least 64
81
- # bytes if given.
82
- # :pad_size :: Pad session data (after possible compression, before encryption), to a multiple of this
83
- # many bytes (default: 32). This can be between 2-4096 bytes, or +nil+ to disable padding.
84
- # :per_cookie_cipher_secret :: Uses a separate cipher key for every cookie, with the key used generated using
85
- # HMAC-SHA-256 of 32 bytes of random data with the default cipher secret. This
86
- # offers additional protection in case the random initialization vector used when
87
- # encrypting the session data has been reused. Odds of that are 1 in 2**64 if
88
- # initialization vector is truly random, but weaknesses in the random number
89
- # generator could make the odds much higher. Default is +true+.
90
- # :parser :: The parser for the serialized session data (default: <tt>JSON.method(:parse)</tt>).
55
+ # +cookie_options+ :: Any cookie options to set on the session cookie. By default, uses
56
+ # <tt>httponly: true, path: '/', same_site: :lax</tt> so that the cookie is not accessible
57
+ # to javascript, allowed for all paths, and will not be used for cross-site non-GET requests.
58
+ # If the +:secure+ option is not present in the hash, then
59
+ # <tt>secure: true</tt> is also set if the request is made over HTTPS. If this option is
60
+ # given, it will be merged into the default cookie options.
61
+ # +env_key+ :: The key in `env` where the session should be located. Defaults to <tt>"rack.session"</tt>, the
62
+ # default key for sessions in Rack.
63
+ # +key+ :: The cookie name to use (default: <tt>'roda.session'</tt>)
64
+ # +max_idle_seconds+ :: The maximum number of seconds to allow since the session was last updated.
65
+ # Default is <tt>86400*7</tt> (7 days). Can be set to nil to disable session idleness
66
+ # checks.
67
+ # +max_seconds+ :: The maximum number of seconds to allow for total session lifetime, starting with when
68
+ # the session was originally created. Default is <tt>86400*30</tt> (30 days). Can be set to
69
+ # +nil+ to disable session lifetime checks.
70
+ # +old_secret+ :: The previous secret to use, allowing for secret rotation. Must be a string of at least 64
71
+ # bytes if given.
72
+ # +pad_size+ :: Pad session data to a multiple of this many bytes (default: 32). This can be between
73
+ # 2-4096 bytes, or +nil+ to disable padding.
74
+ # +parser+ :: The parser for the serialized session data (default: <tt>JSON.method(:parse)</tt>).
91
75
  # :serializer :: The serializer for the session data (default +:to_json.to_proc+).
92
76
  # :skip_within :: If the last update time for the session cookie is less than this number of seconds from the
93
77
  # current time, and the session has not been modified, do not set a new session cookie
94
78
  # (default: 3600).
95
- # :upgrade_from_rack_session_cookie_key :: The cookie name to use for transparently upgrading from
96
- # Rack::Session:Cookie (defaults to <tt>'rack.session'</tt>).
97
- # :upgrade_from_rack_session_cookie_secret (deprecated) :: The secret for the HMAC-SHA1 signature when allowing
98
- # transparent upgrades from Rack::Session::Cookie. Using this
99
- # option is only recommended during a short transition period,
100
- # and is not enabled by default as it lowers security.
101
- # :upgrade_from_rack_session_cookie_options :: Options to pass when deleting the cookie used by
102
- # Rack::Session::Cookie after converting it to use the session
103
- # cookies used by this plugin.
104
79
  #
105
80
  # = Not a Rack Middleware
106
81
  #
@@ -119,13 +94,9 @@ class Roda
119
94
  #
120
95
  # urlsafe_base64("\1" + random_data + IV + encrypted session data + HMAC)
121
96
  #
122
- # If +:per_cookie_cipher_secret+ option is set to +false+, an older format is used:
123
- #
124
- # urlsafe_base64("\0" + IV + encrypted session data + HMAC)
125
- #
126
97
  # where:
127
98
  #
128
- # version :: 1 byte, currently must be 1 or 0, other values reserved for future expansion.
99
+ # version :: 1 byte, currently must be 1, other values reserved for future expansion.
129
100
  # random_data :: 32 bytes, used for generating the per-cookie secret
130
101
  # IV :: 16 bytes, initialization vector for AES-256-CTR cipher.
131
102
  # encrypted session data :: >=12 bytes of data encrypted with AES-256-CTR cipher, see below.
@@ -139,15 +110,13 @@ class Roda
139
110
  # where:
140
111
  #
141
112
  # bitmap :: 2 bytes in little endian format, lower 12 bits storing number of padding
142
- # bytes, 13th bit storing whether serialized data is compressed with deflate.
143
- # Bits 14-16 reserved for future expansion.
113
+ # bytes. Bits 13-16 reserved for future expansion.
144
114
  # creation time :: 4 byte integer in unsigned little endian format, storing unix timestamp
145
115
  # since session initially created.
146
116
  # update time :: 4 byte integer in unsigned little endian format, storing unix timestamp
147
117
  # since session last updated.
148
118
  # padding :: >=0 padding bytes specified in bitmap, filled with random data, can be ignored.
149
- # serialized data :: >=2 bytes of serialized data in JSON format. If the bitmap indicates
150
- # deflate compression, this contains the deflate compressed data.
119
+ # serialized data :: >=2 bytes of serialized data in JSON format.
151
120
  module Sessions
152
121
  DEFAULT_COOKIE_OPTIONS = {:httponly=>true, :path=>'/'.freeze, :same_site=>:lax}.freeze
153
122
  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
@@ -159,6 +128,56 @@ class Roda
159
128
  SESSION_VERSION_NUM = 'roda.session.version'.freeze
160
129
  SESSION_DELETE_RACK_COOKIE = 'roda.session.delete_rack_session_cookie'.freeze
161
130
 
131
+ %i[
132
+ DEFAULT_COOKIE_OPTIONS
133
+ DEFAULT_OPTIONS
134
+ DEFLATE_BIT
135
+ PADDING_MASK
136
+ SESSION_CREATED_AT
137
+ SESSION_UPDATED_AT
138
+ SESSION_SERIALIZED
139
+ SESSION_VERSION_NUM
140
+ SESSION_DELETE_RACK_COOKIE].each do |sym|
141
+ RodaPlugins.deprecate_constant self, sym
142
+ end
143
+
144
+ PLUGIN_ARGUMENTS = %i[
145
+ cookie_options
146
+ env_key
147
+ gzip_over
148
+ key
149
+ max_idle_seconds
150
+ max_seconds
151
+ old_secret
152
+ pad_size
153
+ parser
154
+ per_cookie_cipher_secret
155
+ serializer
156
+ secret
157
+ skip_within
158
+ upgrade_from_rack_session_cookie_key
159
+ upgrade_from_rack_session_cookie_secret
160
+ upgrade_from_rack_session_cookie_options
161
+ ].freeze
162
+ private_constant :PLUGIN_ARGUMENTS
163
+
164
+ deprecated_plugin_arguments = %i[
165
+ gzip_over
166
+ per_cookie_cipher_secret
167
+ upgrade_from_rack_session_cookie_key
168
+ upgrade_from_rack_session_cookie_secret
169
+ upgrade_from_rack_session_cookie_options
170
+ ]
171
+
172
+ Config = Struct.new(*(PLUGIN_ARGUMENTS - deprecated_plugin_arguments - %i[secret old_secret]),
173
+ :remove_cookie_options,
174
+ :cipher_secret,
175
+ :hmac_secret,
176
+ :old_cipher_secret,
177
+ :old_hmac_secret
178
+ )
179
+ private_constant :Config
180
+
162
181
  # Exception class used when creating a session cookie that would exceed the
163
182
  # allowable cookie size limit.
164
183
  class CookieTooLarge < RodaError
@@ -168,62 +187,81 @@ class Roda
168
187
  def self.split_secret(name, secret)
169
188
  raise RodaError, "sessions plugin :#{name} option must be a String" unless secret.is_a?(String)
170
189
  raise RodaError, "invalid sessions plugin :#{name} option length: #{secret.bytesize}, must be >=64" unless secret.bytesize >= 64
171
- hmac_secret = secret = secret.dup.force_encoding('BINARY')
190
+ hmac_secret = secret = secret.b
172
191
  cipher_secret = secret.slice!(0, 32)
173
192
  [cipher_secret.freeze, hmac_secret.freeze]
174
193
  end
175
194
 
176
- def self.load_dependencies(app, opts=OPTS)
195
+ def self.load_dependencies(app, opts=OPTS, **)
177
196
  app.plugin :_base64
197
+ app.plugin :_json
178
198
  end
179
199
 
180
200
  # Configure the plugin, see Sessions for details on options.
181
201
  def self.configure(app, opts=OPTS)
182
- opts = (app.opts[:sessions] || DEFAULT_OPTIONS).merge(opts)
183
- co = opts[:cookie_options] = DEFAULT_COOKIE_OPTIONS.merge(opts[:cookie_options] || OPTS).freeze
184
- opts[:remove_cookie_options] = co.merge(:max_age=>'0', :expires=>Time.at(0))
185
- opts[:parser] ||= app.opts[:json_parser] || JSON.method(:parse)
186
- opts[:serializer] ||= app.opts[:json_serializer] || :to_json.to_proc
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
187
222
 
188
223
  opts[:per_cookie_cipher_secret] = true unless opts.has_key?(:per_cookie_cipher_secret)
189
- opts[:session_version_num] = opts[:per_cookie_cipher_secret] ? 1 : 0
190
224
 
191
225
  if opts[:upgrade_from_rack_session_cookie_secret]
192
- RodaPlugins.warn("Support for upgrading rack session cookie sessions will be removed in Roda 4.")
193
226
  opts[:upgrade_from_rack_session_cookie_key] ||= 'rack.session'
194
227
  rsco = opts[:upgrade_from_rack_session_cookie_options] = Hash[opts[:upgrade_from_rack_session_cookie_options] || OPTS]
195
228
  rsco[:path] ||= co[:path]
196
229
  rsco[:domain] ||= co[:domain]
197
230
  end
198
231
 
199
- if opts[:gzip_over]
200
- RodaPlugins.warn("Support for compressing session data will be removed in Roda 4.")
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)
201
236
  end
202
237
 
203
- opts[:cipher_secret], opts[:hmac_secret] = split_secret(:secret, opts[:secret])
204
- opts[:old_cipher_secret], opts[:old_hmac_secret] = (split_secret(:old_secret, opts[:old_secret]) if opts[:old_secret])
205
-
206
- case opts[:pad_size]
238
+ case config.pad_size
207
239
  when nil
208
240
  # no changes
209
241
  when Integer
210
- raise RodaError, "invalid :pad_size: #{opts[:pad_size]}, must be >=2, < 4096" unless opts[:pad_size] >= 2 && opts[:pad_size] < 4096
242
+ raise RodaError, "invalid :pad_size: #{config.pad_size}, must be >=2, < 4096" unless config.pad_size >= 2 && config.pad_size < 4096
211
243
  else
212
- raise RodaError, "invalid :pad_size option: #{opts[:pad_size].inspect}, must be Integer or nil"
244
+ raise RodaError, "invalid pad_size argument: #{config.pad_size.inspect}, must be Integer or nil"
213
245
  end
214
246
 
215
- app.opts[:sessions] = opts.freeze
247
+ app.opts[:sessions] = config.to_h.merge(opts).freeze
248
+ app.opts[:sessions_config] = config.freeze
216
249
  app.opts[:sessions_convert_symbols] = true unless app.opts.has_key?(:sessions_convert_symbols)
217
250
  end
218
251
 
252
+ module ClassMethods
253
+ RodaPlugins.opt_attr_reader(self, :sessions, name: :sessions_opts)
254
+ RodaPlugins.opt_attr_reader(self, :sessions_config)
255
+ end
256
+
219
257
  module InstanceMethods
220
258
  # Clear data from the session, and update the request environment
221
259
  # so that the session cookie will use a new creation timestamp
222
260
  # instead of the previous creation timestamp.
223
261
  def clear_session
224
262
  session.clear
225
- env.delete(SESSION_CREATED_AT)
226
- env.delete(SESSION_UPDATED_AT)
263
+ env.delete('roda.session.created_at')
264
+ env.delete('roda.session.updated_at')
227
265
  nil
228
266
  end
229
267
 
@@ -233,7 +271,7 @@ class Roda
233
271
  # update the rack response headers to set the session cookie in
234
272
  # the response.
235
273
  def _roda_after_50__sessions(res)
236
- if res && (session = env[self.class.opts[:sessions][:env_key]])
274
+ if res && (session = env[self.class.sessions_config.env_key])
237
275
  @_request.persist_session(res[1], session)
238
276
  end
239
277
  end
@@ -247,37 +285,35 @@ class Roda
247
285
  # this method stores the session in 'rack.session' in the request environment,
248
286
  # but that does not happen until this method is called.
249
287
  def session
250
- @env[roda_class.opts[:sessions][:env_key]] ||= _load_session
288
+ @env[roda_class.sessions_config.env_key] ||= _load_session
251
289
  end
252
290
 
253
291
  # The time the session was originally created. nil if there is no active session.
254
292
  def session_created_at
255
293
  session
256
- Time.at(@env[SESSION_CREATED_AT]) if @env[SESSION_SERIALIZED]
294
+ Time.at(@env['roda.session.created_at']) if @env['roda.session.serialized']
257
295
  end
258
296
 
259
297
  # The time the session was last updated. nil if there is no active session.
260
298
  def session_updated_at
261
299
  session
262
- Time.at(@env[SESSION_UPDATED_AT]) if @env[SESSION_SERIALIZED]
300
+ Time.at(@env['roda.session.updated_at']) if @env['roda.session.serialized']
263
301
  end
264
302
 
265
- # Persist the session data as a cookie. If transparently upgrading from
266
- # Rack::Session::Cookie, mark the related cookie for expiration so it isn't
267
- # sent in the future.
303
+ # Persist the session data as a cookie.
268
304
  def persist_session(headers, session)
269
- opts = roda_class.opts[:sessions]
305
+ config = roda_class.sessions_config
270
306
 
271
307
  if session.empty?
272
- if env[SESSION_SERIALIZED]
308
+ if env['roda.session.serialized']
273
309
  # If session was submitted and is now empty, remove the cookie
274
- Rack::Utils.delete_cookie_header!(headers, opts[:key], opts[:remove_cookie_options])
310
+ Rack::Utils.delete_cookie_header!(headers, config.key, config.remove_cookie_options)
275
311
  # else
276
312
  # If no session was submitted, and the session is empty
277
313
  # then there is no need to do anything
278
314
  end
279
315
  elsif cookie_value = _serialize_session(session)
280
- cookie = Hash[opts[:cookie_options]]
316
+ cookie = Hash[config.cookie_options]
281
317
  cookie[:value] = cookie_value
282
318
  cookie[:secure] = true if !cookie.has_key?(:secure) && ssl?
283
319
 
@@ -287,7 +323,7 @@ class Roda
287
323
  0
288
324
  end
289
325
 
290
- Rack::Utils.set_cookie_header!(headers, opts[:key], cookie)
326
+ Rack::Utils.set_cookie_header!(headers, config.key, cookie)
291
327
 
292
328
  cookie_size = case set_cookie_after = headers[RodaResponseHeaders::SET_COOKIE]
293
329
  when String
@@ -305,7 +341,8 @@ class Roda
305
341
  end
306
342
  end
307
343
 
308
- if env[SESSION_DELETE_RACK_COOKIE]
344
+ if env['roda.session.delete_rack_session_cookie']
345
+ opts = roda_class.sessions_opts
309
346
  Rack::Utils.delete_cookie_header!(headers, opts[:upgrade_from_rack_session_cookie_key], opts[:upgrade_from_rack_session_cookie_options])
310
347
  end
311
348
 
@@ -317,12 +354,11 @@ class Roda
317
354
  # Load the session by looking for the appropriate cookie, or falling
318
355
  # back to the rack session cookie if configured.
319
356
  def _load_session
320
- opts = roda_class.opts[:sessions]
321
357
  cs = cookies
322
358
 
323
- if data = cs[opts[:key]]
359
+ if data = cs[roda_class.sessions_config.key]
324
360
  _deserialize_session(data)
325
- elsif (key = opts[:upgrade_from_rack_session_cookie_key]) && (data = cs[key])
361
+ elsif (key = roda_class.sessions_opts[:upgrade_from_rack_session_cookie_key]) && (data = cs[key])
326
362
  _deserialize_rack_session(data)
327
363
  end || {}
328
364
  end
@@ -336,11 +372,8 @@ class Roda
336
372
  nil
337
373
  end
338
374
 
339
- # Interpret given cookie data as a Rack::Session::Cookie
340
- # serialized session using the default Rack::Session::Cookie
341
- # hmac and coder.
342
375
  def _deserialize_rack_session(data)
343
- opts = roda_class.opts[:sessions]
376
+ opts = roda_class.sessions_opts
344
377
  data, digest = data.split("--", 2)
345
378
  unless digest
346
379
  return _session_serialization_error("Not decoding Rack::Session::Cookie session: invalid format")
@@ -355,26 +388,18 @@ class Roda
355
388
  return _session_serialization_error("Error decoding Rack::Session::Cookie session: not base64 encoded marshal dump")
356
389
  end
357
390
 
358
- # Mark rack session cookie for deletion on success
359
- env[SESSION_DELETE_RACK_COOKIE] = true
391
+ env['roda.session.delete_rack_session_cookie'] = true
360
392
 
361
- # Delete the session id before serializing it. Starting in rack 2.0.8,
362
- # this is an object and not just a string, and calling to_s on it raises
363
- # a RuntimeError.
364
393
  session.delete("session_id")
365
394
 
366
- # Convert the rack session by roundtripping it through
367
- # the parser and serializer, so that you would get the
368
- # same result as you would if the session was handled
369
- # by this plugin.
370
- env[SESSION_SERIALIZED] = data = opts[:serializer].call(session)
371
- env[SESSION_CREATED_AT] = Time.now.to_i
395
+ env['roda.session.serialized'] = data = opts[:serializer].call(session)
396
+ env['roda.session.created_at'] = Time.now.to_i
372
397
  opts[:parser].call(data)
373
398
  end
374
399
 
375
- # Interpret given cookie data as a Rack::Session::Cookie
400
+ # Interpret given cookie data as a session
376
401
  def _deserialize_session(data)
377
- opts = roda_class.opts[:sessions]
402
+ config = roda_class.sessions_config
378
403
 
379
404
  begin
380
405
  data = Base64_.urlsafe_decode64(data)
@@ -398,7 +423,6 @@ class Roda
398
423
  min_data_length = 93
399
424
  when 0
400
425
  per_cookie_secret = false
401
- # minimum length (1+16+12+32) (version+cipher_iv+minimum session+hmac)
402
426
  min_data_length = 61
403
427
  when nil
404
428
  return _session_serialization_error("Unable to decode session: no data")
@@ -412,9 +436,11 @@ class Roda
412
436
  end
413
437
 
414
438
  encrypted_data = data.slice!(0, length-32)
415
- unless Rack::Utils.secure_compare(data, OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, opts[:hmac_secret], encrypted_data+opts[:key]))
416
- if opts[:old_hmac_secret] && Rack::Utils.secure_compare(data, OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, opts[:old_hmac_secret], encrypted_data+opts[:key]))
417
- use_old_cipher_secret = true
439
+ hmac_data = encrypted_data+config.key
440
+ cipher_secret = config.cipher_secret
441
+ unless Rack::Utils.secure_compare(data, OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, config.hmac_secret, hmac_data))
442
+ if config.old_hmac_secret && Rack::Utils.secure_compare(data, OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, config.old_hmac_secret, hmac_data))
443
+ cipher_secret = config.old_cipher_secret
418
444
  else
419
445
  return _session_serialization_error("Not decoding session: HMAC invalid")
420
446
  end
@@ -423,7 +449,6 @@ class Roda
423
449
  # Remove version
424
450
  encrypted_data.slice!(0)
425
451
 
426
- cipher_secret = opts[use_old_cipher_secret ? :old_cipher_secret : :cipher_secret]
427
452
  if per_cookie_secret
428
453
  cipher_secret = OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, cipher_secret, encrypted_data.slice!(0, 32))
429
454
  end
@@ -441,71 +466,71 @@ class Roda
441
466
  data = cipher.update(encrypted_data) << cipher.final
442
467
 
443
468
  bitmap, created_at, updated_at = data.unpack('vVV')
444
- padding_bytes = bitmap & PADDING_MASK
469
+ padding_bytes = bitmap & 0x0fff
445
470
  now = Time.now.to_i
446
- if (max = opts[:max_seconds]) && now > created_at + max
471
+ if (max = config.max_seconds) && now > created_at + max
447
472
  return _session_serialization_error("Not returning session: maximum session time expired")
448
473
  end
449
- if (max = opts[:max_idle_seconds]) && now > updated_at + max
474
+ if (max = config.max_idle_seconds) && now > updated_at + max
450
475
  return _session_serialization_error("Not returning session: maximum session idle time expired")
451
476
  end
452
477
 
453
478
  data = data.slice(10+padding_bytes, data.bytesize)
454
479
 
455
- if bitmap & DEFLATE_BIT > 0
480
+ if bitmap & 0x1000 > 0
456
481
  data = Zlib::Inflate.inflate(data)
457
482
  end
458
483
 
459
484
  env = @env
460
- env[SESSION_CREATED_AT] = created_at
461
- env[SESSION_UPDATED_AT] = updated_at
462
- env[SESSION_SERIALIZED] = data
463
- env[SESSION_VERSION_NUM] = version
485
+ env['roda.session.created_at'] = created_at
486
+ env['roda.session.updated_at'] = updated_at
487
+ env['roda.session.serialized'] = data
488
+ env['roda.session.version'] = version
464
489
 
465
- opts[:parser].call(data)
490
+ config.parser.call(data)
466
491
  end
467
492
 
468
493
  def _serialize_session(session)
469
- opts = roda_class.opts[:sessions]
494
+ config = roda_class.sessions_config
470
495
  env = @env
471
496
  now = Time.now.to_i
472
- json_data = opts[:serializer].call(session).force_encoding('BINARY')
497
+ json_data = config.serializer.call(session).force_encoding(Encoding::ASCII_8BIT)
473
498
 
474
- if (serialized_session = env[SESSION_SERIALIZED]) &&
475
- (opts[:session_version_num] == env[SESSION_VERSION_NUM]) &&
476
- (updated_at = env[SESSION_UPDATED_AT]) &&
477
- (now - updated_at < opts[:skip_within]) &&
499
+ if (serialized_session = env['roda.session.serialized']) &&
500
+ ((roda_class.sessions_opts[:per_cookie_cipher_secret] ? 1 : 0) == env['roda.session.version']) &&
501
+ (updated_at = env['roda.session.updated_at']) &&
502
+ (now - updated_at < config.skip_within) &&
478
503
  (serialized_session == json_data)
479
504
  return
480
505
  end
481
506
 
482
507
  bitmap = 0
483
508
  json_length = json_data.bytesize
484
- gzip_over = opts[:gzip_over]
509
+ gzip_over = roda_class.sessions_opts[:gzip_over]
485
510
 
486
511
  if gzip_over && json_length > gzip_over
487
512
  json_data = Zlib.deflate(json_data)
488
513
  json_length = json_data.bytesize
489
- bitmap |= DEFLATE_BIT
514
+ bitmap |= 0x1000
490
515
  end
491
516
 
492
517
  # When calculating padding bytes to use, include 10 bytes for bitmap and
493
518
  # session create/update times, so total size of encrypted data is a
494
519
  # multiple of pad_size.
495
- if (pad_size = opts[:pad_size]) && (padding_bytes = (json_length+10) % pad_size) != 0
520
+ if (pad_size = config.pad_size) && (padding_bytes = (json_length+10) % pad_size) != 0
496
521
  padding_bytes = pad_size - padding_bytes
497
522
  bitmap |= padding_bytes
498
523
  padding_data = SecureRandom.random_bytes(padding_bytes)
499
524
  end
500
525
 
501
- session_create_time = env[SESSION_CREATED_AT]
526
+ session_create_time = env['roda.session.created_at']
502
527
  serialized_data = [bitmap, session_create_time||now, now].pack('vVV')
503
528
 
504
529
  serialized_data << padding_data if padding_data
505
530
  serialized_data << json_data
506
531
 
507
- cipher_secret = opts[:cipher_secret]
508
- if opts[:per_cookie_cipher_secret]
532
+ cipher_secret = config.cipher_secret
533
+ if roda_class.sessions_opts[:per_cookie_cipher_secret]
509
534
  version = "\1"
510
535
  per_cookie_secret_base = SecureRandom.random_bytes(32)
511
536
  cipher_secret = OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, cipher_secret, per_cookie_secret_base)
@@ -524,7 +549,7 @@ class Roda
524
549
  data << per_cookie_secret_base if per_cookie_secret_base
525
550
  data << cipher_iv
526
551
  data << encrypted_data
527
- data << OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, opts[:hmac_secret], data+opts[:key])
552
+ data << OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, config.hmac_secret, data+config.key)
528
553
 
529
554
  data = Base64_.urlsafe_encode64(data)
530
555
 
@@ -74,6 +74,8 @@ class Roda
74
74
  end
75
75
 
76
76
  module ClassMethods
77
+ RodaPlugins.opt_attr_reader(self, :shape_friendly_scope_instance_variables)
78
+
77
79
  # Automatically refresh the instance variables used if the plugin
78
80
  # sets instance variables.
79
81
  def plugin(plugin, *args, &block)
@@ -107,7 +109,7 @@ class Roda
107
109
  ivs.concat(mod.const_get(const)) if mod.const_defined?(const)
108
110
  end
109
111
 
110
- if const == :SCOPE_INSTANCE_VARIABLES && (scope_ivs = opts[:shape_friendly_scope_instance_variables])
112
+ if const == :SCOPE_INSTANCE_VARIABLES && (scope_ivs = shape_friendly_scope_instance_variables)
111
113
  ivs.concat(scope_ivs)
112
114
  end
113
115