Skip to content
Open
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
63 changes: 43 additions & 20 deletions DevProxy.Abstractions/Utils/ProxyUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public static class ProxyUtils
// all alpha must include 2 to allow for oauth2PermissionScopes
private static readonly Regex allAlphaRegex = new("^[a-z2]+$", RegexOptions.IgnoreCase);
private static readonly Regex deprecationRegex = new("^[a-z]+_v2$", RegexOptions.IgnoreCase);
private static readonly Regex functionCallRegex = new(@"^[a-z]+\(.*\)$", RegexOptions.IgnoreCase);
private static readonly Regex functionCallRegex = new(@"^[a-z][a-z0-9_.]*\(.*\)$", RegexOptions.IgnoreCase);

private static Assembly? _assembly;
private static string _productVersion = string.Empty;
Expand Down Expand Up @@ -264,12 +264,12 @@ public static string SanitizeUrl(string absoluteUrl)
});
// Split requestUrl into segments that can be sanitized individually
var urlSegments = resourceUrl.Split('/');
var sanitizedSegments = new string[urlSegments.Length];
for (var i = 0; i < urlSegments.Length; i++)
{
var segment = urlSegments[i];
var sanitizedSegment = SanitizePathSegment(i < 1 ? "" : urlSegments[i - 1], segment);
resourceUrl = resourceUrl.Replace(segment, sanitizedSegment, StringComparison.OrdinalIgnoreCase);
sanitizedSegments[i] = SanitizePathSegment(i < 1 ? "" : urlSegments[i - 1], urlSegments[i]);
}
resourceUrl = string.Join('/', sanitizedSegments);
}
return $"{uri.GetLeftPart(UriPartial.Authority)}/{parsedSample.QueryVersion}/{resourceUrl}{queryString}";
}
Expand Down Expand Up @@ -680,25 +680,25 @@ private static string SanitizePathSegment(string previousSegment, string segment
}

// Check if segment is in this form: users('<some-id>|<UPN>') and transform to users(<value>)
// or getOffice365ActiveUserDetail(period='D7') and transform to getOffice365ActiveUserDetail(period=<value>)
if (IsFunctionCall(segment))
{
var openingBracketIndex = segment.IndexOf('(', StringComparison.OrdinalIgnoreCase);
var textWithinBrackets = segment.Substring(
openingBracketIndex + 1,
segment.Length - 2
);
var sanitizedText = string.Join(',', textWithinBrackets
.Split(',')
.Select(text =>
{
if (text.Contains('=', StringComparison.OrdinalIgnoreCase))
var openingBracketIndex = segment.IndexOf('(', StringComparison.Ordinal);
var textWithinBrackets = segment[(openingBracketIndex + 1)..^1];
var sanitizedText = string.IsNullOrWhiteSpace(textWithinBrackets)
? string.Empty
: string.Join(',', SplitOutsideQuotes(textWithinBrackets, ',')
.Select(text =>
{
var key = text.Split('=')[0];
key = !IsAllAlpha(key) ? "<key>" : key;
return $"{key}=<value>";
}
return "<value>";
}));
var keyValue = SplitOutsideQuotes(text, '=');
if (keyValue.Count > 1)
{
var key = keyValue[0].Trim();
key = !IsAllAlpha(key) ? "<key>" : key;
return $"{key}=<value>";
}
return "<value>";
}));

return $"{segment[..openingBracketIndex]}({sanitizedText})";
}
Expand Down Expand Up @@ -731,6 +731,29 @@ private static string SanitizeQueryParameters(string queryString)

private static bool IsFunctionCall(string value) => functionCallRegex.IsMatch(value);

// Splits on the separator, ignoring separators inside OData single-quoted
// string literals (where a quote is escaped by doubling it)
private static List<string> SplitOutsideQuotes(string value, char separator)
{
var parts = new List<string>();
var inQuotes = false;
var start = 0;
for (var i = 0; i < value.Length; i++)
{
if (value[i] == '\'')
{
inQuotes = !inQuotes;
}
else if (value[i] == separator && !inQuotes)
{
parts.Add(value[start..i]);
start = i + 1;
}
}
parts.Add(value[start..]);
return parts;
}

private static bool IsPlaceHolderSegment(string segment)
{
return segment.StartsWith('{') && segment.EndsWith('}');
Expand Down
97 changes: 97 additions & 0 deletions DevProxy.Integration.Tests/GraphUtilsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using DevProxy.Plugins.Models;
using DevProxy.Plugins.Utils;
using Microsoft.Extensions.Logging.Abstractions;
using System.Net;
using System.Text;
using Xunit;

namespace DevProxy.Integration.Tests;
Expand Down Expand Up @@ -61,6 +65,99 @@ public void GetTokenizedUrl_NonPathAddressedUrl_PreservesExistingTokenization()
"/sites/{sites-id}/drive/items/{items-id}/content",
GraphUtils.GetTokenizedUrl("https://graph.microsoft.com/v1.0/sites/site-id/drive/items/item-id/content"));

[Theory]
[InlineData(
"https://graph.microsoft.com/v1.0/users('48d31887-5fad-4d73-a9f5-3c356e68a038')",
"/users(<value>)")]
[InlineData(
"https://graph.microsoft.com/v1.0/users('john@contoso.com')/messages",
"/users(<value>)/messages")]
Comment thread
waldekmastykarz marked this conversation as resolved.
Resolved
[InlineData(
"https://graph.microsoft.com/v1.0/applications(appId='46e6adf4-a9cf-4b60-9390-0ba6fb00bf6b')",
"/applications(appId=<value>)")]
[InlineData(
"https://graph.microsoft.com/v1.0/oauth2PermissionGrants('grant-id')",
"/oauth2PermissionGrants(<value>)")]
public void GetTokenizedUrl_KeyInParentheses_ReturnsTokenizedKey(string url, string expected) =>
Assert.Equal(expected, GraphUtils.GetTokenizedUrl(url));

[Theory]
[InlineData(
"https://graph.microsoft.com/v1.0/reports/getOffice365ActiveUserDetail(period='D7')",
"/reports/getOffice365ActiveUserDetail(period=<value>)")]
[InlineData(
"https://graph.microsoft.com/v1.0/me/calendarView/delta()",
"/me/calendarView/delta()")]
[InlineData(
"https://graph.microsoft.com/v1.0/me/drive/root/search(q='budget, 2024=final')",
"/me/drive/root/search(q=<value>)")]
[InlineData(
"https://graph.microsoft.com/v1.0/me/drive/root/search(q='O''Brien')",
"/me/drive/root/search(q=<value>)")]
[InlineData(
"https://graph.microsoft.com/v1.0/me/drive/items/1/getActivitiesByInterval(startDateTime='2017-01-01',endDateTime='2017-01-03',interval='day')",
"/me/drive/items/{items-id}/getActivitiesByInterval(startDateTime=<value>,endDateTime=<value>,interval=<value>)")]
[InlineData(
"https://graph.microsoft.com/beta/reports/microsoft.graph.getTeamsUserActivityUserDetail(date=2024-01-01)",
"/reports/microsoft.graph.getTeamsUserActivityUserDetail(date=<value>)")]
public void GetTokenizedUrl_FunctionWithParameters_ReturnsTokenizedParameters(string url, string expected) =>
Assert.Equal(expected, GraphUtils.GetTokenizedUrl(url));

[Fact]
public void GetTokenizedUrl_RepeatedSegmentValues_TokenizesEachSegmentIndependently() =>
Assert.Equal(
"/sites/root/lists/{lists-id}/items/{items-id}",
GraphUtils.GetTokenizedUrl("https://graph.microsoft.com/v1.0/sites/root/lists/1/items/1"));

[Theory]
[InlineData("/users/{users-id}/messages")]
[InlineData("/users(<value>)/messages")]
public async Task UpdateUserScopesAsync_OtherUserEndpoint_ReplacesMinimalScope(string url)
{
using var handler = new PermissionsHandler("""[{"value":"Mail.Read"},{"value":"Mail.Read.Shared"}]""");
using var httpClient = new HttpClient(handler);
var graphUtils = new GraphUtils(httpClient, NullLogger<GraphUtils>.Instance);

var scopes = await graphUtils.UpdateUserScopesAsync(
["Mail.Read"],
[new MethodAndUrl("GET", url)],
GraphPermissionsType.Delegated);

Assert.Equal(["Mail.Read.Shared"], scopes);
var requestUri = Assert.Single(handler.RequestUris);
Assert.Contains($"requesturl={url}", Uri.UnescapeDataString(requestUri.Query), StringComparison.Ordinal);
}

[Fact]
public async Task UpdateUserScopesAsync_NoOtherUserEndpoint_ReturnsOriginalScopes()
{
using var handler = new PermissionsHandler("[]");
using var httpClient = new HttpClient(handler);
var graphUtils = new GraphUtils(httpClient, NullLogger<GraphUtils>.Instance);

var scopes = await graphUtils.UpdateUserScopesAsync(
["Mail.Read"],
[new MethodAndUrl("GET", "/me/messages")],
GraphPermissionsType.Delegated);

Assert.Equal(["Mail.Read"], scopes);
Assert.Empty(handler.RequestUris);
}

private sealed class PermissionsHandler(string responseJson) : HttpMessageHandler
{
public List<Uri> RequestUris { get; } = [];

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
RequestUris.Add(request.RequestUri!);
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(responseJson, Encoding.UTF8, "application/json")
});
}
}

[Fact]
public void GetRequestsFromBatch_PathAddressedRequest_ReturnsIdAddressedUrl()
{
Expand Down
4 changes: 3 additions & 1 deletion DevProxy.Plugins/Utils/GraphUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ internal static string GetScopeTypeString(GraphPermissionsType type)

internal async Task<IEnumerable<string>> UpdateUserScopesAsync(IEnumerable<string> minimalScopes, IEnumerable<MethodAndUrl> endpoints, GraphPermissionsType permissionsType)
{
var userEndpoints = endpoints.Where(e => e.Url.Contains("/users/{", StringComparison.OrdinalIgnoreCase));
var userEndpoints = endpoints.Where(e =>
e.Url.Contains("/users/{", StringComparison.OrdinalIgnoreCase) ||
e.Url.Contains("/users(", StringComparison.OrdinalIgnoreCase));
if (!userEndpoints.Any())
{
return minimalScopes;
Expand Down
Loading