Skip to content

Commit 43253d8

Browse files
baywetCopilot
andauthored
fix(http): align default middleware order (#884)
* fix(http): align default middleware order Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e625fa94-4ae9-464b-8e28-fddf64a8999d * fix(http): resolve relative redirects against the full request URI Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e625fa94-4ae9-464b-8e28-fddf64a8999d --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e625fa94-4ae9-464b-8e28-fddf64a8999d
1 parent a7ad03e commit 43253d8

8 files changed

Lines changed: 159 additions & 44 deletions

File tree

‎src/http/httpClient/KiotaClientFactory.cs‎

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ namespace Microsoft.Kiota.Http.HttpClientLibrary
2222
public static class KiotaClientFactory
2323
{
2424
/// <summary>
25-
/// Initializes the <see cref="HttpClient"/> with the default configuration and middlewares including a authentication middleware using the <see cref="IAuthenticationProvider"/> if provided.
25+
/// Initializes the <see cref="HttpClient"/> with the default configuration and middleware, without authorization middleware.
2626
/// </summary>
2727
/// <param name="finalHandler">The final <see cref="HttpMessageHandler"/> in the http pipeline. Can be configured for proxies, auto-decompression and auto-redirects </param>
2828
/// <param name="optionsForHandlers">A array of <see cref="IRequestOption"/> objects passed to the default handlers.</param>
@@ -50,16 +50,17 @@ public static HttpClient Create(IList<DelegatingHandler> handlers, HttpMessageHa
5050
/// <returns></returns>
5151
public static HttpClient Create(BaseBearerTokenAuthenticationProvider authenticationProvider, IRequestOption[]? optionsForHandlers = null, HttpMessageHandler? finalHandler = null)
5252
{
53-
var defaultHandlersEnumerable = CreateDefaultHandlers(optionsForHandlers);
54-
defaultHandlersEnumerable.Add(new AuthorizationHandler(authenticationProvider));
55-
return Create(defaultHandlersEnumerable, finalHandler);
53+
return Create(CreateDefaultHandlers(optionsForHandlers, new AuthorizationHandler(authenticationProvider)), finalHandler);
5654
}
5755

5856
/// <summary>
5957
/// Creates a default set of middleware to be used by the <see cref="HttpClient"/>.
6058
/// </summary>
6159
/// <returns>A list of the default handlers used by the client.</returns>
6260
public static IList<DelegatingHandler> CreateDefaultHandlers(IRequestOption[]? optionsForHandlers = null)
61+
=> CreateDefaultHandlers(optionsForHandlers, null);
62+
63+
private static IList<DelegatingHandler> CreateDefaultHandlers(IRequestOption[]? optionsForHandlers, AuthorizationHandler? authorizationHandler)
6364
{
6465
optionsForHandlers ??= Array.Empty<IRequestOption>();
6566

@@ -89,16 +90,19 @@ public static IList<DelegatingHandler> CreateDefaultHandlers(IRequestOption[]? o
8990
bodyInspectionHandlerOption = bodyInspectionOption;
9091
}
9192

92-
return new List<DelegatingHandler>
93+
var handlers = new List<DelegatingHandler>
9394
{
9495
uriReplacementOption != null ? new UriReplacementHandler<UriReplacementHandlerOption>(uriReplacementOption) : new UriReplacementHandler<UriReplacementHandlerOption>(),
95-
retryHandlerOption != null ? new RetryHandler(retryHandlerOption) : new RetryHandler(),
96-
redirectHandlerOption != null ? new RedirectHandler(redirectHandlerOption) : new RedirectHandler(),
9796
parametersNameDecodingOption != null ? new ParametersNameDecodingHandler(parametersNameDecodingOption) : new ParametersNameDecodingHandler(),
9897
userAgentHandlerOption != null ? new UserAgentHandler(userAgentHandlerOption) : new UserAgentHandler(),
99-
headersInspectionHandlerOption != null ? new HeadersInspectionHandler(headersInspectionHandlerOption) : new HeadersInspectionHandler(),
100-
bodyInspectionHandlerOption != null ? new BodyInspectionHandler(bodyInspectionHandlerOption) : new BodyInspectionHandler(),
10198
};
99+
if(authorizationHandler != null)
100+
handlers.Add(authorizationHandler);
101+
handlers.Add(redirectHandlerOption != null ? new RedirectHandler(redirectHandlerOption) : new RedirectHandler());
102+
handlers.Add(retryHandlerOption != null ? new RetryHandler(retryHandlerOption) : new RetryHandler());
103+
handlers.Add(headersInspectionHandlerOption != null ? new HeadersInspectionHandler(headersInspectionHandlerOption) : new HeadersInspectionHandler());
104+
handlers.Add(bodyInspectionHandlerOption != null ? new BodyInspectionHandler(bodyInspectionHandlerOption) : new BodyInspectionHandler());
105+
return handlers;
102106
}
103107

104108
/// <summary>
@@ -112,10 +116,10 @@ public static IList<DelegatingHandler> CreateDefaultHandlers(IRequestOption[]? o
112116
return new List<System.Type>
113117
{
114118
typeof(UriReplacementHandler<UriReplacementHandlerOption>),
115-
typeof(RetryHandler),
116-
typeof(RedirectHandler),
117119
typeof(ParametersNameDecodingHandler),
118120
typeof(UserAgentHandler),
121+
typeof(RedirectHandler),
122+
typeof(RetryHandler),
119123
typeof(HeadersInspectionHandler),
120124
typeof(BodyInspectionHandler),
121125
};
@@ -131,10 +135,10 @@ public static IList<ActivatableType> GetDefaultHandlerActivatableTypes()
131135
return new List<ActivatableType>()
132136
{
133137
new(typeof(UriReplacementHandler<UriReplacementHandlerOption>)),
134-
new(typeof(RetryHandler)),
135-
new(typeof(RedirectHandler)),
136138
new(typeof(ParametersNameDecodingHandler)),
137139
new(typeof(UserAgentHandler)),
140+
new(typeof(RedirectHandler)),
141+
new(typeof(RetryHandler)),
138142
new(typeof(HeadersInspectionHandler)),
139143
new(typeof(BodyInspectionHandler)),
140144
};
@@ -230,7 +234,7 @@ public static HttpMessageHandler GetDefaultHttpMessageHandler(IWebProxy? proxy =
230234
// If custom proxy is passed, the WindowsProxyUsePolicy will need updating
231235
// https://github.com/dotnet/runtime/blob/main/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs#L575
232236
var proxyPolicy = proxy != null ? WindowsProxyUsePolicy.UseCustomProxy : WindowsProxyUsePolicy.UseWinHttpProxy;
233-
return new WinHttpHandler { Proxy = proxy, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, WindowsProxyUsePolicy = proxyPolicy, SendTimeout = System.Threading.Timeout.InfiniteTimeSpan, ReceiveDataTimeout = System.Threading.Timeout.InfiniteTimeSpan, ReceiveHeadersTimeout = System.Threading.Timeout.InfiniteTimeSpan, EnableMultipleHttp2Connections = true };
237+
return new WinHttpHandler { Proxy = proxy, AutomaticRedirection = false, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, WindowsProxyUsePolicy = proxyPolicy, SendTimeout = System.Threading.Timeout.InfiniteTimeSpan, ReceiveDataTimeout = System.Threading.Timeout.InfiniteTimeSpan, ReceiveHeadersTimeout = System.Threading.Timeout.InfiniteTimeSpan, EnableMultipleHttp2Connections = true };
234238
#elif NET5_0_OR_GREATER && !BROWSER
235239
return new SocketsHttpHandler { Proxy = proxy, AllowAutoRedirect = false, EnableMultipleHttp2Connections = true, AutomaticDecompression = DecompressionMethods.All };
236240
#elif BROWSER

‎src/http/httpClient/Middleware/AuthorizationHandler.cs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
using System.Threading.Tasks;
1313
using Microsoft.Kiota.Abstractions.Authentication;
1414
using Microsoft.Kiota.Http.HttpClientLibrary.Extensions;
15+
using Microsoft.Kiota.Http.HttpClientLibrary.Middleware.Options;
1516

1617
namespace Microsoft.Kiota.Http.HttpClientLibrary.Middleware
1718
{
@@ -62,8 +63,14 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
6263
}
6364
Dictionary<string, object> additionalAuthenticationContext = new Dictionary<string, object>();
6465
await AuthenticateRequestAsync(request, additionalAuthenticationContext, activity, cancellationToken).ConfigureAwait(false);
66+
var originalUri = request.RequestUri;
6567
var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
66-
if(response.StatusCode != HttpStatusCode.Unauthorized || response.RequestMessage == null || !response.RequestMessage.IsBuffered())
68+
// A redirect may have removed authorization. Do not let a challenge extend it to another origin.
69+
if(response.StatusCode != HttpStatusCode.Unauthorized ||
70+
originalUri is not { IsAbsoluteUri: true } ||
71+
response.RequestMessage?.RequestUri is not { IsAbsoluteUri: true } challengedUri ||
72+
!RedirectHandlerOption.HaveSameOrigin(originalUri, challengedUri) ||
73+
!response.RequestMessage.IsBuffered())
6774
return response;
6875
// Attempt CAE claims challenge
6976
var claims = ContinuousAccessEvaluation.GetClaims(response);

‎src/http/httpClient/Middleware/Options/RedirectHandlerOption.cs‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,7 @@ public static void DefaultScrubSensitiveHeaders(HttpRequestMessage newRequest, U
6969
var newUri = newRequest.RequestUri ?? throw new InvalidOperationException("The request URI cannot be null.");
7070

7171
// Remove Authorization and Cookie headers if http request's scheme, host, or port changes
72-
var isDifferentOrigin = !newUri.Host.Equals(originalUri.Host, StringComparison.OrdinalIgnoreCase) ||
73-
!newUri.Scheme.Equals(originalUri.Scheme, StringComparison.OrdinalIgnoreCase) ||
74-
newUri.Port != originalUri.Port;
75-
if(isDifferentOrigin)
72+
if(!HaveSameOrigin(originalUri, newUri))
7673
{
7774
newRequest.Headers.Authorization = null;
7875
newRequest.Headers.Remove("Cookie");
@@ -87,5 +84,10 @@ public static void DefaultScrubSensitiveHeaders(HttpRequestMessage newRequest, U
8784
newRequest.Headers.ProxyAuthorization = null;
8885
}
8986
}
87+
88+
internal static bool HaveSameOrigin(Uri first, Uri second) =>
89+
first.Host.Equals(second.Host, StringComparison.OrdinalIgnoreCase) &&
90+
first.Scheme.Equals(second.Scheme, StringComparison.OrdinalIgnoreCase) &&
91+
first.Port == second.Port;
9092
}
9193
}

‎src/http/httpClient/Middleware/RedirectHandler.cs‎

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -69,17 +69,14 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
6969
// check response status code and redirect handler option
7070
if(ShouldRedirect(response, redirectOption))
7171
{
72-
if(response.Headers.Location == null)
73-
{
74-
throw new InvalidOperationException(
75-
"Unable to perform redirect as Location Header is not set in response",
76-
new Exception($"No header present in response with status code {response.StatusCode}"));
77-
}
78-
7972
var redirectCount = 0;
8073

8174
while(redirectCount < redirectOption.MaxRedirect)
8275
{
76+
var location = response.Headers.Location ?? throw new InvalidOperationException(
77+
"Unable to perform redirect as Location Header is not set in response",
78+
new Exception($"No header present in response with status code {response.StatusCode}"));
79+
8380
using var redirectActivity = activitySource?.StartActivity($"{nameof(RedirectHandler)}_{nameof(SendAsync)} - redirect {redirectCount}");
8481
redirectActivity?.SetTag("com.microsoft.kiota.handler.redirect.count", redirectCount);
8582
redirectActivity?.SetTag("http.response.status_code", response.StatusCode);
@@ -95,12 +92,15 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
9592

9693
// general clone request with internal CloneAsync (see CloneAsync for details) extension method
9794
var originalRequest = response.RequestMessage;
98-
if(originalRequest == null)
95+
if(originalRequest == null || originalRequest.RequestUri is not { } originalUri)
9996
{
10097
return response;// We can't clone the original request to replay it.
10198
}
10299
var newRequest = await originalRequest.CloneAsync(cancellationToken).ConfigureAwait(false);
103100

101+
// The next hop gets its own retry budget and attempt header.
102+
newRequest.Headers.Remove(RetryHandler.RetryAttempt);
103+
104104
if(RequestRequiresForceGet(response.StatusCode, newRequest.Method))
105105
{
106106
newRequest.Method = HttpMethod.Get;
@@ -109,20 +109,11 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
109109
newRequest.Headers.TransferEncodingChunked = false;
110110
}
111111

112-
// Set newRequestUri from response
113-
if(response.Headers.Location?.IsAbsoluteUri ?? false)
114-
{
115-
newRequest.RequestUri = response.Headers.Location;
116-
}
117-
else
118-
{
119-
var baseAddress = newRequest.RequestUri?.GetComponents(UriComponents.SchemeAndServer | UriComponents.KeepDelimiter, UriFormat.Unescaped);
120-
newRequest.RequestUri = new Uri(baseAddress + response.Headers.Location);
121-
}
112+
newRequest.RequestUri = location.IsAbsoluteUri ? location : new Uri(originalUri, location);
122113

123114
// Scrub sensitive headers before following the redirect
124115
var proxyResolver = GetProxyResolver();
125-
redirectOption.ScrubSensitiveHeaders(newRequest, originalRequest.RequestUri!, proxyResolver);
116+
redirectOption.ScrubSensitiveHeaders(newRequest, originalUri, proxyResolver);
126117

127118
// If scheme has changed. Ensure that this has been opted in for security reasons
128119
if(!newRequest.RequestUri.Scheme.Equals(request.RequestUri?.Scheme) && !redirectOption.AllowRedirectOnSchemeChange)

‎src/http/httpClient/Middleware/RetryHandler.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ namespace Microsoft.Kiota.Http.HttpClientLibrary.Middleware
2222
public class RetryHandler : DelegatingHandler
2323
{
2424
private const string RetryAfter = "Retry-After";
25-
private const string RetryAttempt = "Retry-Attempt";
25+
internal const string RetryAttempt = "Retry-Attempt";
2626

2727
/// <summary>
2828
/// RetryOption property

‎src/http/httpClient/README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ Read more about Kiota [here](https://github.com/microsoft/kiota/blob/main/README
1212
dotnet add package Microsoft.Kiota.Http.HttpClientLibrary
1313
```
1414

15+
The default middleware runs in this outbound order: URL replacement, query parameter name decoding, User-Agent, redirect, retry, headers inspection, and body inspection. The default transport handles response decompression. Each redirect hop has its own retry budget, and inspection runs for each attempt immediately before the transport.
16+
17+
For arbitrary HTTP requests, the `KiotaClientFactory.Create` overload that accepts a bearer token authentication provider adds authorization after User-Agent and before redirect. Generated clients authenticate in the request adapter and do not need that overload. The default redirect policy strips authorization when the origin changes, and a claims challenge from a different origin does not trigger authentication.
18+
1519
## Debugging
1620

1721
If you are using Visual Studio Code as your IDE, the **launch.json** file already contains the configuration to build and test the library. Otherwise, you can open the **Microsoft.Kiota.Http.HttpClientLibrary.sln** with Visual Studio.

0 commit comments

Comments
 (0)