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 13, 2024
1 parent 4de9313 commit 0a19160
Showing 1 changed file with 33 additions and 3 deletions.
36 changes: 33 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,38 @@ 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)
{
int i = 0;

while (i < path.Length)
{
int openBrace = path.IndexOf('{', i);

if (openBrace < 0)
{
return path;
}

int closeBrace = path.IndexOf('}', openBrace);

if (closeBrace < 0)
{
return path;
}

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

Check notice

Code scanning / CodeQL

String concatenation in loop Note

String concatenation in loop: use 'StringBuilder'.
i = openBrace + 2;
}

return path;
}

// add more rules
}
}

0 comments on commit 0a19160

Please sign in to comment.