From 9092e9dbabc5d53ca3faf22b16370fffe168b896 Mon Sep 17 00:00:00 2001 From: Dominic Charley-Roy <78050200+dcr-stripe@users.noreply.github.com> Date: Tue, 21 Jun 2022 16:35:46 -0400 Subject: [PATCH] fix: Update logging to coerce ASCII-8BIT into UTF-8. (#1076) --- lib/stripe/util.rb | 9 +++++++++ test/stripe/util_test.rb | 7 +++++++ 2 files changed, 16 insertions(+) diff --git a/lib/stripe/util.rb b/lib/stripe/util.rb index ece84a040..70f32837e 100644 --- a/lib/stripe/util.rb +++ b/lib/stripe/util.rb @@ -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. diff --git a/test/stripe/util_test.rb b/test/stripe/util_test.rb index 71b6435e1..d4812f385 100644 --- a/test/stripe/util_test.rb +++ b/test/stripe/util_test.rb @@ -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