Skip to content

Commit 6324009

Browse files
Add error handling and test for regex timeouts (#107)
1 parent 5bb1912 commit 6324009

File tree

2 files changed

+27
-7
lines changed

2 files changed

+27
-7
lines changed

sonar-text-dotnet/src/SonarLint.Secrets.DotNet.UnitTests/DotNetOnly/RegexMatcherTest_NoJavaTests.cs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ woijwoj w woijw e
4343

4444
var actual = testSubject.FindIn(input);
4545

46-
actual.Count().Should().Be(2);
46+
actual.Count.Should().Be(2);
4747

4848
actual.First().StartIndex.Should().Be(9);
4949
actual.First().Length.Should().Be(3);
@@ -53,5 +53,19 @@ woijwoj w woijw e
5353
actual.Last().Length.Should().Be(6);
5454
actual.Last().Text.Should().Be("abcdef");
5555
}
56+
57+
[TestMethod]
58+
public void Find_RegexTimeout_DoesNotThrow()
59+
{
60+
const string pattern = @"([a-z]*)*";
61+
var input = string.Join("", Enumerable.Repeat("a", 10_000_000));
62+
var testSubject = new RegexMatcher(pattern);
63+
64+
// With this input the timeout is reached and an exception is thrown.
65+
// This test ensures that the exception is not propagated further.
66+
var actual = testSubject.FindIn(input);
67+
68+
actual.Count.Should().Be(0);
69+
}
5670
}
5771
}

sonar-text-dotnet/src/SonarLint.Secrets.DotNet/Rules/Matching/RegexMatcher.cs

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,13 +35,19 @@ public RegexMatcher(string stringPattern)
3535

3636
public List<Match> FindIn(string input)
3737
{
38-
List<Match> matches = new List<Match>();
39-
40-
foreach (MatchResult matchResult in pattern.Matches(input))
38+
var matches = new List<Match>();
39+
try
40+
{
41+
foreach (MatchResult matchResult in pattern.Matches(input))
42+
{
43+
// Note: hard-coded assumption that the text to highlight is in the second group (index = 1)
44+
var group = matchResult.Groups[1];
45+
matches.Add(new Match(group.Value, group.Index, group.Length));
46+
}
47+
}
48+
catch (RegexMatchTimeoutException)
4149
{
42-
// Note: hard-coded assumption that the text to highlight is in the second group (index = 1)
43-
var group = matchResult.Groups[1];
44-
matches.Add(new Match(group.Value, group.Index, group.Length));
50+
return matches;
4551
}
4652

4753
return matches;

0 commit comments

Comments
 (0)