Skip to content

Commit

Permalink
Harden heuristics against Regexp::TimeoutError errors (#6518)
Browse files Browse the repository at this point in the history
* Rescue Regexp::TimeoutError errors

Ruby 3.2 allows you to set a process global `Regexp.timeout = <time>` to limit the impact of poor regex and prevent ReDoS attacks. GitHub is now enforcing a timeout so we need to be sure to play nicely.

* Replace catastrophic backreferencing regex

* Skip test if Ruby < 3.2.0

* Add back ^

* Update regex
  • Loading branch information
lildude authored Sep 7, 2023
1 parent 916bd8f commit a0a6d59
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 1 deletion.
2 changes: 2 additions & 0 deletions lib/linguist/heuristics.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ def self.call(blob, candidates)
end

[] # No heuristics matched
rescue Regexp::TimeoutError
[] # Return nothing if we have a bad regexp which leads to a timeout enforced by Regexp.timeout in Ruby 3.2 or later
end

# Public: Get all heuristic definitions
Expand Down
2 changes: 1 addition & 1 deletion lib/linguist/heuristics.yml
Original file line number Diff line number Diff line change
Expand Up @@ -686,7 +686,7 @@ disambiguations:
- extensions: ['.stl']
rules:
- language: STL
pattern: '\A\s*solid(?=$|\s)(?:.|[\r\n])*?^endsolid(?:$|\s)'
pattern: '\A\s*solid(?:$|\s)[\s\S]*^endsolid(?:$|\s)'
- extensions: ['.sw']
rules:
- language: Sway
Expand Down
7 changes: 7 additions & 0 deletions test/test_heuristics.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ def test_symlink_empty
assert_equal [], Heuristics.call(file_blob("Markdown/symlink.md"), [Language["Markdown"]])
end

def test_no_match_if_regexp_timeout
skip("This test requires Ruby 3.2.0 or later") if Gem::Version.new(RUBY_VERSION) < Gem::Version.new('3.2.0')

Regexp.any_instance.stubs(:match).raises(Regexp::TimeoutError)
assert_equal [], Heuristics.call(file_blob("#{fixtures_path}/Generic/stl/STL/cube1.stl"), [Language["STL"]])
end

# alt_name is a file name that will be used instead of the file name of the
# original sample. This is used to force a sample to go through a specific
# heuristic even if its extension doesn't match.
Expand Down

0 comments on commit a0a6d59

Please sign in to comment.