From 661effe84b2b0abe6003d47a83f76c1396442b92 Mon Sep 17 00:00:00 2001 From: Andrew Konchin Date: Mon, 2 Dec 2024 15:40:30 +0200 Subject: [PATCH] Improve validation of a Time.new single String argument --- spec/ruby/core/time/new_spec.rb | 26 +++++++++++++++++++ .../core/truffle/time_operations.rb | 2 +- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/spec/ruby/core/time/new_spec.rb b/spec/ruby/core/time/new_spec.rb index c310a8631e26..24bb9fde0caf 100644 --- a/spec/ruby/core/time/new_spec.rb +++ b/spec/ruby/core/time/new_spec.rb @@ -564,6 +564,12 @@ def obj.to_int; 3; end Time.new("2020-12-25") }.should raise_error(ArgumentError, /no time information|can't parse:/) end + + it "raises ArgumentError if day is missing" do + -> { + Time.new("2020-12") + }.should raise_error(ArgumentError, /no time information|can't parse:/) + end end it "raises ArgumentError if subsecond is missing after dot" do @@ -679,6 +685,26 @@ def obj.to_int; 3; end Time.new("2021-11-31 00:00:59 +09:00 abc") }.should raise_error(ArgumentError, /can't parse.+ abc/) end + + ruby_version_is "3.2.3" do + it "raises ArgumentError when there are leading space characters" do + -> { Time.new(" 2020-12-02 00:00:00") }.should raise_error(ArgumentError, /can't parse/) + -> { Time.new("\t2020-12-02 00:00:00") }.should raise_error(ArgumentError, /can't parse/) + -> { Time.new("\n2020-12-02 00:00:00") }.should raise_error(ArgumentError, /can't parse/) + -> { Time.new("\v2020-12-02 00:00:00") }.should raise_error(ArgumentError, /can't parse/) + -> { Time.new("\f2020-12-02 00:00:00") }.should raise_error(ArgumentError, /can't parse/) + -> { Time.new("\r2020-12-02 00:00:00") }.should raise_error(ArgumentError, /can't parse/) + end + + it "raises ArgumentError when there are trailing whitespaces" do + -> { Time.new("2020-12-02 00:00:00 ") }.should raise_error(ArgumentError, /can't parse/) + -> { Time.new("2020-12-02 00:00:00\t") }.should raise_error(ArgumentError, /can't parse/) + -> { Time.new("2020-12-02 00:00:00\n") }.should raise_error(ArgumentError, /can't parse/) + -> { Time.new("2020-12-02 00:00:00\v") }.should raise_error(ArgumentError, /can't parse/) + -> { Time.new("2020-12-02 00:00:00\f") }.should raise_error(ArgumentError, /can't parse/) + -> { Time.new("2020-12-02 00:00:00\r") }.should raise_error(ArgumentError, /can't parse/) + end + end end end end diff --git a/src/main/ruby/truffleruby/core/truffle/time_operations.rb b/src/main/ruby/truffleruby/core/truffle/time_operations.rb index 47152a79e346..d3c80f7516d0 100644 --- a/src/main/ruby/truffleruby/core/truffle/time_operations.rb +++ b/src/main/ruby/truffleruby/core/truffle/time_operations.rb @@ -104,7 +104,7 @@ def self.new_from_string(time_class, str, **options) : (? \d{2}) : (? \d{2}) (?:\. (? \d+) )? - \s* (?\S+)? + (?:\s* (?\S+))? )?\z/x =~ str return self.compose(time_class, self.utc_offset_for_compose(offset || options[:in]), year, month, mday, hour, min, sec, usec) end