dalli 5.2.8 → 5.2.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: 4fa868aa2b92a8669cc00416effa319b3122ebb39140b4621eb25185b0fc114f
4
- data.tar.gz: 45cd331ebc4366007ec0fd49d172fb7042b49680bc49ca947f8b43fd9d3b2367
3
+ metadata.gz: 2e1086cdd8b9a7bac4828786bfb089d1b046c5b1e61cd5074c795c5a2bc81acf
4
+ data.tar.gz: 3a3987346678ee792c0ce367ff3141122fcd9ac9c35eeb203e22f7e22d1cc4ea
5
5
  SHA512:
6
- metadata.gz: a69bc353299d1d8dea6a877cdec90149ab750083fcad768f0246b20ed0cd1f07c119df48bbb0e842ddbe01d32be9419e4a218d58e41d40d30c4b81a187e400e5
7
- data.tar.gz: 1cf619274e1e90679a85698b6114c2a24fef8064b94694a0c2b522d6495c1611265851f5530a7063a0f0602866d42a4b7bec120f9e4a29fd575922f9612dd7f4
6
+ metadata.gz: aae2272b110f5d4aa579884fecd7b090b76fa66f3014ad60b9481c1567d1ec1bdadaf2804e593e58d3d46614dba6d2b327628367708094f1c07a26f0d0ce108d
7
+ data.tar.gz: 2f773864672599adfb9b1f75bb66ff032d235f8d2e771020e48fe3b569d6d6ab6ffcd00c37043220bf850d36c999d454cdc4e283b90168d0abe531a9456b07bc
data/CHANGELOG.md CHANGED
@@ -1,6 +1,13 @@
1
1
  Dalli Changelog
2
2
  =====================
3
3
 
4
+ 5.2.9
5
+ ==========
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
+
4
11
  5.2.8
5
12
  ==========
6
13
 
data/README.md CHANGED
@@ -70,6 +70,8 @@ Dalli::Client.new('localhost:11211', value_max_bytes: 2 * 1024 * 1024)
70
70
 
71
71
  memcached's limit covers the whole item, so Dalli checks the stored (serialized and compressed) value plus the key plus 63 bytes of per-item overhead against `value_max_bytes`, and raises `Dalli::ValueOverMaxSize` before sending anything larger. With the defaults, the largest value you can store under a 10-byte key is 1,048,576 - 10 - 63 = 1,048,503 bytes.
72
72
 
73
+ Dalli also limits the size of values it reads to `value_max_bytes`. If another client writes larger items that this client needs to read, set `max_response_bytes` explicitly. Keep it no higher than the largest item size you intend to accept from the server.
74
+
73
75
  ### Deferred Draining
74
76
 
75
77
  By default, a `quiet` (or `multi`) block ends by waiting for the replies memcached still sends for its quiet requests, one round trip for each server the block wrote to. With `defer_drain: true`, the block returns without waiting:
data/lib/dalli/client.rb CHANGED
@@ -39,6 +39,8 @@ module Dalli
39
39
  # memcached, Dalli counts the key and 63 bytes of item overhead against this limit along
40
40
  # with the (serialized, compressed) value, so the largest value that can be stored is
41
41
  # value_max_bytes - key bytesize - 63. Larger values raise Dalli::ValueOverMaxSize.
42
+ # - :max_response_bytes - largest value accepted from a server. Defaults to :value_max_bytes (1MB by default).
43
+ # Set this explicitly when reading larger items written by another client.
42
44
  # - :serializer - defaults to Marshal
43
45
  # - :compressor - defaults to Dalli::Compressor, a Zlib-based implementation
44
46
  # - :cache_nils - defaults to false, if true Dalli will not treat cached nil values as 'not found' for
@@ -228,6 +228,16 @@ module Dalli
228
228
  def servers_with_response(servers, timeout)
229
229
  return [] if servers.empty?
230
230
 
231
+ # A bounded read can stop while OpenSSL still holds decrypted bytes.
232
+ # IO.select only sees the underlying socket, so process those bytes
233
+ # before waiting for another network event.
234
+ buffered = nil
235
+ servers.each do |server|
236
+ sock = server.sock
237
+ (buffered ||= []) << server if sock.respond_to?(:pending_data?) && sock.pending_data?
238
+ end
239
+ return buffered if buffered
240
+
231
241
  sockets = servers.map(&:sock)
232
242
  readable, = IO.select(sockets, nil, nil, timeout)
233
243
  return [] if readable.nil?
@@ -177,6 +177,9 @@ module Dalli
177
177
  # to the noop at the end of the pipeline
178
178
  finish_pipeline && break if status && key.nil?
179
179
 
180
+ @pipeline_response_count += 1
181
+ raise Dalli::DalliError, 'Too many get_multi replies' if @pipeline_response_count > @expected_response_count
182
+
180
183
  # A key that wasn't requested means the replies are out of step
181
184
  # (see expect_reply_keys): keep what was read so far, drop the rest
182
185
  if unexpected_reply_key?(key)
@@ -217,6 +220,8 @@ module Dalli
217
220
  response_buffer.clear
218
221
  @pipeline_out_of_step = false
219
222
  @expected_reply_keys = nil
223
+ @expected_response_count = nil
224
+ @pipeline_response_count = nil
220
225
  @connection_manager.abort_request!
221
226
  return true unless connected?
222
227
 
@@ -422,7 +427,7 @@ module Dalli
422
427
  # Non-blocking read and processing of any available pipeline responses.
423
428
  # Used during interleaved pipelined gets to prevent buffer deadlock.
424
429
  # Populates the provided results hash directly to avoid allocation overhead.
425
- def drain_pipeline_responses(results)
430
+ def drain_pipeline_responses(results) # rubocop:disable Metrics/CyclomaticComplexity
426
431
  return unless connected?
427
432
 
428
433
  # Non-blocking check if socket has data available
@@ -436,6 +441,9 @@ module Dalli
436
441
  status, cas, key, value = response_buffer.process_single_getk_response
437
442
  break if status.nil? # No complete response available
438
443
 
444
+ @pipeline_response_count += 1
445
+ raise Dalli::DalliError, 'Too many get_multi replies' if @pipeline_response_count > @expected_response_count
446
+
439
447
  # Handled by the next pipeline_next_responses, once sending is done
440
448
  if unexpected_reply_key?(key)
441
449
  @pipeline_out_of_step = true
@@ -469,6 +477,8 @@ module Dalli
469
477
  # other clients created, on memcached versions with the behavior.
470
478
  def expect_reply_keys(keys)
471
479
  @pipeline_out_of_step = false
480
+ @expected_response_count = keys.size
481
+ @pipeline_response_count = 0
472
482
  @expected_reply_keys = (keys.to_set { |k| reply_key_form(k) } if @verify_reply_keys)
473
483
  end
474
484
 
@@ -213,7 +213,7 @@ module Dalli
213
213
 
214
214
  def read_line
215
215
  flush_write_buffer
216
- data = @sock.gets("\r\n", MAX_LINE_BYTES)
216
+ data = timed_tls_operation { @sock.gets("\r\n", MAX_LINE_BYTES) }
217
217
  error_on_request!('EOF in read_line') if data.nil?
218
218
  # Without its CRLF the line either ran past MAX_LINE_BYTES or was cut
219
219
  # short by EOF; either way the connection is out of step
@@ -378,13 +378,23 @@ module Dalli
378
378
 
379
379
  private
380
380
 
381
+ # Ruby 3.3's default OpenSSL can block past IO#timeout= on the TCP
382
+ # socket. Bound the blocking TLS call itself; error_on_request! closes
383
+ # the connection after the Timeout::Error, so a partial reply or write
384
+ # is never reused.
385
+ def timed_tls_operation(&)
386
+ return yield unless @sock.is_a?(Dalli::Socket::SSLSocket)
387
+
388
+ Timeout.timeout(socket_timeout, &)
389
+ end
390
+
381
391
  # One write per flush. A TLS socket sends each argument of
382
392
  # write(*parts) as its own record and system call, so the parts are
383
393
  # joined first.
384
394
  def flush_write_buffer
385
395
  return if @write_buffer.empty?
386
396
 
387
- @sock.write(@write_buffer.size == 1 ? @write_buffer.first : joined_write_buffer)
397
+ timed_tls_operation { @sock.write(@write_buffer.size == 1 ? @write_buffer.first : joined_write_buffer) }
388
398
  discard_write_buffer
389
399
  end
390
400
 
@@ -417,7 +427,7 @@ module Dalli
417
427
  # error_on_request!, which closes the dirty socket for a retry on a fresh
418
428
  # connection (and preserves the $ERROR_INFO context down! relies on).
419
429
  def read_bytes(count)
420
- buffer = @sock.read(count)
430
+ buffer = timed_tls_operation { @sock.read(count) }
421
431
  return buffer if buffer && buffer.bytesize == count
422
432
 
423
433
  raise EOFError, "EOF reading #{count} bytes; received #{buffer ? buffer.bytesize : 0}"
@@ -229,7 +229,7 @@ module Dalli
229
229
 
230
230
  def finish_pipelined_delete(sent)
231
231
  write_noop
232
- sent - response_processor.pipelined_delete_non_deletions
232
+ sent - response_processor.pipelined_delete_non_deletions(sent)
233
233
  end
234
234
 
235
235
  # Arithmetic Commands
@@ -363,8 +363,13 @@ module Dalli
363
363
  def read_multi_metadata_responses(is_raw, keys)
364
364
  expect_reply_keys(keys)
365
365
  hash = {}
366
+ replies = 0
366
367
  while (line = @connection_manager.read_line)
367
368
  break if line.start_with?('MN')
369
+
370
+ replies += 1
371
+ raise Dalli::DalliError, 'Too many get_multi replies' if replies > keys.size
372
+
368
373
  next unless line.start_with?('VA ')
369
374
 
370
375
  tokens = line.chomp!(TERMINATOR).split
@@ -387,8 +392,13 @@ module Dalli
387
392
  def read_multi_get_responses(is_raw, keys)
388
393
  expect_reply_keys(keys)
389
394
  hash = {}
395
+ replies = 0
390
396
  while (line = @connection_manager.read_line)
391
397
  break if line.start_with?('MN')
398
+
399
+ replies += 1
400
+ raise Dalli::DalliError, 'Too many get_multi replies' if replies > keys.size
401
+
392
402
  next unless line.start_with?('VA ')
393
403
 
394
404
  key, value = parse_multi_get_value(line, is_raw)
@@ -439,7 +449,7 @@ module Dalli
439
449
  buffer = RequestFormatter.multi_meta_set(entries, ttl: ttl, **routing_token_kwargs(req_options))
440
450
  flushed_write(buffer)
441
451
  buffer.clear
442
- response_processor.consume_all_responses_until_mn
452
+ response_processor.consume_all_responses_until_mn(entries.size)
443
453
  end
444
454
  raise value_error if value_error
445
455
  end
@@ -451,7 +461,7 @@ module Dalli
451
461
  **routing_token_kwargs(req_options))
452
462
  flushed_write(buffer)
453
463
  buffer.clear
454
- keys.size - response_processor.pipelined_delete_non_deletions
464
+ keys.size - response_processor.pipelined_delete_non_deletions(keys.size)
455
465
  end
456
466
 
457
467
  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
  HD_PREFIX = 'HD '
30
32
  FLAGS_TOKEN_PREFIX = ' f'
31
33
  CAS_TOKEN_PREFIX = ' c'
@@ -174,7 +176,11 @@ module Dalli
174
176
  def stats
175
177
  tokens = error_on_unexpected!(T_END_TOKEN_STAT)
176
178
  values = {}
179
+ replies = 0
177
180
  while tokens.first != END_TOKEN
181
+ replies += 1
182
+ raise Dalli::DalliError, 'Too many stats replies' if replies > MAX_STATS_ENTRIES
183
+
178
184
  values[tokens[1]] = tokens[2]
179
185
  tokens = next_line_to_tokens
180
186
  end
@@ -198,10 +204,16 @@ module Dalli
198
204
  tokens.last
199
205
  end
200
206
 
201
- def consume_all_responses_until_mn
207
+ def consume_all_responses_until_mn(max_responses = MAX_QUIET_RESPONSES)
202
208
  tokens = next_line_to_tokens
203
209
 
204
- tokens = next_line_to_tokens while tokens.first != MN
210
+ replies = 0
211
+ while tokens.first != MN
212
+ replies += 1
213
+ raise Dalli::DalliError, 'Too many quiet replies' if replies > max_responses
214
+
215
+ tokens = next_line_to_tokens
216
+ end
205
217
  true
206
218
  end
207
219
 
@@ -212,11 +224,13 @@ module Dalli
212
224
  # was NOT deleted -- a miss (NF) or an error. Returns that count so
213
225
  # callers can derive the number of successful deletes as
214
226
  # (keys_sent - non_deletions).
215
- def pipelined_delete_non_deletions
227
+ def pipelined_delete_non_deletions(max_responses = MAX_QUIET_RESPONSES)
216
228
  non_deletions = 0
217
229
  tokens = next_line_to_tokens
218
230
  until tokens.first == MN
219
231
  non_deletions += 1
232
+ raise Dalli::DalliError, 'Too many delete replies' if non_deletions > max_responses
233
+
220
234
  tokens = next_line_to_tokens
221
235
  end
222
236
  non_deletions
@@ -237,6 +251,13 @@ module Dalli
237
251
  def getk_response_from_buffer(buf, offset = 0, raw: false)
238
252
  # Find the header terminator starting from offset
239
253
  term_idx = buf.byteindex(TERMINATOR, offset)
254
+ max_line_bytes = ConnectionManager::MAX_LINE_BYTES
255
+ header_too_long = if term_idx
256
+ term_idx - offset + TERMINATOR.bytesize > max_line_bytes
257
+ else
258
+ buf.bytesize - offset >= max_line_bytes
259
+ end
260
+ raise Dalli::DalliError, "Reply line without CRLF in the first #{max_line_bytes} bytes" if header_too_long
240
261
  return [0] unless term_idx
241
262
 
242
263
  if buf.byteslice(offset, VA_PREFIX.bytesize) == VA_PREFIX
@@ -456,9 +477,11 @@ module Dalli
456
477
  end
457
478
 
458
479
  def check_value_size!(size)
459
- return if size.between?(0, MAX_VALUE_BYTES)
480
+ limit = @value_marshaller.max_response_bytes
481
+ return if size >= 0 && size <= MAX_VALUE_BYTES && size <= limit # rubocop:disable Style/ComparableBetween
460
482
 
461
- raise Dalli::DalliError, "Reply value size #{size} is out of range"
483
+ effective_limit = [MAX_VALUE_BYTES, limit].min
484
+ raise Dalli::DalliError, "Reply value size #{size} exceeds the #{effective_limit}-byte response limit"
462
485
  end
463
486
 
464
487
  def read_line
@@ -15,12 +15,14 @@ module Dalli
15
15
  value_max_bytes: 1024 * 1024
16
16
  }.freeze
17
17
 
18
- attr_reader :value_max_bytes
18
+ attr_reader :value_max_bytes, :max_response_bytes
19
19
 
20
20
  def initialize(client_options)
21
21
  @value_max_bytes = client_options.fetch(:value_max_bytes) do
22
22
  DEFAULTS.fetch(:value_max_bytes)
23
23
  end.to_i
24
+ @max_response_bytes = Integer(client_options.fetch(:max_response_bytes, @value_max_bytes))
25
+ raise ArgumentError, 'max_response_bytes must be positive' unless @max_response_bytes.positive?
24
26
  end
25
27
 
26
28
  def store(key, value, _options = nil)
@@ -47,6 +47,8 @@ module Dalli
47
47
  @marshal_options =
48
48
  DEFAULTS.merge(client_options.slice(*OPTIONS))
49
49
  @marshal_options[:value_max_bytes] = @marshal_options[:value_max_bytes].to_i
50
+ @max_response_bytes = Integer(client_options.fetch(:max_response_bytes, value_max_bytes))
51
+ raise ArgumentError, 'max_response_bytes must be positive' unless @max_response_bytes.positive?
50
52
  end
51
53
 
52
54
  def store(key, value, options = nil)
@@ -67,6 +69,8 @@ module Dalli
67
69
  @marshal_options[:value_max_bytes]
68
70
  end
69
71
 
72
+ attr_reader :max_response_bytes
73
+
70
74
  def error_if_over_max_value_bytes(key, value)
71
75
  self.class.error_if_over_max_value_bytes(key, value, value_max_bytes)
72
76
  end
data/lib/dalli/socket.rb CHANGED
@@ -19,6 +19,10 @@ module Dalli
19
19
  ##
20
20
  module InstanceMethods
21
21
  READ_CHUNK_SIZE = 8196
22
+ # Give the response parser control between bounded socket reads. In
23
+ # particular, a peer continuously sending a header without CRLF must
24
+ # not keep this method appending forever.
25
+ MAX_AVAILABLE_BYTES = READ_CHUNK_SIZE * 8
22
26
 
23
27
  # Reads whatever is available without blocking. A read that returns less
24
28
  # than a full chunk means the socket was drained, so we stop there rather
@@ -26,7 +30,7 @@ module Dalli
26
30
  # Callers keep waiting on IO.select for anything that arrives later.
27
31
  def read_available(reusable_buffer = nil)
28
32
  if reusable_buffer
29
- value = read_nonblock(READ_CHUNK_SIZE, reusable_buffer, exception: false)
33
+ value = read_nonblock([READ_CHUNK_SIZE, MAX_AVAILABLE_BYTES].min, reusable_buffer, exception: false)
30
34
  case value
31
35
  when :wait_writable, :wait_readable
32
36
  return reusable_buffer.clear
@@ -34,13 +38,15 @@ module Dalli
34
38
  raise Errno::ECONNRESET, "Connection reset: #{logged_options.inspect}"
35
39
  end
36
40
  return value if drained_after?(value)
41
+ return value if value.bytesize >= MAX_AVAILABLE_BYTES
37
42
  else
38
43
  value = ''.b
39
44
  end
40
45
 
41
46
  buffer = ''.b
42
47
  loop do
43
- result = read_nonblock(READ_CHUNK_SIZE, buffer, exception: false)
48
+ result = read_nonblock([READ_CHUNK_SIZE, MAX_AVAILABLE_BYTES - value.bytesize].min,
49
+ buffer, exception: false)
44
50
  case result
45
51
  when :wait_writable, :wait_readable
46
52
  buffer.clear
@@ -50,6 +56,7 @@ module Dalli
50
56
  else
51
57
  value << result
52
58
  return value if drained_after?(result)
59
+ return value if value.bytesize >= MAX_AVAILABLE_BYTES
53
60
  end
54
61
  end
55
62
  end
@@ -114,13 +121,17 @@ module Dalli
114
121
  # jruby-openssl can take the next record off the socket during a short
115
122
  # read and hold it where neither pending nor IO.select sees it, so on
116
123
  # JRuby a read continues until the socket would block.
124
+ def pending_data?
125
+ pending.positive? || (@rbuffer && !@rbuffer.empty?)
126
+ end
127
+
117
128
  if RUBY_ENGINE == 'jruby'
118
129
  def buffered_data?
119
130
  true
120
131
  end
121
132
  else
122
133
  def buffered_data?
123
- pending.positive?
134
+ pending_data?
124
135
  end
125
136
  end
126
137
 
@@ -157,7 +168,12 @@ module Dalli
157
168
  sock.options = { host: host, port: port }.merge(options)
158
169
  init_socket_options(sock, options)
159
170
 
160
- options[:ssl_context] ? wrapping_ssl_socket(sock, host, options[:ssl_context]) : sock
171
+ if options[:ssl_context]
172
+ wrapping_ssl_socket(sock, host, options[:ssl_context],
173
+ options[:socket_timeout])
174
+ else
175
+ sock
176
+ end
161
177
  end
162
178
  end
163
179
 
@@ -248,13 +264,15 @@ module Dalli
248
264
 
249
265
  # Closes the TCP socket if the handshake fails or times out, so a failed
250
266
  # attempt doesn't hold a file descriptor until GC.
251
- def self.wrapping_ssl_socket(tcp_socket, host, ssl_context)
267
+ def self.wrapping_ssl_socket(tcp_socket, host, ssl_context, timeout = nil)
252
268
  warn_if_unverified(ssl_context)
253
269
  connected = false
254
270
  ssl_socket = Dalli::Socket::SSLSocket.new(tcp_socket, ssl_context)
255
271
  ssl_socket.hostname = host
256
272
  ssl_socket.sync_close = true
257
- ssl_socket.connect
273
+ # The underlying TCP socket's IO#timeout= does not reliably bound
274
+ # OpenSSL's blocking handshake on Ruby 3.3.
275
+ Timeout.timeout(timeout) { ssl_socket.connect }
258
276
  connected = true
259
277
  ssl_socket
260
278
  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.2.8'
4
+ VERSION = '5.2.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.2.8
4
+ version: 5.2.9
5
5
  platform: ruby
6
6
  authors:
7
7
  - Peter M. Goldstein