Skip to content

Commit

Permalink
fix: Update logging to coerce ASCII-8BIT into UTF-8. (#1076)
Browse files Browse the repository at this point in the history
  • Loading branch information
dcr-stripe authored Jun 21, 2022
1 parent 33c8200 commit 9092e9d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/stripe/util.rb
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,15 @@ def self.wrap_logfmt_value(val)
# Hopefully val is a string, but protect in case it's not.
val = val.to_s

# Some values returned by the server are encoded in ASCII-8BIT before
# being parsed as UTF-8 by Marshal. If we don't transform these here, then
# puts will fail as it tries to render UTF-8 characters as ASCII-8BIT
# which is not valid.
if val && val.encoding == Encoding::ASCII_8BIT
# Dup the string as it is a frozen literal.
val = val.dup.force_encoding("UTF-8")
end

if %r{[^\w\-/]} =~ val
# If the string contains any special characters, escape any double
# quotes it has, remove newlines, and wrap the whole thing in quotes.
Expand Down
7 changes: 7 additions & 0 deletions test/stripe/util_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,13 @@ def isatty
should "not error if given a non-string" do
assert_equal "true", Util.send(:wrap_logfmt_value, true)
end

should "handle UTF-8 characters encoded in ASCII-8BIT" do
expected_utf8_str = "\"é\"".dup.force_encoding(Encoding::UTF_8.name)
ascii_8bit_str = "é".dup.force_encoding(Encoding::ASCII_8BIT.name)

assert_equal expected_utf8_str, Util.send(:wrap_logfmt_value, ascii_8bit_str)
end
end
end
end

0 comments on commit 9092e9d

Please sign in to comment.