Module: Enumpath::RegexpTimeout
- Defined in:
- lib/enumpath/regexp_timeout.rb
Overview
Bounds how long a regular expression in a filter expression may run. A pattern with a backreference, such as
/^(a*)*\1$/, can take exponential time to match a short string, so a hostile or careless path could hang the
process.
The limit uses the timeout of Regexp.new, which needs Ruby 3.2 or later. Older Rubies have no protection and
ignore the limit. Once one match runs out of time, every later regular expression match in the same
apply call is skipped and does not match, so the total delay is bounded by one limit, not one limit per
member of the data.
Defined Under Namespace
Classes: State
Constant Summary collapse
- DEFAULT =
The limit in seconds when Enumpath.apply is not given a
:regexp_timeout 1.0- SUPPORTED =
Whether this Ruby can limit regular expressions
Regexp.respond_to?(:timeout)
- ERROR =
Raised when a match ran out of time, or when an earlier match in the same call did
SUPPORTED ? Regexp::TimeoutError : Class.new(StandardError)
- THREAD_KEY =
The
Thread.currentkey that holds the State for the current Enumpath.apply call :enumpath_regexp_timeout
Class Method Summary collapse
-
.limit(regexp) ⇒ Regexp
Returns the regular expression with the current limit applied.
Class Method Details
.limit(regexp) ⇒ Regexp
Returns the regular expression with the current limit applied
53 54 55 56 57 58 59 60 61 |
# File 'lib/enumpath/regexp_timeout.rb', line 53 def limit(regexp) state = Thread.current[THREAD_KEY] raise ERROR, 'an earlier regular expression ran out of time' if state&.expired seconds = state ? state.seconds : DEFAULT return regexp unless SUPPORTED && seconds Regexp.new(regexp.source, regexp., timeout: seconds) end |