Skip to content

Commit e707cc8

Browse files
authored
fix: handle invalid strings when sanitizing (#739)
Fixes #733
1 parent bf7773f commit e707cc8

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

lib/honeybadger/util/sanitizer.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,13 @@ def can_dup?(obj)
206206
end
207207

208208
def inspected?(string)
209-
String(string) =~ /#<.*>/
209+
# Ensure string has valid encoding before pattern matching
210+
# to avoid ArgumentError with invalid byte sequences
211+
string = valid_encoding(string) unless valid_encoding?(string)
212+
string =~ /#<.*>/
213+
rescue
214+
# If any encoding error occurs, assume it's not inspected
215+
false
210216
end
211217
end
212218
end

spec/unit/honeybadger/util/sanitizer_spec.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,34 @@
9797
expect(described_class.new.sanitize(object)).to eq(object)
9898
end
9999

100+
it "handles objects with invalid byte sequences in their string representation" do
101+
# Create a string with invalid UTF-8 byte sequences
102+
invalid_string = (100..1000).to_a.pack("c*").force_encoding("utf-8")
103+
object = double(to_s: invalid_string)
104+
105+
# Should not raise an error
106+
expect { described_class.new.sanitize(object) }.not_to raise_error
107+
108+
# Should return sanitized string
109+
result = described_class.new.sanitize(object)
110+
expect(result).to be_a(String)
111+
expect(result.encoding).to eq(Encoding::UTF_8)
112+
expect(result.valid_encoding?).to be true
113+
end
114+
115+
it "handles objects with invalid byte sequences that look like inspect output" do
116+
# Create a string with invalid UTF-8 that starts with #<
117+
invalid_string = "#<Object \xFF\xFE>".force_encoding("utf-8")
118+
object = double(to_s: invalid_string)
119+
120+
# Should not raise an error
121+
expect { described_class.new.sanitize(object) }.not_to raise_error
122+
123+
# Should return sanitized class name since it looks like inspect output
124+
result = described_class.new.sanitize(object)
125+
expect(result).to eq("#<RSpec::Mocks::Double>")
126+
end
127+
100128
context "with bad encodings" do
101129
let(:string) { "hello ümlaut" }
102130
let(:binary) { string.dup.force_encoding(Encoding::BINARY) }

0 commit comments

Comments
 (0)