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
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,16 @@ In `pom.xml` in the `dependencies` section:
</dependency>
```

### Default OkHttp middleware

`KiotaClientFactory` applies URL replacement, query parameter name decoding, and User-Agent to the
initial request, then follows redirects, retries each hop, and inspects headers for each send.
The `Retry-Attempt` header is reset when following a redirect or replaying a claims challenge.
Generated clients authenticate in the request adapter. For standalone OkHttp requests, pass an
authentication provider to `KiotaClientFactory.create` to opt in to authorization after User-Agent
and before redirects. Opt-in header inspection can capture sensitive headers such as `Authorization`.
OkHttp handles transparent response decompression.

## Extra

Third party tools and extensions:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import com.microsoft.kiota.http.middleware.options.UserAgentHandlerOption;

import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
Expand Down Expand Up @@ -102,10 +103,8 @@ private KiotaClientFactory() {}
@Nonnull public static OkHttpClient.Builder create(
@Nonnull final BaseBearerTokenAuthenticationProvider authenticationProvider,
@Nonnull final RequestOption[] requestOptions) {
ArrayList<Interceptor> interceptors =
new ArrayList<>(Arrays.asList(createDefaultInterceptors(requestOptions)));
interceptors.add(new AuthorizationHandler(authenticationProvider));
return create(interceptors);
Objects.requireNonNull(authenticationProvider, "AuthenticationProvider cannot be null");
return create(createDefaultInterceptors(requestOptions, authenticationProvider));
}

/**
Expand All @@ -123,6 +122,12 @@ private KiotaClientFactory() {}
*/
@Nonnull public static Interceptor[] createDefaultInterceptors(
@Nonnull final RequestOption[] requestOptions) {
return createDefaultInterceptors(requestOptions, null);
}

@Nonnull private static Interceptor[] createDefaultInterceptors(
@Nonnull final RequestOption[] requestOptions,
@Nullable final BaseBearerTokenAuthenticationProvider authenticationProvider) {
Objects.requireNonNull(requestOptions, "parameter requestOptions cannot be null");

UrlReplaceHandlerOption uriReplacementOption = null;
Expand Down Expand Up @@ -151,25 +156,21 @@ private KiotaClientFactory() {}
}

final List<Interceptor> handlers = new ArrayList<>();
// orders matter as they are executed in a chain
// interceptors that only modify the request should be added first
// interceptors that read the response should be added last
handlers.add(
userAgentHandlerOption != null
? new UserAgentHandler(userAgentHandlerOption)
: new UserAgentHandler());
uriReplacementOption != null
? new UrlReplaceHandler(uriReplacementOption)
: new UrlReplaceHandler());
handlers.add(
parametersNameDecodingOption != null
? new ParametersNameDecodingHandler(parametersNameDecodingOption)
: new ParametersNameDecodingHandler());
handlers.add(
uriReplacementOption != null
? new UrlReplaceHandler(uriReplacementOption)
: new UrlReplaceHandler());
handlers.add(
headersInspectionHandlerOption != null
? new HeadersInspectionHandler(headersInspectionHandlerOption)
: new HeadersInspectionHandler());
userAgentHandlerOption != null
? new UserAgentHandler(userAgentHandlerOption)
: new UserAgentHandler());
if (authenticationProvider != null) {
handlers.add(new AuthorizationHandler(authenticationProvider));
}
handlers.add(
redirectHandlerOption != null
? new RedirectHandler(redirectHandlerOption)
Expand All @@ -178,6 +179,10 @@ private KiotaClientFactory() {}
retryHandlerOption != null
? new RetryHandler(retryHandlerOption)
: new RetryHandler());
Comment thread
baywet marked this conversation as resolved.
Resolved
handlers.add(
headersInspectionHandlerOption != null
? new HeadersInspectionHandler(headersInspectionHandlerOption)
: new HeadersInspectionHandler());

return handlers.toArray(new Interceptor[0]);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
Expand Down Expand Up @@ -50,7 +51,7 @@ public AuthorizationHandler(
@SuppressWarnings("UnknownNullness")
public @Nonnull Response intercept(final Chain chain) throws IOException {
Objects.requireNonNull(chain, "parameter chain cannot be null");
final Request request = chain.request();
final Request incomingRequest = chain.request();

final Span span =
GlobalOpenTelemetry.getTracer(
Expand All @@ -64,6 +65,10 @@ public AuthorizationHandler(
}

try {
final Request request =
span == null
? incomingRequest
: incomingRequest.newBuilder().tag(Span.class, span).build();
// Auth provider already added auth header
if (request.headers().names().contains(AUTHORIZATION_HEADER)) {
if (span != null)
Expand All @@ -78,7 +83,20 @@ public AuthorizationHandler(
authenticateRequest(request, additionalContext, span);
final Response response = chain.proceed(authenticatedRequest);

if (response != null && response.code() != HttpURLConnection.HTTP_UNAUTHORIZED) {
if (response.code() != HttpURLConnection.HTTP_UNAUTHORIZED) {
return response;
}

// Handle a challenge only on the hop that retained the original authorization.
final Request challengedRequest = response.request();
final HttpUrl originalUrl = authenticatedRequest.url();
final HttpUrl challengedUrl = challengedRequest.url();
if (!originalUrl.scheme().equals(challengedUrl.scheme())
|| !originalUrl.host().equals(challengedUrl.host())
|| originalUrl.port() != challengedUrl.port()
|| !Objects.equals(
authenticatedRequest.header(AUTHORIZATION_HEADER),
challengedRequest.header(AUTHORIZATION_HEADER))) {
return response;
}

Expand All @@ -92,7 +110,7 @@ public AuthorizationHandler(
span.addEvent("com.microsoft.kiota.handler.authorization.challenge_received");

// We cannot replay one-shot requests after claims challenge
final RequestBody requestBody = request.body();
final RequestBody requestBody = challengedRequest.body();
if (requestBody != null && requestBody.isOneShot()) {
return response;
}
Expand All @@ -104,7 +122,15 @@ public AuthorizationHandler(
span.setAttribute(HTTP_REQUEST_RESEND_COUNT, 1);
}
final Request authenticatedRequestAfterCAE =
authenticateRequest(request, additionalContext, span);
authenticateRequest(
challengedRequest
.newBuilder()
.removeHeader(AUTHORIZATION_HEADER)
.removeHeader(RetryHandler.RETRY_ATTEMPT_HEADER)
.tag(Span.class, request.tag(Span.class))
Comment thread
baywet marked this conversation as resolved.
Resolved
.build(),
additionalContext,
span);
return chain.proceed(authenticatedRequestAfterCAE);
} finally {
if (scope != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,13 @@ Request getRedirect(
// Don't follow redirects to unsupported protocols.
if (locationUrl == null) return null;

// Most redirects don't include a request body.
Request.Builder requestBuilder = userResponse.request().newBuilder().url(locationUrl);
// The retry count belongs to the previous hop.
Request.Builder requestBuilder =
userResponse
.request()
.newBuilder()
.url(locationUrl)
.removeHeader(RetryHandler.RETRY_ATTEMPT_HEADER);

// Scrub sensitive headers before following the redirect
java.util.function.Function<HttpUrl, java.net.Proxy> proxyResolver =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public class RetryHandler implements Interceptor {
/**
* Header name to track the retry attempt number
*/
private static final String RETRY_ATTEMPT_HEADER = "Retry-Attempt";
static final String RETRY_ATTEMPT_HEADER = "Retry-Attempt";

/**
* Header name for the retry after information
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,41 @@
import com.microsoft.kiota.http.middleware.RetryHandler;
import com.microsoft.kiota.http.middleware.UrlReplaceHandler;
import com.microsoft.kiota.http.middleware.UserAgentHandler;
import com.microsoft.kiota.http.middleware.options.HeadersInspectionOption;
import com.microsoft.kiota.http.middleware.options.RetryHandlerOption;
import com.microsoft.kiota.http.middleware.options.UrlReplaceHandlerOption;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class KiotaClientFactoryTest {

@Test
void testCreatesDefaultInterceptors() throws IOException {
OkHttpClient client = KiotaClientFactory.create().build();
assertNotNull(client.interceptors());
assertEquals(6, client.interceptors().size());
assertEquals(
Arrays.asList(
UrlReplaceHandler.class,
ParametersNameDecodingHandler.class,
UserAgentHandler.class,
RedirectHandler.class,
RetryHandler.class,
HeadersInspectionHandler.class),
client.interceptors().stream().map(Object::getClass).collect(Collectors.toList()));
}

@Test
Expand Down Expand Up @@ -121,9 +136,16 @@ void testCreateWithAuthProviderAndRequestOptions() throws IOException {
options.toArray(new RequestOption[0]))
.build();
List<Interceptor> clientInterceptors = client.interceptors();
assertNotNull(clientInterceptors);
// including the Authorization Handler
assertEquals(7, clientInterceptors.size());
assertEquals(
Arrays.asList(
UrlReplaceHandler.class,
ParametersNameDecodingHandler.class,
UserAgentHandler.class,
AuthorizationHandler.class,
RedirectHandler.class,
RetryHandler.class,
HeadersInspectionHandler.class),
clientInterceptors.stream().map(Object::getClass).collect(Collectors.toList()));
for (Interceptor interceptor : clientInterceptors) {
if (interceptor instanceof RetryHandler) {
RetryHandlerOption handlerOption = ((RetryHandler) interceptor).getRetryOptions();
Expand All @@ -137,19 +159,65 @@ void testCreateWithAuthProviderAndRequestOptions() throws IOException {
assertTrue(handlerOption.getReplacementPairs().isEmpty());
assertFalse(handlerOption.isEnabled());
}
}
}

assertTrue(
interceptor instanceof UrlReplaceHandler
|| interceptor instanceof RedirectHandler
|| interceptor instanceof RetryHandler
|| interceptor instanceof ParametersNameDecodingHandler
|| interceptor instanceof UserAgentHandler
|| interceptor instanceof HeadersInspectionHandler
|| interceptor instanceof ChaosHandler
|| interceptor instanceof AuthorizationHandler,
"Array should contain instances of"
+ " UrlReplaceHandler,RedirectHandler,RetryHandler,ParametersNameDecodingHandler,UserAgentHandler,"
+ " HeadersInspectionHandler, and ChaosHandler");
@Test
void retriesOnlyTheRedirectedHopAndInspectsTheRetriedRequest() throws Exception {
try (MockWebServer server = new MockWebServer()) {
server.enqueue(
new MockResponse().setResponseCode(302).setHeader("Location", "/target"));
server.enqueue(new MockResponse().setResponseCode(429).setHeader("Retry-After", "0"));
server.enqueue(new MockResponse().setHeader("X-Result", "final"));
HeadersInspectionOption inspection = new HeadersInspectionOption(true, true);
Request request =
new Request.Builder()
.url(server.url("/initial"))
.tag(HeadersInspectionOption.class, inspection)
.build();

try (Response response =
KiotaClientFactory.create().build().newCall(request).execute()) {
assertEquals(200, response.code());
assertTrue(inspection.getRequestHeaders().get("Retry-Attempt").contains("1"));
assertTrue(inspection.getResponseHeaders().get("X-Result").contains("final"));
}
assertEquals(3, server.getRequestCount());
assertEquals("/initial", server.takeRequest().getPath());
assertEquals("/target", server.takeRequest().getPath());
assertEquals("/target", server.takeRequest().getPath());
}
}

@Test
void clearsRetryAttemptWhenFollowingARedirect() throws Exception {
try (MockWebServer server = new MockWebServer()) {
server.enqueue(new MockResponse().setResponseCode(429).setHeader("Retry-After", "0"));
server.enqueue(
new MockResponse().setResponseCode(302).setHeader("Location", "/target"));
server.enqueue(new MockResponse());
HeadersInspectionOption inspection = new HeadersInspectionOption(true, false);
Request request =
new Request.Builder()
.url(server.url("/initial"))
.tag(HeadersInspectionOption.class, inspection)
.build();

try (Response response =
KiotaClientFactory.create().build().newCall(request).execute()) {
assertEquals(200, response.code());
assertFalse(inspection.getRequestHeaders().containsKey("Retry-Attempt"));
}
assertEquals(3, server.getRequestCount());
final RecordedRequest initial = server.takeRequest();
assertEquals("/initial", initial.getPath());
assertNull(initial.getHeader("Retry-Attempt"));
final RecordedRequest retry = server.takeRequest();
assertEquals("/initial", retry.getPath());
assertEquals("1", retry.getHeader("Retry-Attempt"));
final RecordedRequest target = server.takeRequest();
assertEquals("/target", target.getPath());
assertNull(target.getHeader("Retry-Attempt"));
}
}

Expand Down
Loading
Loading