Skip to content

Commit

Permalink
Replaced RegEx with IndexOf/Substring to avoid RegexMatchTimeoutExcep…
Browse files Browse the repository at this point in the history
…tion
  • Loading branch information
mthesing88 authored and mus65 committed Jan 15, 2024
1 parent 4de9313 commit a99baf2
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Properties;

Expand Down Expand Up @@ -36,7 +35,6 @@ public static class OpenApiPathsRules
}
});

private static readonly Regex regexPath = new Regex("\\{([^/}]+)\\}", RegexOptions.Compiled, TimeSpan.FromMilliseconds(100));
/// <summary>
/// A relative path to an individual endpoint. The field name MUST begin with a slash.
/// </summary>
Expand All @@ -50,7 +48,7 @@ public static class OpenApiPathsRules
{
context.Enter(path);

var pathSignature = regexPath.Replace(path, "{}");
var pathSignature = GetPathSignature(path);

if (!hashSet.Add(pathSignature))
context.CreateError(nameof(PathMustBeUnique),
Expand All @@ -60,6 +58,28 @@ public static class OpenApiPathsRules
}
});

/// <summary>
/// Replaces placeholders in the path with {}, e.g. /pets/{petId} becomes /pets/{} .
/// </summary>
/// <param name="path">The input path</param>
/// <returns>The path signature</returns>
private static string GetPathSignature(string path)
{
for (int openBrace = path.IndexOf('{'); openBrace > -1; openBrace = path.IndexOf('{', openBrace + 2))
{
int closeBrace = path.IndexOf('}', openBrace);

if (closeBrace < 0)
{
return path;
}

path = path.Substring(0, openBrace + 1) + path.Substring(closeBrace);

Check notice

Code scanning / CodeQL

String concatenation in loop Note

String concatenation in loop: use 'StringBuilder'.
}

return path;
}

// add more rules
}
}

0 comments on commit a99baf2

Please sign in to comment.