Skip to content

Commit 84481df

Browse files
authored
Ensure that truncating keys in CouchbaseStore preserves the validity of their encoding (#125)
1 parent cc7140b commit 84481df

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

lib/active_support/cache/couchbase_store.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -294,14 +294,14 @@ def failsafe(method, returning: nil)
294294

295295
# Truncate keys that exceed 250 characters
296296
def normalize_key(key, options)
297-
truncate_key super&.b
297+
truncate_key super
298298
end
299299

300300
def truncate_key(key)
301301
if key && key.bytesize > MAX_KEY_BYTESIZE
302302
suffix = ":sha2:#{::Digest::SHA2.hexdigest(key)}"
303303
truncate_at = MAX_KEY_BYTESIZE - suffix.bytesize
304-
"#{key.byteslice(0, truncate_at)}#{suffix}"
304+
"#{key.mb_chars.limit(truncate_at)}#{suffix}"
305305
else
306306
key
307307
end

test/active_support/behaviors/encoded_key_cache_behavior.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,20 @@ def test_retains_encoding
3333
assert @cache.write(key, "1", raw: true)
3434
assert_equal Encoding::UTF_8, key.encoding
3535
end
36+
37+
def test_very_long_utf8_key
38+
key = ("a"*249 + "\xC3\xBC").force_encoding(Encoding::UTF_8)
39+
assert @cache.write(key, "1", raw: true)
40+
assert_equal Encoding::UTF_8, key.encoding
41+
assert key.valid_encoding?
42+
assert key.bytesize > 250
43+
end
44+
45+
def test_normalize_key
46+
key = ("a"*249 + "\xC3\xBC").force_encoding(Encoding::UTF_8)
47+
normalized_key = @cache.send(:normalize_key, key, nil)
48+
assert_equal Encoding::UTF_8, normalized_key.encoding
49+
assert normalized_key.valid_encoding?
50+
assert normalized_key.bytesize <= 250
51+
end
3652
end

0 commit comments

Comments
 (0)