Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion src/Docs/ApiOperation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ public class ApiOperation
operation.Path = parts[1]
.MakePathRelativeToVersion()
.NormalizeIdSegments()
.NormalizeParameters()
.FixUserDrivePath()
.FixDriveShortcut()
.FixDriveShareId()
Expand Down
84 changes: 39 additions & 45 deletions src/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,45 +43,42 @@ public static string NormalizeIdSegments(this string path)
}

/// <summary>
/// Normalizes parameter names and values in API paths.
/// Converts a function path segment into a canonical form for comparison by
/// replacing every parameter value with a common placeholder token.
/// </summary>
/// <param name="path">The API path to normalize.</param>
/// <returns>The normalized API path.</returns>
public static string NormalizeParameters(this string path)
/// <param name="segment">The path segment to canonicalize.</param>
/// <returns>
/// The canonical form, e.g. <c>getAllRecordings(userId=*,startDateTime=*)</c>,
/// or the original segment if it is not a function segment.
/// </returns>
/// <remarks>
/// Function parameter values are formatted inconsistently in docs and OpenAPI
/// ({x}, '{x}', @x, '@x'), so only the function name and parameter names are
/// significant.
/// </remarks>
public static string CanonicalizeFunctionSegment(this string segment)
{
var newPath = path;

// Extract parameters if present
var parameterListMatches = ParameterListRegex().Matches(path);

foreach (var parameterListMatch in parameterListMatches.ToList())
var match = FunctionSegmentRegex().Match(segment);
if (!match.Success)
{
var parameterList = parameterListMatch.Groups[1].Value;

var parameterValuePairMatches = ParameterValuePairRegex().Matches(parameterList);
return segment;
}

var parameters = new List<string>();
var parameterList = match.Groups["params"].Value;
if (string.IsNullOrWhiteSpace(parameterList))
{
return $"{match.Groups["name"].Value}()";
}

foreach (var parameterValuePairMatch in parameterValuePairMatches.ToList())
var parameters = parameterList
.Split(',', StringSplitOptions.TrimEntries)
.Select(p =>
{
var parameterName = parameterValuePairMatch.Groups.GetValueOrDefault("param")?.Value;
var valueName = parameterValuePairMatch.Groups.GetValueOrDefault("value")?.Value;

if (!string.IsNullOrEmpty(valueName) && valueName.StartsWith('@'))
{
parameters.Add($"{parameterName}='@{parameterName}'");
}
else
{
parameters.Add($"{parameterName}='{{{parameterName}}}'");
}
}
var equalsIndex = p.IndexOf('=');
return equalsIndex < 0 ? "*" : $"{p[..equalsIndex].Trim()}=*";
});

var newParameterList = string.Join(',', parameters);
newPath = newPath.Replace(parameterList, newParameterList);
}

return newPath;
return $"{match.Groups["name"].Value}({string.Join(',', parameters)})";
}

/// <summary>
Expand Down Expand Up @@ -197,15 +194,15 @@ public static bool IsEqualIgnoringCase(this string value, string compareTo)
{
int compareValue = string.Compare(value, compareTo, StringComparison.InvariantCultureIgnoreCase);

// Handle inconsistent formatting for function parameters in OpenAPI
// Sometimes value placeholders are like '{value}',
// Sometimes just like {value}
if (compareValue != 0 && value.Contains('(') && value.Contains('{') && compareTo.Contains('(') && compareTo.Contains('{'))
// Function parameter values are formatted inconsistently across docs
// and OpenAPI ({value}, '{value}', @value, '@value'), so compare only
// the function and parameter names
if (compareValue != 0 && value.Contains('(') && compareTo.Contains('('))
{
var pattern = $"^{compareTo.Replace("'", "'?").Replace("(", "\\(").Replace(")", "\\)")}$";
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
var isMatch = regex.IsMatch(value);
return isMatch;
return string.Equals(
value.CanonicalizeFunctionSegment(),
compareTo.CanonicalizeFunctionSegment(),
StringComparison.InvariantCultureIgnoreCase);
}

return compareValue == 0;
Expand All @@ -214,11 +211,8 @@ public static bool IsEqualIgnoringCase(this string value, string compareTo)
[GeneratedRegex("\\/{[^{}]*id[^{}]*}", RegexOptions.IgnoreCase)]
private static partial Regex IdSegmentRegex();

[GeneratedRegex("\\(((?>\\w*='?\\{?[\\w@-]*\\}?'?,?)+)\\)")]
private static partial Regex ParameterListRegex();

[GeneratedRegex("(?<param>\\w*)='?(?<value>\\{?[\\w@-]*\\}?)'?")]
private static partial Regex ParameterValuePairRegex();
[GeneratedRegex("^(?<name>[^()]+)\\((?<params>[^()]*)\\)$")]
private static partial Regex FunctionSegmentRegex();

[GeneratedRegex("^\\/users\\/{id}\\/drive\\/")]
private static partial Regex UsersDriveRegex();
Expand Down
17 changes: 16 additions & 1 deletion src/OpenAPI/OpenAPIOverrides.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT license.

using System.Text.Json;
using CheckCloudSupport.Extensions;

namespace CheckCloudSupport.OpenAPI;

Expand Down Expand Up @@ -32,7 +33,7 @@ public static void Initialize(string? overridesFile, string? excludesFile)
/// <returns>The override path.</returns>
public static string CheckForOverride(string originalPath, HttpMethod? method)
{
var apiOverride = overrides?.SingleOrDefault(o => string.Compare(o.ApiPath?.ToLower(), originalPath.ToLower()) == 0);
var apiOverride = overrides?.SingleOrDefault(o => PathsMatch(o.ApiPath, originalPath));
if (!string.IsNullOrEmpty(apiOverride?.Operation) &&
method != null &&
string.Compare(apiOverride.Operation, method.Method, StringComparison.OrdinalIgnoreCase) != 0)
Expand Down Expand Up @@ -71,6 +72,20 @@ public static bool CheckIfCloudExcludedForFile(string fileName, string cloud)
string.Compare(e.Cloud, cloud, StringComparison.InvariantCultureIgnoreCase) == 0) ?? false;
}

private static bool PathsMatch(string? overridePath, string apiPath)
{
if (overridePath == null)
{
return false;
}

var overrideSegments = overridePath.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var apiSegments = apiPath.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);

return overrideSegments.Length == apiSegments.Length &&
overrideSegments.Zip(apiSegments).All(s => s.First.IsEqualIgnoringCase(s.Second));
}

private static void LoadOverridesFromJson(string? jsonFile)
{
if (!string.IsNullOrEmpty(jsonFile))
Expand Down
16 changes: 16 additions & 0 deletions test/OpenAPIOverridesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,22 @@ public void CheckForOverride_MatchesCaseInsensitively()
Assert.Equal("/places/{id}/graph.room", result);
}

[Theory]
[InlineData("/identityGovernance/entitlementManagement/subjects(objectId={objectId})")]
[InlineData("/identityGovernance/entitlementManagement/subjects(objectId='@objectId')")]
public void CheckForOverride_MatchesFunctionParameterVariations(string path)
{
var result = OpenAPIOverrides.CheckForOverride(path, HttpMethod.Get);
Assert.Equal("/identityGovernance/entitlementManagement/subjects(objectId='{objectId}')/subject", result);
}

[Fact]
public void CheckForOverride_DoesNotMatchPathPrefix()
{
var result = OpenAPIOverrides.CheckForOverride("/places/{id}/checkIns", HttpMethod.Get);
Assert.Equal("/places/{id}/checkIns", result);
}

[Fact]
public void CheckIfCloudExcluded_TrueWhenPathMethodCloudMatch()
{
Expand Down
43 changes: 43 additions & 0 deletions test/OpenApiUrlTreeNodeExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,49 @@ public async Task GetNodeByPath_ReturnsNullForUnknownPath()
Assert.Null(node);
}

[Theory]
// OpenAPI {x}; docs '{x}'
[InlineData("GET /reports/getEmailActivityUserDetail(date='{date}')", "getEmailActivityUserDetail(date={date})")]
// OpenAPI '{x}' on a key-as-segment; docs {x}
[InlineData("GET /applications(appId={appId})", "applications(appId='{appId}')")]
// OpenAPI mixed '{x}' and {x}; docs with quoting reversed
[InlineData("GET /reports/getUserArchivedPrintJobs(userId={userId},startDateTime='{startDateTime}',endDateTime='{endDateTime}')", "getUserArchivedPrintJobs(userId='{userId}',startDateTime={startDateTime},endDateTime={endDateTime})")]
// OpenAPI mixed '@x' and @x; docs {x}
[InlineData("GET /users/{usersId}/adhocCalls/getAllRecordings(userId={userId},startDateTime={startDateTime},endDateTime={endDateTime})", "getAllRecordings(userId='@userId',startDateTime=@startDateTime,endDateTime=@endDateTime)")]
// OpenAPI mixed '@x' and @x; docs @x with quoting reversed
[InlineData("GET /users/{usersId}/adhocCalls/getAllRecordings(userId=@userId,startDateTime='@startDateTime',endDateTime='@endDateTime')", "getAllRecordings(userId='@userId',startDateTime=@startDateTime,endDateTime=@endDateTime)")]
// OpenAPI '@x'; docs '{x}'
[InlineData("GET /teams/{team-id}/primaryChannel/doesUserHaveAccess(userId='{userId}',tenantId='{tenantId}',userPrincipalName='{userPrincipalName}')", "doesUserHaveAccess(userId='@userId',tenantId='@tenantId',userPrincipalName='@userPrincipalName')")]
// OpenAPI mixed '{x}' and '@x'; docs {x}
[InlineData("GET /copilot/reports/getMicrosoft365CopilotUserCountTrend(period={period},version={version})", "getMicrosoft365CopilotUserCountTrend(period='{period}',version='@version')")]
// Chained functions; OpenAPI has image() overloads with 1, 2, and 3 parameters
[InlineData("GET /drives/{drive-id}/items/{item-id}/workbook/worksheets/{id}/charts/item(name={name})/image(width={width},height={height})", "image(width={width},height={height})")]
public async Task GetNodeByPath_MatchesFunctionVariations(string httpLine, string expectedSegment)
{
/**
* This test ensures that the GetNodeByPath method correctly matches function variations
* with parentheses and parameters in the path. Functions are documented inconsistently in
* Graph documentation - sometimes placeholders are wrapped with curly braces, sometimes
* preceded by @, and sometimes surrounded by single-quotes. This is complicated further
* by the fact that they are formatted inconsistently in the OpenAPI specification itself.
*/
var settings = new OpenApiReaderSettings();
settings.AddYamlReader();

var tree = OpenApiUrlTreeNode.Create();

using var stream = File.OpenRead("../../../test-data/openapi-functions.yml");
var loadResult = await OpenApiDocument.LoadAsync(stream, settings: settings);
Assert.NotNull(loadResult.Document);
tree.Attach(loadResult.Document!, "Global");

var operation = BuildOperation(httpLine);

var node = tree.GetNodeByPath(operation, "microsoft.graph");
Assert.NotNull(node);
Assert.Equal(expectedSegment, node!.Segment);
}

[Fact]
public async Task GetCloudSupportStatus_ReturnsGlobalWhenOnlyGlobal()
{
Expand Down
41 changes: 28 additions & 13 deletions test/StringExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,6 @@ namespace CheckCloudSupportTests;

public class StringExtensionsTests
{
[Fact]
public void ParameterNormalizationSucceeds()
{
// Arrange
var path = "/identityGovernance/entitlementManagement/assignments/additionalAccess(accessPackageId='parameterValue',incompatibleAccessPackageId='parameterValue')";

// Act
var normalizedPath = path.NormalizeParameters();

// Assert
Assert.Equal("/identityGovernance/entitlementManagement/assignments/additionalAccess(accessPackageId='{accessPackageId}',incompatibleAccessPackageId='{incompatibleAccessPackageId}')", normalizedPath);
}

[Fact]
public void OneDriveShortcutFixSucceeds()
{
Expand Down Expand Up @@ -208,4 +195,32 @@ public void IsEqualIgnoringCase_MatchesFunctionParametersWithInconsistentQuoting

Assert.True(value.IsEqualIgnoringCase(compareTo));
}

[Theory]
[InlineData("getAllRecordings(userId='@userId',startDateTime=@startDateTime)", "getAllRecordings(userId='{userId}',startDateTime='{startDateTime}')", true)]
[InlineData("getAllRecordings(userId={userId},startDateTime={startDateTime})", "getAllRecordings(userId=@userId,startDateTime='@startDateTime')", true)]
[InlineData("GETALLRECORDINGS(USERID=@userId)", "getAllRecordings(userId='{userId}')", true)]
[InlineData("getAllRecordings(userId='{userId}')", "getAllTranscripts(userId='{userId}')", false)]
[InlineData("getAllRecordings(userId='{userId}')", "getAllRecordings(meetingOrganizerUserId='{meetingOrganizerUserId}')", false)]
[InlineData("getAllRecordings(userId='{userId}',startDateTime='{startDateTime}')", "getAllRecordings(startDateTime='{startDateTime}',userId='{userId}')", false)]
[InlineData("getAllRecordings(userId='{userId}')", "getAllRecordings(userId='{userId}',startDateTime='{startDateTime}')", false)]
public void IsEqualIgnoringCase_MatchesFunctionParameterVariations(string value, string compareTo, bool expected)
{
Assert.Equal(expected, value.IsEqualIgnoringCase(compareTo));
}

[Theory]
[InlineData("getAllRecordings(userId={userId},startDateTime={startDateTime})", "getAllRecordings(userId=*,startDateTime=*)")]
[InlineData("getAllRecordings(userId='{userId}',startDateTime='{startDateTime}')", "getAllRecordings(userId=*,startDateTime=*)")]
[InlineData("getAllRecordings(userId=@userId,startDateTime=@startDateTime)", "getAllRecordings(userId=*,startDateTime=*)")]
[InlineData("getAllRecordings(userId='@userId',startDateTime=@startDateTime)", "getAllRecordings(userId=*,startDateTime=*)")]
[InlineData("getAllRecordings(userId = '{userId}' , startDateTime = @startDateTime)", "getAllRecordings(userId=*,startDateTime=*)")]
[InlineData("microsoft.graph.getUsage()", "microsoft.graph.getUsage()")]
[InlineData("getByIds('{id}')", "getByIds(*)")]
[InlineData("messages", "messages")]
[InlineData("{user-id}", "{user-id}")]
public void CanonicalizeFunctionSegment_NormalizesParameterValues(string segment, string expected)
{
Assert.Equal(expected, segment.CanonicalizeFunctionSegment());
}
}
Loading