dalli 5.1.8 → 5.1.9

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: aedfdf5af128f44424f0d21689f66a86813b9714677716854889788fe3b62546
4
- data.tar.gz: 4375bcb70c31f53ac8fbf13cc4bc16171756a87148f95c024d214d8028216795
3
+ metadata.gz: cc4062ebe527bfd27199048a809597f9911085d560ff6b90036b9d1b30ce7062
4
+ data.tar.gz: ca89bd2d68a77b7b2a00fefe43e9d83197df65a24a242552f741acca8f2efa74
5
5
  SHA512:
6
- metadata.gz: ea2568b866c13f7d3bb9bf7d0c305c2164503df325c029d5aa160edb1316bc8ff01f97ec30d46e8a5113ed49350f6813c915f6202a093c7d28b21f9aed690cf0
7
- data.tar.gz: 2dac25033ab69bc1819eae18a94e2f7b4b672e540438e94f6aa8d73fe414baa47b17d77a65137b667ee1a9d0c57927477e30563b34c08d1cf4dbfde5f760ca1f
6
+ metadata.gz: '09e9bfdd9678e48ee9fc4c8023d2ddbbe294e28d80cc8fc7e9f344b2bf4ef31106e917e6e5442fbe09e6ce29d79007f1198cc0049bbb0b7ce1923c0cf05dcc20'
7
+ data.tar.gz: 0a120b2b37558725c8897cbe01c5a37d55a8d0098074f626ac9328d105c3454862ffa320fc84f399513737af55a1b8ca2355626a725aa6fdd85a297e8dfd512f
data/CHANGELOG.md CHANGED
@@ -1,9 +1,13 @@
1
1
  Dalli Changelog
2
2
  =====================
3
3
 
4
- Unreleased
4
+ 5.1.9
5
5
  ==========
6
6
 
7
+ Security:
8
+
9
+ - Bound memcached reply headers, incoming value sizes, and response counts, and enforce TLS timeouts for blocking operations (GHSA-5wpc-45jc-6ccc)
10
+
7
11
  5.1.8
8
12
  ==========
9
13
 
data/README.md CHANGED
@@ -49,6 +49,10 @@ Dalli::Client.new('localhost:11211', namespace: 'myapp', namespace_separator: '/
49
49
 
50
50
  The separator must be a single non-alphanumeric character. Valid examples: `:`, `/`, `|`, `.`, `-`, `_`, `#`
51
51
 
52
+ ### Maximum Value Size
53
+
54
+ `value_max_bytes` limits values written to memcached (1 MiB by default). Values read from a server have the same default limit. If another client writes larger values that this client must read, configure `max_response_bytes` explicitly.
55
+
52
56
  ## Security Note
53
57
 
54
58
  By default, Dalli uses Ruby's Marshal for serialization. Deserializing untrusted data with Marshal can lead to remote code execution. If you cache user-controlled data, consider using a safer serializer:
data/lib/dalli/client.rb CHANGED
@@ -35,6 +35,9 @@ module Dalli
35
35
  # to memcached. Default: true.
36
36
  # - :compression_min_size - the minimum size (in bytes) for which Dalli will compress values sent to Memcached.
37
37
  # Defaults to 4K.
38
+ # - :value_max_bytes - largest value Dalli will write, 1MB by default.
39
+ # - :max_response_bytes - largest value accepted from a server. Defaults to :value_max_bytes (1MB by default).
40
+ # Set this explicitly when reading larger items written by another client.
38
41
  # - :serializer - defaults to Marshal
39
42
  # - :compressor - defaults to Dalli::Compressor, a Zlib-based implementation
40
43
  # - :cache_nils - defaults to false, if true Dalli will not treat cached nil values as 'not found' for
@@ -225,6 +225,16 @@ module Dalli
225
225
  def servers_with_response(servers, timeout)
226
226
  return [] if servers.empty?
227
227
 
228
+ # A bounded read can stop while OpenSSL still holds decrypted bytes.
229
+ # IO.select only sees the underlying socket, so process those bytes
230
+ # before waiting for another network event.
231
+ buffered = nil
232
+ servers.each do |server|
233
+ sock = server.sock
234
+ (buffered ||= []) << server if sock.respond_to?(:pending_data?) && sock.pending_data?
235
+ end
236
+ return buffered if buffered
237
+
228
238
  sockets = servers.map(&:sock)
229
239
  readable, = IO.select(sockets, nil, nil, timeout)
230
240
  return [] if readable.nil?
@@ -181,6 +181,9 @@ module Dalli
181
181
  # to the noop at the end of the pipeline
182
182
  finish_pipeline && break if status && key.nil?
183
183
 
184
+ @pipeline_response_count += 1
185
+ raise Dalli::DalliError, 'Too many get_multi replies' if @pipeline_response_count > @expected_response_count
186
+
184
187
  # A key that wasn't requested means the replies are out of step
185
188
  # (see expect_reply_keys): keep what was read so far, drop the rest
186
189
  if unexpected_reply_key?(key)
@@ -221,6 +224,8 @@ module Dalli
221
224
  response_buffer.clear
222
225
  @pipeline_out_of_step = false
223
226
  @expected_reply_keys = nil
227
+ @expected_response_count = nil
228
+ @pipeline_response_count = nil
224
229
  @connection_manager.abort_request!
225
230
  return true unless connected?
226
231
 
@@ -404,7 +409,7 @@ module Dalli
404
409
  # Non-blocking read and processing of any available pipeline responses.
405
410
  # Used during interleaved pipelined gets to prevent buffer deadlock.
406
411
  # Populates the provided results hash directly to avoid allocation overhead.
407
- def drain_pipeline_responses(results)
412
+ def drain_pipeline_responses(results) # rubocop:disable Metrics/CyclomaticComplexity
408
413
  return unless connected?
409
414
 
410
415
  # Non-blocking check if socket has data available
@@ -418,6 +423,9 @@ module Dalli
418
423
  status, cas, key, value = response_buffer.process_single_getk_response
419
424
  break if status.nil? # No complete response available
420
425
 
426
+ @pipeline_response_count += 1
427
+ raise Dalli::DalliError, 'Too many get_multi replies' if @pipeline_response_count > @expected_response_count
428
+
421
429
  # Handled by the next pipeline_next_responses, once sending is done
422
430
  if unexpected_reply_key?(key)
423
431
  @pipeline_out_of_step = true
@@ -451,6 +459,8 @@ module Dalli
451
459
  # other clients created, on memcached versions with the behavior.
452
460
  def expect_reply_keys(keys)
453
461
  @pipeline_out_of_step = false
462
+ @expected_response_count = keys.size
463
+ @pipeline_response_count = 0
454
464
  @expected_reply_keys = (keys.to_set { |k| reply_key_form(k) } if @verify_reply_keys)
455
465
  end
456
466
 
@@ -204,7 +204,7 @@ module Dalli
204
204
 
205
205
  def read_line
206
206
  flush_write_buffer
207
- data = @sock.gets("\r\n", MAX_LINE_BYTES)
207
+ data = timed_tls_operation { @sock.gets("\r\n", MAX_LINE_BYTES) }
208
208
  error_on_request!('EOF in read_line') if data.nil?
209
209
  # Without its CRLF the line either ran past MAX_LINE_BYTES or was cut
210
210
  # short by EOF; either way the connection is out of step
@@ -369,13 +369,23 @@ module Dalli
369
369
 
370
370
  private
371
371
 
372
+ # Ruby 3.3's default OpenSSL can block past IO#timeout= on the TCP
373
+ # socket. Bound the blocking TLS call itself; error_on_request! closes
374
+ # the connection after the Timeout::Error, so a partial reply or write
375
+ # is never reused.
376
+ def timed_tls_operation(&)
377
+ return yield unless @sock.is_a?(Dalli::Socket::SSLSocket)
378
+
379
+ Timeout.timeout(socket_timeout, &)
380
+ end
381
+
372
382
  # One write per flush. A TLS socket sends each argument of
373
383
  # write(*parts) as its own record and system call, so the parts are
374
384
  # joined first.
375
385
  def flush_write_buffer
376
386
  return if @write_buffer.empty?
377
387
 
378
- @sock.write(@write_buffer.size == 1 ? @write_buffer.first : joined_write_buffer)
388
+ timed_tls_operation { @sock.write(@write_buffer.size == 1 ? @write_buffer.first : joined_write_buffer) }
379
389
  discard_write_buffer
380
390
  end
381
391
 
@@ -408,7 +418,7 @@ module Dalli
408
418
  # error_on_request!, which closes the dirty socket for a retry on a fresh
409
419
  # connection (and preserves the $ERROR_INFO context down! relies on).
410
420
  def read_bytes(count)
411
- buffer = @sock.read(count)
421
+ buffer = timed_tls_operation { @sock.read(count) }
412
422
  return buffer if buffer && buffer.bytesize == count
413
423
 
414
424
  raise EOFError, "EOF reading #{count} bytes; received #{buffer ? buffer.bytesize : 0}"
@@ -219,7 +219,7 @@ module Dalli
219
219
 
220
220
  def finish_pipelined_delete(sent)
221
221
  write_noop
222
- sent - response_processor.pipelined_delete_non_deletions
222
+ sent - response_processor.pipelined_delete_non_deletions(sent)
223
223
  end
224
224
 
225
225
  # Arithmetic Commands
@@ -342,8 +342,13 @@ module Dalli
342
342
  def read_multi_metadata_responses(is_raw, keys)
343
343
  expect_reply_keys(keys)
344
344
  hash = {}
345
+ replies = 0
345
346
  while (line = @connection_manager.read_line)
346
347
  break if line.start_with?('MN')
348
+
349
+ replies += 1
350
+ raise Dalli::DalliError, 'Too many get_multi replies' if replies > keys.size
351
+
347
352
  next unless line.start_with?('VA ')
348
353
 
349
354
  tokens = line.chomp!(TERMINATOR).split
@@ -367,8 +372,13 @@ module Dalli
367
372
  expect_reply_keys(keys)
368
373
  hash = {}
369
374
  key_index = is_raw ? 2 : 3
375
+ replies = 0
370
376
  while (line = @connection_manager.read_line)
371
377
  break if line.start_with?('MN')
378
+
379
+ replies += 1
380
+ raise Dalli::DalliError, 'Too many get_multi replies' if replies > keys.size
381
+
372
382
  next unless line.start_with?('VA ')
373
383
 
374
384
  key, value = parse_multi_get_value(line, key_index, is_raw)
@@ -419,7 +429,7 @@ module Dalli
419
429
  buffer = RequestFormatter.multi_meta_set(entries, ttl: ttl, **routing_token_kwargs(req_options))
420
430
  flushed_write(buffer)
421
431
  buffer.clear
422
- response_processor.consume_all_responses_until_mn
432
+ response_processor.consume_all_responses_until_mn(entries.size)
423
433
  end
424
434
  raise value_error if value_error
425
435
  end
@@ -431,7 +441,7 @@ module Dalli
431
441
  **routing_token_kwargs(req_options))
432
442
  flushed_write(buffer)
433
443
  buffer.clear
434
- keys.size - response_processor.pipelined_delete_non_deletions
444
+ keys.size - response_processor.pipelined_delete_non_deletions(keys.size)
435
445
  end
436
446
 
437
447
  require_relative 'key_regularizer'
@@ -26,6 +26,8 @@ module Dalli
26
26
  VA_PREFIX = 'VA '
27
27
  # memcached can't store an item larger than 1 GiB (its -I maximum)
28
28
  MAX_VALUE_BYTES = 1024 * 1024 * 1024
29
+ MAX_STATS_ENTRIES = 10_000
30
+ MAX_QUIET_RESPONSES = 100_000
29
31
  FLAGS_TOKEN_PREFIX = ' f'
30
32
  BYTE_B = 'b'.ord
31
33
  BYTE_C = 'c'.ord
@@ -159,7 +161,11 @@ module Dalli
159
161
  def stats
160
162
  tokens = error_on_unexpected!(T_END_TOKEN_STAT)
161
163
  values = {}
164
+ replies = 0
162
165
  while tokens.first != END_TOKEN
166
+ replies += 1
167
+ raise Dalli::DalliError, 'Too many stats replies' if replies > MAX_STATS_ENTRIES
168
+
163
169
  values[tokens[1]] = tokens[2]
164
170
  tokens = next_line_to_tokens
165
171
  end
@@ -183,10 +189,16 @@ module Dalli
183
189
  tokens.last
184
190
  end
185
191
 
186
- def consume_all_responses_until_mn
192
+ def consume_all_responses_until_mn(max_responses = MAX_QUIET_RESPONSES)
187
193
  tokens = next_line_to_tokens
188
194
 
189
- tokens = next_line_to_tokens while tokens.first != MN
195
+ replies = 0
196
+ while tokens.first != MN
197
+ replies += 1
198
+ raise Dalli::DalliError, 'Too many quiet replies' if replies > max_responses
199
+
200
+ tokens = next_line_to_tokens
201
+ end
190
202
  true
191
203
  end
192
204
 
@@ -197,11 +209,13 @@ module Dalli
197
209
  # was NOT deleted -- a miss (NF) or an error. Returns that count so
198
210
  # callers can derive the number of successful deletes as
199
211
  # (keys_sent - non_deletions).
200
- def pipelined_delete_non_deletions
212
+ def pipelined_delete_non_deletions(max_responses = MAX_QUIET_RESPONSES)
201
213
  non_deletions = 0
202
214
  tokens = next_line_to_tokens
203
215
  until tokens.first == MN
204
216
  non_deletions += 1
217
+ raise Dalli::DalliError, 'Too many delete replies' if non_deletions > max_responses
218
+
205
219
  tokens = next_line_to_tokens
206
220
  end
207
221
  non_deletions
@@ -222,6 +236,13 @@ module Dalli
222
236
  def getk_response_from_buffer(buf, offset = 0, raw: false)
223
237
  # Find the header terminator starting from offset
224
238
  term_idx = buf.byteindex(TERMINATOR, offset)
239
+ max_line_bytes = ConnectionManager::MAX_LINE_BYTES
240
+ header_too_long = if term_idx
241
+ term_idx - offset + TERMINATOR.bytesize > max_line_bytes
242
+ else
243
+ buf.bytesize - offset >= max_line_bytes
244
+ end
245
+ raise Dalli::DalliError, "Reply line without CRLF in the first #{max_line_bytes} bytes" if header_too_long
225
246
  return [0] unless term_idx
226
247
 
227
248
  header = buf.byteslice(offset, term_idx - offset)
@@ -374,9 +395,11 @@ module Dalli
374
395
  end
375
396
 
376
397
  def check_value_size!(size)
377
- return if size.between?(0, MAX_VALUE_BYTES)
398
+ limit = @value_marshaller.max_response_bytes
399
+ return if size >= 0 && size <= MAX_VALUE_BYTES && size <= limit # rubocop:disable Style/ComparableBetween
378
400
 
379
- raise Dalli::DalliError, "Reply value size #{size} is out of range"
401
+ effective_limit = [MAX_VALUE_BYTES, limit].min
402
+ raise Dalli::DalliError, "Reply value size #{size} exceeds the #{effective_limit}-byte response limit"
380
403
  end
381
404
 
382
405
  def read_line
@@ -14,12 +14,14 @@ module Dalli
14
14
  value_max_bytes: 1024 * 1024
15
15
  }.freeze
16
16
 
17
- attr_reader :value_max_bytes
17
+ attr_reader :value_max_bytes, :max_response_bytes
18
18
 
19
19
  def initialize(client_options)
20
20
  @value_max_bytes = client_options.fetch(:value_max_bytes) do
21
21
  DEFAULTS.fetch(:value_max_bytes)
22
22
  end.to_i
23
+ @max_response_bytes = Integer(client_options.fetch(:max_response_bytes, @value_max_bytes))
24
+ raise ArgumentError, 'max_response_bytes must be positive' unless @max_response_bytes.positive?
23
25
  end
24
26
 
25
27
  def store(key, value, _options = nil)
@@ -28,6 +28,9 @@ module Dalli
28
28
 
29
29
  @marshal_options =
30
30
  DEFAULTS.merge(client_options.slice(*OPTIONS))
31
+ @marshal_options[:value_max_bytes] = @marshal_options[:value_max_bytes].to_i
32
+ @max_response_bytes = Integer(client_options.fetch(:max_response_bytes, value_max_bytes))
33
+ raise ArgumentError, 'max_response_bytes must be positive' unless @max_response_bytes.positive?
31
34
  end
32
35
 
33
36
  def store(key, value, options = nil)
@@ -48,6 +51,8 @@ module Dalli
48
51
  @marshal_options[:value_max_bytes]
49
52
  end
50
53
 
54
+ attr_reader :max_response_bytes
55
+
51
56
  def error_if_over_max_value_bytes(key, value)
52
57
  return if value.bytesize <= value_max_bytes
53
58
 
data/lib/dalli/socket.rb CHANGED
@@ -12,22 +12,35 @@ module Dalli
12
12
  # Common methods for all socket implementations.
13
13
  ##
14
14
  module InstanceMethods
15
+ READ_CHUNK_SIZE = 8196
16
+ # Give the response parser control between bounded socket reads. In
17
+ # particular, a peer continuously sending a header without CRLF must
18
+ # not keep this method appending forever.
19
+ MAX_AVAILABLE_BYTES = READ_CHUNK_SIZE * 8
20
+
21
+ # Reads whatever is available without blocking. A read that returns less
22
+ # than a full chunk means the socket was drained, so we stop there rather
23
+ # than spend another read_nonblock call just to get :wait_readable back.
24
+ # Callers keep waiting on IO.select for anything that arrives later.
15
25
  def read_available(reusable_buffer = nil)
16
26
  if reusable_buffer
17
- value = read_nonblock(8196, reusable_buffer, exception: false)
27
+ value = read_nonblock([READ_CHUNK_SIZE, MAX_AVAILABLE_BYTES].min, reusable_buffer, exception: false)
18
28
  case value
19
29
  when :wait_writable, :wait_readable
20
30
  return reusable_buffer.clear
21
31
  when nil
22
32
  raise Errno::ECONNRESET, "Connection reset: #{logged_options.inspect}"
23
33
  end
34
+ return value if drained_after?(value)
35
+ return value if value.bytesize >= MAX_AVAILABLE_BYTES
24
36
  else
25
37
  value = ''.b
26
38
  end
27
39
 
28
40
  buffer = ''.b
29
41
  loop do
30
- result = read_nonblock(8196, buffer, exception: false)
42
+ result = read_nonblock([READ_CHUNK_SIZE, MAX_AVAILABLE_BYTES - value.bytesize].min,
43
+ buffer, exception: false)
31
44
  case result
32
45
  when :wait_writable, :wait_readable
33
46
  buffer.clear
@@ -36,10 +49,20 @@ module Dalli
36
49
  raise Errno::ECONNRESET, "Connection reset: #{logged_options.inspect}"
37
50
  else
38
51
  value << result
52
+ return value if drained_after?(result)
53
+ return value if value.bytesize >= MAX_AVAILABLE_BYTES
39
54
  end
40
55
  end
41
56
  end
42
57
 
58
+ def drained_after?(chunk)
59
+ chunk.bytesize < READ_CHUNK_SIZE && !buffered_data?
60
+ end
61
+
62
+ def buffered_data?
63
+ false
64
+ end
65
+
43
66
  FILTERED_OUT_OPTIONS = %i[username password].freeze
44
67
  def logged_options
45
68
  options.except(*FILTERED_OUT_OPTIONS)
@@ -83,6 +106,27 @@ module Dalli
83
106
  io.options
84
107
  end
85
108
 
109
+ # OpenSSL can hold decrypted bytes that IO.select won't report as readable.
110
+ # With OpenSSL's default (no read-ahead) a short read has already used up
111
+ # the current record, so this is normally 0; it guards read-ahead setups.
112
+ #
113
+ # jruby-openssl can take the next record off the socket during a short
114
+ # read and hold it where neither pending nor IO.select sees it, so on
115
+ # JRuby a read continues until the socket would block.
116
+ def pending_data?
117
+ pending.positive? || (@rbuffer && !@rbuffer.empty?)
118
+ end
119
+
120
+ if RUBY_ENGINE == 'jruby'
121
+ def buffered_data?
122
+ true
123
+ end
124
+ else
125
+ def buffered_data?
126
+ pending_data?
127
+ end
128
+ end
129
+
86
130
  unless method_defined?(:wait_readable)
87
131
  def wait_readable(timeout = nil)
88
132
  to_io.wait_readable(timeout)
@@ -116,7 +160,12 @@ module Dalli
116
160
  sock.options = { host: host, port: port }.merge(options)
117
161
  init_socket_options(sock, options)
118
162
 
119
- options[:ssl_context] ? wrapping_ssl_socket(sock, host, options[:ssl_context]) : sock
163
+ if options[:ssl_context]
164
+ wrapping_ssl_socket(sock, host, options[:ssl_context],
165
+ options[:socket_timeout])
166
+ else
167
+ sock
168
+ end
120
169
  end
121
170
  end
122
171
 
@@ -205,13 +254,15 @@ module Dalli
205
254
 
206
255
  # Closes the TCP socket if the handshake fails or times out, so a failed
207
256
  # attempt doesn't hold a file descriptor until GC.
208
- def self.wrapping_ssl_socket(tcp_socket, host, ssl_context)
257
+ def self.wrapping_ssl_socket(tcp_socket, host, ssl_context, timeout = nil)
209
258
  warn_if_unverified(ssl_context)
210
259
  connected = false
211
260
  ssl_socket = Dalli::Socket::SSLSocket.new(tcp_socket, ssl_context)
212
261
  ssl_socket.hostname = host
213
262
  ssl_socket.sync_close = true
214
- ssl_socket.connect
263
+ # The underlying TCP socket's IO#timeout= does not reliably bound
264
+ # OpenSSL's blocking handshake on Ruby 3.3.
265
+ Timeout.timeout(timeout) { ssl_socket.connect }
215
266
  connected = true
216
267
  ssl_socket
217
268
  ensure
data/lib/dalli/version.rb CHANGED
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Dalli
4
- VERSION = '5.1.8'
4
+ VERSION = '5.1.9'
5
5
 
6
6
  MIN_SUPPORTED_MEMCACHED_VERSION = '1.6.27'
7
7
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: dalli
3
3
  version: !ruby/object:Gem::Version
4
- version: 5.1.8
4
+ version: 5.1.9
5
5
  platform: ruby
6
6
  authors:
7
7
  - Peter M. Goldstein
@@ -88,7 +88,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
88
88
  - !ruby/object:Gem::Version
89
89
  version: '0'
90
90
  requirements: []
91
- rubygems_version: 4.0.23
91
+ rubygems_version: 4.0.24
92
92
  specification_version: 4
93
93
  summary: High performance memcached client for Ruby
94
94
  test_files: []