From d4232b91c4a19bc5a00f048acdf1df12d6c8175e Mon Sep 17 00:00:00 2001 From: Hamza Tarar Date: Tue, 17 Nov 2026 01:58:11 +0500 Subject: [PATCH] Do not raise ArgumentError on an argument with invalid bytes Regexp#=== raises ArgumentError for a string that is not valid in its encoding, and parse_in_order matches every argument against the option patterns before it can tell whether the argument is an option. A single bad byte in ARGV therefore took the parser down, including on arguments optparse would have returned untouched, such as a file name from a system using another encoding. Switch#parse_arg had the same problem when matching a switch's pattern against its value. Match a binary copy at both sites. Option syntax is ASCII, so the structure still parses and the bytes are passed on as they arrived. Only arguments that raise today are affected. String#rindex is the reason parse_arg needs this too: on an invalid UTF-8 string it does not raise, it fails to find a substring the string does contain, so converting back before that line would turn the crash into a spurious InvalidArgument. --- lib/optparse.rb | 12 +++++++ test/optparse/test_invalid_encoding.rb | 47 ++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 test/optparse/test_invalid_encoding.rb diff --git a/lib/optparse.rb b/lib/optparse.rb index 97178e2..bae97fd 100644 --- a/lib/optparse.rb +++ b/lib/optparse.rb @@ -563,6 +563,10 @@ def initialize(pattern = nil, conv = nil, # private def parse_arg(arg) # :nodoc: pattern or return nil, [arg] + # As in #parse_in_order: an argument that is not valid in its encoding + # would make Regexp#match raise, and String#rindex below fail to find a + # substring it does contain. + arg = arg.b unless arg.valid_encoding? unless m = pattern.match(arg) yield(InvalidArgument, arg) return arg, [] @@ -1733,6 +1737,14 @@ def order!(argv = default_argv, into: nil, **keywords, &nonopt) nonopt ||= proc {|a| throw :terminate, a} argv.unshift(arg) if arg = catch(:terminate) { while arg = argv.shift + # Ruby passes arguments through ARGV as the bytes it was given, so one + # can hold bytes that are not valid in its encoding, such as a file + # name from another system. Matching such a string raises + # ArgumentError from Regexp#===, before optparse can decide whether it + # is an option at all, so treat it as the bytes it is. Only arguments + # that raise today are affected. + arg = arg.b unless arg.valid_encoding? + case arg # long option when /\A--([^=]*)(?:=(.*))?/m diff --git a/test/optparse/test_invalid_encoding.rb b/test/optparse/test_invalid_encoding.rb new file mode 100644 index 0000000..3a280e4 --- /dev/null +++ b/test/optparse/test_invalid_encoding.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: false +require_relative 'test_optparse' + +class TestOptionParserInvalidEncoding < TestOptionParser + # Ruby passes arguments through ARGV as the bytes it was given, so an + # argument can hold bytes that are not valid in its encoding, such as a + # file name from a system using another one. + INVALID = "caf\xE9.txt".force_encoding(Encoding::UTF_8) + + def setup + super + @opt.def_option("-n", "--name=NAME") {|x| @flag = x} + @opt.def_option("-v", "--verbose") {|x| @flag = x} + assert_not_predicate(INVALID, :valid_encoding?) + end + + def test_non_option_argument_is_left_alone + rest = no_error {@opt.parse!([INVALID.dup])} + assert_equal([INVALID.bytes], rest.map(&:bytes)) + assert_equal(self.class, @flag) + end + + def test_option_argument_joined_by_equals + assert_empty(no_error {@opt.parse!(["--name=#{INVALID}"])}) + assert_equal(INVALID.bytes, @flag.bytes) + end + + def test_option_argument_in_the_next_element + assert_empty(no_error {@opt.parse!(["--name", INVALID.dup])}) + assert_equal(INVALID.bytes, @flag.bytes) + end + + def test_short_option_argument + assert_empty(no_error {@opt.parse!(["-n#{INVALID}"])}) + assert_equal(INVALID.bytes, @flag.bytes) + end + + def test_option_before_a_non_option_argument + rest = no_error {@opt.parse!(["--verbose", INVALID.dup])} + assert_equal([INVALID.bytes], rest.map(&:bytes)) + assert_equal(true, @flag) + end + + def test_an_unknown_option_still_raises_parse_error + assert_raise(OptionParser::InvalidOption) {@opt.parse!(["--bogus", INVALID.dup])} + end +end