Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
32 changes: 18 additions & 14 deletions src/http/httpClient/KiotaClientFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ namespace Microsoft.Kiota.Http.HttpClientLibrary
public static class KiotaClientFactory
{
/// <summary>
/// Initializes the <see cref="HttpClient"/> with the default configuration and middlewares including a authentication middleware using the <see cref="IAuthenticationProvider"/> if provided.
/// Initializes the <see cref="HttpClient"/> with the default configuration and middleware, without authorization middleware.
/// </summary>
/// <param name="finalHandler">The final <see cref="HttpMessageHandler"/> in the http pipeline. Can be configured for proxies, auto-decompression and auto-redirects </param>
/// <param name="optionsForHandlers">A array of <see cref="IRequestOption"/> objects passed to the default handlers.</param>
Expand Down Expand Up @@ -50,16 +50,17 @@ public static HttpClient Create(IList<DelegatingHandler> handlers, HttpMessageHa
/// <returns></returns>
public static HttpClient Create(BaseBearerTokenAuthenticationProvider authenticationProvider, IRequestOption[]? optionsForHandlers = null, HttpMessageHandler? finalHandler = null)
{
var defaultHandlersEnumerable = CreateDefaultHandlers(optionsForHandlers);
defaultHandlersEnumerable.Add(new AuthorizationHandler(authenticationProvider));
return Create(defaultHandlersEnumerable, finalHandler);
return Create(CreateDefaultHandlers(optionsForHandlers, new AuthorizationHandler(authenticationProvider)), finalHandler);
}

/// <summary>
/// Creates a default set of middleware to be used by the <see cref="HttpClient"/>.
/// </summary>
/// <returns>A list of the default handlers used by the client.</returns>
public static IList<DelegatingHandler> CreateDefaultHandlers(IRequestOption[]? optionsForHandlers = null)
=> CreateDefaultHandlers(optionsForHandlers, null);

private static IList<DelegatingHandler> CreateDefaultHandlers(IRequestOption[]? optionsForHandlers, AuthorizationHandler? authorizationHandler)
{
optionsForHandlers ??= Array.Empty<IRequestOption>();

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

return new List<DelegatingHandler>
var handlers = new List<DelegatingHandler>
{
uriReplacementOption != null ? new UriReplacementHandler<UriReplacementHandlerOption>(uriReplacementOption) : new UriReplacementHandler<UriReplacementHandlerOption>(),
retryHandlerOption != null ? new RetryHandler(retryHandlerOption) : new RetryHandler(),
redirectHandlerOption != null ? new RedirectHandler(redirectHandlerOption) : new RedirectHandler(),
parametersNameDecodingOption != null ? new ParametersNameDecodingHandler(parametersNameDecodingOption) : new ParametersNameDecodingHandler(),
userAgentHandlerOption != null ? new UserAgentHandler(userAgentHandlerOption) : new UserAgentHandler(),
headersInspectionHandlerOption != null ? new HeadersInspectionHandler(headersInspectionHandlerOption) : new HeadersInspectionHandler(),
bodyInspectionHandlerOption != null ? new BodyInspectionHandler(bodyInspectionHandlerOption) : new BodyInspectionHandler(),
};
if(authorizationHandler != null)
handlers.Add(authorizationHandler);
handlers.Add(redirectHandlerOption != null ? new RedirectHandler(redirectHandlerOption) : new RedirectHandler());
handlers.Add(retryHandlerOption != null ? new RetryHandler(retryHandlerOption) : new RetryHandler());
handlers.Add(headersInspectionHandlerOption != null ? new HeadersInspectionHandler(headersInspectionHandlerOption) : new HeadersInspectionHandler());
handlers.Add(bodyInspectionHandlerOption != null ? new BodyInspectionHandler(bodyInspectionHandlerOption) : new BodyInspectionHandler());
return handlers;
}

/// <summary>
Expand All @@ -112,10 +116,10 @@ public static IList<DelegatingHandler> CreateDefaultHandlers(IRequestOption[]? o
return new List<System.Type>
{
typeof(UriReplacementHandler<UriReplacementHandlerOption>),
typeof(RetryHandler),
typeof(RedirectHandler),
typeof(ParametersNameDecodingHandler),
typeof(UserAgentHandler),
typeof(RedirectHandler),
typeof(RetryHandler),
typeof(HeadersInspectionHandler),
typeof(BodyInspectionHandler),
};
Expand All @@ -131,10 +135,10 @@ public static IList<ActivatableType> GetDefaultHandlerActivatableTypes()
return new List<ActivatableType>()
{
new(typeof(UriReplacementHandler<UriReplacementHandlerOption>)),
new(typeof(RetryHandler)),
new(typeof(RedirectHandler)),
new(typeof(ParametersNameDecodingHandler)),
new(typeof(UserAgentHandler)),
new(typeof(RedirectHandler)),
new(typeof(RetryHandler)),
new(typeof(HeadersInspectionHandler)),
new(typeof(BodyInspectionHandler)),
};
Expand Down Expand Up @@ -230,7 +234,7 @@ public static HttpMessageHandler GetDefaultHttpMessageHandler(IWebProxy? proxy =
// If custom proxy is passed, the WindowsProxyUsePolicy will need updating
// https://github.com/dotnet/runtime/blob/main/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs#L575
var proxyPolicy = proxy != null ? WindowsProxyUsePolicy.UseCustomProxy : WindowsProxyUsePolicy.UseWinHttpProxy;
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 };
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 };
Comment thread
baywet marked this conversation as resolved.
Resolved
#elif NET5_0_OR_GREATER && !BROWSER
return new SocketsHttpHandler { Proxy = proxy, AllowAutoRedirect = false, EnableMultipleHttp2Connections = true, AutomaticDecompression = DecompressionMethods.All };
#elif BROWSER
Expand Down
9 changes: 8 additions & 1 deletion src/http/httpClient/Middleware/AuthorizationHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using System.Threading.Tasks;
using Microsoft.Kiota.Abstractions.Authentication;
using Microsoft.Kiota.Http.HttpClientLibrary.Extensions;
using Microsoft.Kiota.Http.HttpClientLibrary.Middleware.Options;

namespace Microsoft.Kiota.Http.HttpClientLibrary.Middleware
{
Expand Down Expand Up @@ -62,8 +63,14 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
}
Dictionary<string, object> additionalAuthenticationContext = new Dictionary<string, object>();
await AuthenticateRequestAsync(request, additionalAuthenticationContext, activity, cancellationToken).ConfigureAwait(false);
var originalUri = request.RequestUri;
var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
if(response.StatusCode != HttpStatusCode.Unauthorized || response.RequestMessage == null || !response.RequestMessage.IsBuffered())
// A redirect may have removed authorization. Do not let a challenge extend it to another origin.
if(response.StatusCode != HttpStatusCode.Unauthorized ||
originalUri is not { IsAbsoluteUri: true } ||
response.RequestMessage?.RequestUri is not { IsAbsoluteUri: true } challengedUri ||
!RedirectHandlerOption.HaveSameOrigin(originalUri, challengedUri) ||
!response.RequestMessage.IsBuffered())
return response;
// Attempt CAE claims challenge
var claims = ContinuousAccessEvaluation.GetClaims(response);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,7 @@ public static void DefaultScrubSensitiveHeaders(HttpRequestMessage newRequest, U
var newUri = newRequest.RequestUri ?? throw new InvalidOperationException("The request URI cannot be null.");

// Remove Authorization and Cookie headers if http request's scheme, host, or port changes
var isDifferentOrigin = !newUri.Host.Equals(originalUri.Host, StringComparison.OrdinalIgnoreCase) ||
!newUri.Scheme.Equals(originalUri.Scheme, StringComparison.OrdinalIgnoreCase) ||
newUri.Port != originalUri.Port;
if(isDifferentOrigin)
if(!HaveSameOrigin(originalUri, newUri))
{
newRequest.Headers.Authorization = null;
newRequest.Headers.Remove("Cookie");
Expand All @@ -87,5 +84,10 @@ public static void DefaultScrubSensitiveHeaders(HttpRequestMessage newRequest, U
newRequest.Headers.ProxyAuthorization = null;
}
}

internal static bool HaveSameOrigin(Uri first, Uri second) =>
first.Host.Equals(second.Host, StringComparison.OrdinalIgnoreCase) &&
first.Scheme.Equals(second.Scheme, StringComparison.OrdinalIgnoreCase) &&
first.Port == second.Port;
}
}
3 changes: 3 additions & 0 deletions src/http/httpClient/Middleware/RedirectHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
}
var newRequest = await originalRequest.CloneAsync(cancellationToken).ConfigureAwait(false);

// The next hop gets its own retry budget and attempt header.
newRequest.Headers.Remove(RetryHandler.RetryAttempt);

if(RequestRequiresForceGet(response.StatusCode, newRequest.Method))
{
newRequest.Method = HttpMethod.Get;
Expand Down
2 changes: 1 addition & 1 deletion src/http/httpClient/Middleware/RetryHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ namespace Microsoft.Kiota.Http.HttpClientLibrary.Middleware
public class RetryHandler : DelegatingHandler
{
private const string RetryAfter = "Retry-After";
private const string RetryAttempt = "Retry-Attempt";
internal const string RetryAttempt = "Retry-Attempt";

/// <summary>
/// RetryOption property
Expand Down
4 changes: 4 additions & 0 deletions src/http/httpClient/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ Read more about Kiota [here](https://github.com/microsoft/kiota/blob/main/README
dotnet add package Microsoft.Kiota.Http.HttpClientLibrary
```

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.

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.

## Debugging

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.
Expand Down
104 changes: 104 additions & 0 deletions tests/http/httpClient/KiotaClientFactoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#if !NET5_0_OR_GREATER
using System.Net.Http;
#endif
using System.Net.Http.Headers;
using Microsoft.Kiota.Abstractions.Authentication;
using Microsoft.Kiota.Http.HttpClientLibrary.Middleware;
using Microsoft.Kiota.Http.HttpClientLibrary.Middleware.Options;
Expand Down Expand Up @@ -86,6 +87,17 @@ public void GetDefaultHttpMessageHandlerEnablesMultipleHttp2Connections()
#endif
}

[Fact]
public void GetDefaultHttpMessageHandlerLeavesRedirectsToMiddleware()
{
using var handler = KiotaClientFactory.GetDefaultHttpMessageHandler();
#if NETFRAMEWORK
Assert.False(Assert.IsType<WinHttpHandler>(handler).AutomaticRedirection);
#else
Assert.False(Assert.IsType<SocketsHttpHandler>(handler).AllowAutoRedirect);
#endif
}

[Fact]
public void GetDefaultHttpMessageHandlerSetsUpProxy()
{
Expand Down Expand Up @@ -119,6 +131,98 @@ public void CreateDefaultHandlersWithOptions()
Assert.Equal(retryHandlerOption, retryHandler.RetryOption);
}

[Fact]
public void DefaultHandlerListsUseTheSameOutboundOrder()
{
Type[] expected =
[
typeof(UriReplacementHandler<UriReplacementHandlerOption>),
typeof(ParametersNameDecodingHandler),
typeof(UserAgentHandler),
typeof(RedirectHandler),
typeof(RetryHandler),
typeof(HeadersInspectionHandler),
typeof(BodyInspectionHandler),
];
Assert.Equal(expected, KiotaClientFactory.CreateDefaultHandlers().Select(handler => handler.GetType()));
#pragma warning disable CS0618 // Verify the legacy type list is still consistent.
Assert.Equal(expected, KiotaClientFactory.GetDefaultHandlerTypes());
Comment thread
baywet marked this conversation as resolved.
Resolved
#pragma warning restore CS0618
Assert.Equal(expected, KiotaClientFactory.GetDefaultHandlerActivatableTypes().Select(handler => handler.Type));
}

[Fact]
public async Task RedirectHopsHaveSeparateRetryBudgetsAndKeepTheServerProvidedQuery()
{
using var initialFailure = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable);
using var redirect = new HttpResponseMessage(HttpStatusCode.Found);
redirect.Headers.Location = new Uri("/second?%24select=id", UriKind.Relative);
using var redirectFailure = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable);
using var success = new HttpResponseMessage(HttpStatusCode.OK);
var transport = new ResponseSequenceHandler(initialFailure, redirect, redirectFailure, success);
using var client = KiotaClientFactory.Create(transport, [new RetryHandlerOption { MaxRetry = 1, Delay = 0 }]);

var response = await client.GetAsync("https://example.com/first?%24select=id", TestContext.Current.CancellationToken);

Assert.Same(success, response);
Assert.Equal(
new (string, string?)[]
{
("/first?$select=id", null),
("/first?$select=id", "1"),
("/second?%24select=id", null),
("/second?%24select=id", "1"),
},
transport.Requests.Select(request => (request.RequestUri!.PathAndQuery,
request.Headers.TryGetValues("Retry-Attempt", out var values) ? Assert.Single(values) : null)));
}

[Theory]
[InlineData("https://example.com/second", true)]
[InlineData("https://other.example.com/second", false)]
[InlineData("https://example.com:8443/second", false)]
[InlineData("http://example.com/second", false)]
public async Task FactoryAuthorizationOnlyAnswersClaimsChallengesFromTheOriginalOrigin(string destination, bool sameOrigin)
{
var tokens = new Mock<IAccessTokenProvider>();
tokens.SetupGet(provider => provider.AllowedHostsValidator).Returns(
new AllowedHostsValidator(["example.com", "other.example.com"]));
tokens.SetupSequence(provider => provider.GetAuthorizationTokenAsync(
It.IsAny<Uri>(), It.IsAny<Dictionary<string, object>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync("initial-token").ReturnsAsync("claims-token");

using var redirect = new HttpResponseMessage(HttpStatusCode.Found);
redirect.Headers.Location = new Uri(destination);
using var challenge = new HttpResponseMessage(HttpStatusCode.Unauthorized);
challenge.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Bearer", "error=\"insufficient_claims\", claims=\"YQ==\""));
using var success = new HttpResponseMessage(HttpStatusCode.OK);
var transport = new ResponseSequenceHandler(redirect, challenge, success);
using var client = KiotaClientFactory.Create(new BaseBearerTokenAuthenticationProvider(tokens.Object),
[new RedirectHandlerOption { AllowRedirectOnSchemeChange = true }], transport);

var response = await client.GetAsync("https://example.com/first", TestContext.Current.CancellationToken);

Assert.Same(sameOrigin ? success : challenge, response);
string?[] expectedTokens = sameOrigin ? ["initial-token", "initial-token", "claims-token"] : ["initial-token", null];
Assert.Equal(expectedTokens, transport.Requests.Select(request => request.Headers.Authorization?.Parameter));
tokens.Verify(provider => provider.GetAuthorizationTokenAsync(
It.IsAny<Uri>(), It.IsAny<Dictionary<string, object>>(), It.IsAny<CancellationToken>()),
Times.Exactly(sameOrigin ? 2 : 1));
}

private sealed class ResponseSequenceHandler(params HttpResponseMessage[] responses) : HttpMessageHandler
{
public List<HttpRequestMessage> Requests { get; } = [];

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = responses[Requests.Count];
Requests.Add(request);
response.RequestMessage = request;
return Task.FromResult(response);
}
}

[Fact]
public void CreateWithNullOrEmptyHandlersReturnsHttpClient()
{
Expand Down
Loading