Commit 1b33df2f authored by Grzegorz Bizon's avatar Grzegorz Bizon
Browse files

Simplify untrusted regexp factory method

parent 646ef43c1097
......@@ -55,7 +55,7 @@ def self.with_fallback(pattern, multiline: false)
end
def self.valid?(pattern)
self.fabricate(pattern)
!!self.fabricate(pattern)
rescue RegexpError
false
end
......@@ -63,16 +63,13 @@ def self.valid?(pattern)
def self.fabricate(pattern)
matches = pattern.match(%r{^/(?<regexp>.+)/(?<flags>[ismU]*)$})
if matches
expression = matches[:regexp]
flags = matches[:flags]
raise RegexpError, 'Invalid regular expression!' if matches.nil?
expression.prepend("(?#{flags})") if flags.present?
expression = matches[:regexp]
flags = matches[:flags]
expression.prepend("(?#{flags})") if flags.present?
self.new(expression, multiline: false)
else
self.new(pattern, multiline: false)
end
self.new(expression, multiline: false)
end
private
......
......@@ -79,7 +79,7 @@
describe '#evaluate' do
it 'returns a regular expression' do
regexp = described_class.new('abc')
regexp = described_class.new('/abc/')
expect(regexp.evaluate).to eq Gitlab::UntrustedRegexp.new('abc')
end
......@@ -87,7 +87,7 @@
it 'raises error if evaluated regexp is not valid' do
allow(Gitlab::UntrustedRegexp).to receive(:valid?).and_return(true)
regexp = described_class.new('invalid ( .*')
regexp = described_class.new('/invalid ( .*/')
expect { regexp.evaluate }
.to raise_error(Gitlab::Ci::Pipeline::Expression::RuntimeError)
......
......@@ -4,9 +4,13 @@
describe Gitlab::UntrustedRegexp do
describe '.valid?' do
it 'returns true if regexp is valid' do
expect(described_class.valid?('/some ( thing/'))
.to be false
end
it 'returns true if regexp is invalid' do
expect(described_class.valid?('/some .* thing/'))
.to be true
end
end
......@@ -32,17 +36,9 @@
end
end
context 'when regexp is not plain pattern' do
it 'fabricates regexp without flags' do
regexp = described_class.fabricate('something')
expect(regexp).to eq described_class.new('something')
end
end
context 'when regexp is invalid' do
context 'when regexp is a raw pattern' do
it 'raises an error' do
expect { described_class.fabricate('/some ( thing/') }
expect { described_class.fabricate('some .* thing') }
.to raise_error(RegexpError)
end
end
......
require 'timeout'
shared_examples 'malicious regexp' do
let(:malicious_text) { 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!' }
let(:malicious_regexp) { '(?i)^(([a-z])+.)+[A-Z]([a-z])+$' }
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment