From 1317b1b565dc7f07c2e2730b7354a5340abd8b8c Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 24 Nov 2026 10:23:03 -0500 Subject: [PATCH 1/3] fix(http): align default middleware order Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e625fa94-4ae9-464b-8e28-fddf64a8999d --- README.md | 9 ++ .../kiota/http/KiotaClientFactory.java | 39 +++++---- .../http/middleware/AuthorizationHandler.java | 27 +++++- .../kiota/http/KiotaClientFactoryTest.java | 69 +++++++++++---- .../middleware/AuthorizationHandlerTest.java | 85 ++++++++++++++++++- 5 files changed, 190 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index 996f025b1..75b1bcf41 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,15 @@ In `pom.xml` in the `dependencies` section: ``` +### 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. +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: diff --git a/components/http/okHttp/src/main/java/com/microsoft/kiota/http/KiotaClientFactory.java b/components/http/okHttp/src/main/java/com/microsoft/kiota/http/KiotaClientFactory.java index 5f36334f2..231764a9c 100644 --- a/components/http/okHttp/src/main/java/com/microsoft/kiota/http/KiotaClientFactory.java +++ b/components/http/okHttp/src/main/java/com/microsoft/kiota/http/KiotaClientFactory.java @@ -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; @@ -102,10 +103,8 @@ private KiotaClientFactory() {} @Nonnull public static OkHttpClient.Builder create( @Nonnull final BaseBearerTokenAuthenticationProvider authenticationProvider, @Nonnull final RequestOption[] requestOptions) { - ArrayList 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)); } /** @@ -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; @@ -151,25 +156,21 @@ private KiotaClientFactory() {} } final List 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) @@ -178,6 +179,10 @@ private KiotaClientFactory() {} retryHandlerOption != null ? new RetryHandler(retryHandlerOption) : new RetryHandler()); + handlers.add( + headersInspectionHandlerOption != null + ? new HeadersInspectionHandler(headersInspectionHandlerOption) + : new HeadersInspectionHandler()); return handlers.toArray(new Interceptor[0]); } diff --git a/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/AuthorizationHandler.java b/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/AuthorizationHandler.java index c80b16177..85d8dcbc8 100644 --- a/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/AuthorizationHandler.java +++ b/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/AuthorizationHandler.java @@ -14,6 +14,7 @@ import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; +import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.RequestBody; @@ -78,7 +79,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; } @@ -92,7 +106,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; } @@ -104,7 +118,14 @@ public AuthorizationHandler( span.setAttribute(HTTP_REQUEST_RESEND_COUNT, 1); } final Request authenticatedRequestAfterCAE = - authenticateRequest(request, additionalContext, span); + authenticateRequest( + challengedRequest + .newBuilder() + .removeHeader(AUTHORIZATION_HEADER) + .tag(Span.class, request.tag(Span.class)) + .build(), + additionalContext, + span); return chain.proceed(authenticatedRequestAfterCAE); } finally { if (scope != null) { diff --git a/components/http/okHttp/src/test/java/com/microsoft/kiota/http/KiotaClientFactoryTest.java b/components/http/okHttp/src/test/java/com/microsoft/kiota/http/KiotaClientFactoryTest.java index 37800c4dd..12ceb797a 100644 --- a/components/http/okHttp/src/test/java/com/microsoft/kiota/http/KiotaClientFactoryTest.java +++ b/components/http/okHttp/src/test/java/com/microsoft/kiota/http/KiotaClientFactoryTest.java @@ -14,26 +14,40 @@ 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 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 @@ -121,9 +135,16 @@ void testCreateWithAuthProviderAndRequestOptions() throws IOException { options.toArray(new RequestOption[0])) .build(); List 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(); @@ -137,19 +158,33 @@ 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()); } } diff --git a/components/http/okHttp/src/test/java/com/microsoft/kiota/http/middleware/AuthorizationHandlerTest.java b/components/http/okHttp/src/test/java/com/microsoft/kiota/http/middleware/AuthorizationHandlerTest.java index 605aaf69d..261cc6eeb 100644 --- a/components/http/okHttp/src/test/java/com/microsoft/kiota/http/middleware/AuthorizationHandlerTest.java +++ b/components/http/okHttp/src/test/java/com/microsoft/kiota/http/middleware/AuthorizationHandlerTest.java @@ -1,10 +1,13 @@ package com.microsoft.kiota.http.middleware; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.microsoft.kiota.authentication.AccessTokenProvider; @@ -17,6 +20,9 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; @@ -172,6 +178,77 @@ void testAuthorizationHandlerAddedByClientFactory() throws IOException { NEW_AUTHORIZATION_HEADER_VALUE, response.request().header(AUTHORIZATION_HEADER)); } + @Test + void testSameOriginClaimsChallengeReplaysOnlyTheRedirectedRequest() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue( + new MockResponse().setResponseCode(303).setHeader("Location", "/target")); + server.enqueue( + new MockResponse() + .setResponseCode(401) + .setHeader("WWW-Authenticate", CLAIMS_CHALLENGE_HEADER_VALUE)); + server.enqueue(new MockResponse()); + final OkHttpClient client = + KiotaClientFactory.create(getMockAuthenticationProvider(server.url("/").host())) + .build(); + final Request request = + new Request.Builder() + .url(server.url("/initial")) + .post(RequestBody.create("test", null)) + .build(); + + try (Response response = client.newCall(request).execute()) { + assertEquals(200, response.code()); + } + assertEquals(3, server.getRequestCount()); + assertEquals("/initial", server.takeRequest().getPath()); + final RecordedRequest firstHopToTarget = server.takeRequest(); + assertEquals("/target", firstHopToTarget.getPath()); + assertEquals( + NEW_AUTHORIZATION_HEADER_VALUE, + firstHopToTarget.getHeader(AUTHORIZATION_HEADER)); + final RecordedRequest replay = server.takeRequest(); + assertEquals("/target", replay.getPath()); + assertEquals("GET", replay.getMethod()); + assertEquals( + Arrays.asList("Bearer " + TOKEN_AFTER_CAE), + replay.getHeaders().values(AUTHORIZATION_HEADER)); + } + } + + @Test + void testDifferentOriginDoesNotReceiveAuthorizationOrTriggerClaimsRetry() throws Exception { + try (MockWebServer initial = new MockWebServer(); + MockWebServer target = new MockWebServer()) { + initial.enqueue( + new MockResponse() + .setResponseCode(302) + .setHeader("Location", target.url("/target"))); + initial.enqueue(new MockResponse()); + target.enqueue( + new MockResponse() + .setResponseCode(401) + .setHeader("WWW-Authenticate", CLAIMS_CHALLENGE_HEADER_VALUE)); + target.enqueue(new MockResponse()); + final BaseBearerTokenAuthenticationProvider provider = + getMockAuthenticationProvider(initial.url("/").host()); + final OkHttpClient client = KiotaClientFactory.create(provider).build(); + final Request request = new Request.Builder().url(initial.url("/initial")).build(); + + try (Response response = client.newCall(request).execute()) { + assertEquals(401, response.code()); + } + assertEquals(1, initial.getRequestCount()); + assertEquals( + NEW_AUTHORIZATION_HEADER_VALUE, + initial.takeRequest().getHeader(AUTHORIZATION_HEADER)); + assertEquals(1, target.getRequestCount()); + assertNull(target.takeRequest().getHeader(AUTHORIZATION_HEADER)); + verify(provider.getAccessTokenProvider(), times(1)) + .getAuthorizationToken(any(URI.class), anyMap()); + } + } + private Chain getMockChain(Request mockRequest, Response mockResponse) throws IOException { Chain mockChain = mock(Chain.class); when(mockChain.request()).thenReturn(mockRequest); @@ -189,9 +266,13 @@ public Response answer(InvocationOnMock invocation) { } private BaseBearerTokenAuthenticationProvider getMockAuthenticationProvider() { + return getMockAuthenticationProvider("graph.microsoft.com"); + } + + private BaseBearerTokenAuthenticationProvider getMockAuthenticationProvider( + String allowedHost) { final AccessTokenProvider mockAccessTokenProvider = mock(AccessTokenProvider.class); - final AllowedHostsValidator allowedHostsValidator = - new AllowedHostsValidator("graph.microsoft.com"); + final AllowedHostsValidator allowedHostsValidator = new AllowedHostsValidator(allowedHost); when(mockAccessTokenProvider.getAllowedHostsValidator()).thenReturn(allowedHostsValidator); when(mockAccessTokenProvider.getAuthorizationToken(any(URI.class), anyMap())) .thenReturn(ACCESS_TOKEN_STRING, TOKEN_AFTER_CAE); From 94468be5f8c8f99388ce602c425165ae6c215dd2 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 24 Nov 2026 10:42:25 -0500 Subject: [PATCH 2/3] fix(http): reset retry headers and preserve authorization spans Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e625fa94-4ae9-464b-8e28-fddf64a8999d --- README.md | 1 + .../http/middleware/AuthorizationHandler.java | 6 +- .../http/middleware/RedirectHandler.java | 9 +- .../kiota/http/middleware/RetryHandler.java | 2 +- .../kiota/http/KiotaClientFactoryTest.java | 33 ++++++++ .../middleware/AuthorizationHandlerTest.java | 83 +++++++++++++++++++ 6 files changed, 130 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 75b1bcf41..525e127e5 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,7 @@ In `pom.xml` in the `dependencies` section: `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. 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`. diff --git a/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/AuthorizationHandler.java b/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/AuthorizationHandler.java index 85d8dcbc8..500d0d4e4 100644 --- a/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/AuthorizationHandler.java +++ b/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/AuthorizationHandler.java @@ -51,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( @@ -65,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) diff --git a/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/RedirectHandler.java b/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/RedirectHandler.java index 96c516082..f592e1956 100644 --- a/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/RedirectHandler.java +++ b/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/RedirectHandler.java @@ -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 proxyResolver = diff --git a/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/RetryHandler.java b/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/RetryHandler.java index 0392a8ee7..1cb46a3cd 100644 --- a/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/RetryHandler.java +++ b/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/RetryHandler.java @@ -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 diff --git a/components/http/okHttp/src/test/java/com/microsoft/kiota/http/KiotaClientFactoryTest.java b/components/http/okHttp/src/test/java/com/microsoft/kiota/http/KiotaClientFactoryTest.java index 12ceb797a..1ccc73ae4 100644 --- a/components/http/okHttp/src/test/java/com/microsoft/kiota/http/KiotaClientFactoryTest.java +++ b/components/http/okHttp/src/test/java/com/microsoft/kiota/http/KiotaClientFactoryTest.java @@ -24,6 +24,7 @@ import okhttp3.Response; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; import org.junit.jupiter.api.Test; @@ -188,6 +189,38 @@ void retriesOnlyTheRedirectedHopAndInspectsTheRetriedRequest() throws Exception } } + @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")); + } + } + @Test void upstreamRedirectHandlingDisabledByDefault() { OkHttpClient client = KiotaClientFactory.create().build(); diff --git a/components/http/okHttp/src/test/java/com/microsoft/kiota/http/middleware/AuthorizationHandlerTest.java b/components/http/okHttp/src/test/java/com/microsoft/kiota/http/middleware/AuthorizationHandlerTest.java index 261cc6eeb..950a62617 100644 --- a/components/http/okHttp/src/test/java/com/microsoft/kiota/http/middleware/AuthorizationHandlerTest.java +++ b/components/http/okHttp/src/test/java/com/microsoft/kiota/http/middleware/AuthorizationHandlerTest.java @@ -2,10 +2,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.RETURNS_SELF; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -14,6 +18,16 @@ import com.microsoft.kiota.authentication.AllowedHostsValidator; import com.microsoft.kiota.authentication.BaseBearerTokenAuthenticationProvider; import com.microsoft.kiota.http.KiotaClientFactory; +import com.microsoft.kiota.http.ObservabilityOptions; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanBuilder; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.context.Context; import okhttp3.Interceptor.Chain; import okhttp3.OkHttpClient; @@ -25,6 +39,10 @@ import okhttp3.mockwebserver.RecordedRequest; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -216,6 +234,62 @@ void testSameOriginClaimsChallengeReplaysOnlyTheRedirectedRequest() throws Excep } } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void testAuthorizationSpanParentsDownstreamRequests(boolean alreadyAuthenticated) + throws IOException { + try (MockWebServer server = new MockWebServer(); + MockedStatic telemetry = + mockStatic(GlobalOpenTelemetry.class)) { + final Tracer tracer = mock(Tracer.class); + final SpanBuilder otherBuilder = mock(SpanBuilder.class, RETURNS_SELF); + final SpanBuilder userAgentBuilder = mock(SpanBuilder.class, RETURNS_SELF); + final SpanBuilder authorizationBuilder = mock(SpanBuilder.class); + final SpanBuilder redirectBuilder = mock(SpanBuilder.class, RETURNS_SELF); + final Span userAgentSpan = createSpan("0000000000000001"); + final Span authorizationSpan = createSpan("0000000000000002"); + final Span redirectSpan = createSpan("0000000000000003"); + telemetry.when(() -> GlobalOpenTelemetry.getTracer(anyString())).thenReturn(tracer); + when(tracer.spanBuilder(anyString())).thenReturn(otherBuilder); + when(tracer.spanBuilder("UserAgentHandler_Intercept")).thenReturn(userAgentBuilder); + when(tracer.spanBuilder("AuthorizationHandler_Intercept")) + .thenReturn(authorizationBuilder); + when(tracer.spanBuilder("RedirectHandler_Intercept")).thenReturn(redirectBuilder); + when(userAgentBuilder.startSpan()).thenReturn(userAgentSpan); + when(authorizationBuilder.startSpan()).thenReturn(authorizationSpan); + when(redirectBuilder.startSpan()).thenReturn(redirectSpan); + + if (!alreadyAuthenticated) { + server.enqueue( + new MockResponse() + .setResponseCode(401) + .setHeader("WWW-Authenticate", CLAIMS_CHALLENGE_HEADER_VALUE)); + } + server.enqueue(new MockResponse()); + final OkHttpClient client = + KiotaClientFactory.create(getMockAuthenticationProvider(server.url("/").host())) + .build(); + final Request.Builder request = + new Request.Builder() + .url(server.url("/initial")) + .tag(ObservabilityOptions.class, new ObservabilityOptions()); + if (alreadyAuthenticated) { + request.header(AUTHORIZATION_HEADER, PREV_AUTHORIZATION_HEADER_VALUE); + } + + try (Response response = client.newCall(request.build()).execute()) { + assertEquals(200, response.code()); + } + final int expectedRequests = alreadyAuthenticated ? 1 : 2; + assertEquals(expectedRequests, server.getRequestCount()); + final ArgumentCaptor parents = ArgumentCaptor.forClass(Context.class); + verify(redirectBuilder, times(expectedRequests)).setParent(parents.capture()); + for (Context parent : parents.getAllValues()) { + assertSame(authorizationSpan, Span.fromContext(parent)); + } + } + } + @Test void testDifferentOriginDoesNotReceiveAuthorizationOrTriggerClaimsRetry() throws Exception { try (MockWebServer initial = new MockWebServer(); @@ -249,6 +323,15 @@ void testDifferentOriginDoesNotReceiveAuthorizationOrTriggerClaimsRetry() throws } } + private static Span createSpan(String spanId) { + return Span.wrap( + SpanContext.create( + "00000000000000000000000000000001", + spanId, + TraceFlags.getSampled(), + TraceState.getDefault())); + } + private Chain getMockChain(Request mockRequest, Response mockResponse) throws IOException { Chain mockChain = mock(Chain.class); when(mockChain.request()).thenReturn(mockRequest); From 3353aef2417f9b2ce40302adaceaba80e5089ff0 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 24 Nov 2026 10:56:15 -0500 Subject: [PATCH 3/3] fix(http): reset retry attempt for claims replay Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e625fa94-4ae9-464b-8e28-fddf64a8999d --- README.md | 2 +- .../http/middleware/AuthorizationHandler.java | 1 + .../middleware/AuthorizationHandlerTest.java | 32 +++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 525e127e5..c4246b1c7 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ In `pom.xml` in the `dependencies` section: `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. +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`. diff --git a/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/AuthorizationHandler.java b/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/AuthorizationHandler.java index 500d0d4e4..01e0e1e5d 100644 --- a/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/AuthorizationHandler.java +++ b/components/http/okHttp/src/main/java/com/microsoft/kiota/http/middleware/AuthorizationHandler.java @@ -126,6 +126,7 @@ public AuthorizationHandler( challengedRequest .newBuilder() .removeHeader(AUTHORIZATION_HEADER) + .removeHeader(RetryHandler.RETRY_ATTEMPT_HEADER) .tag(Span.class, request.tag(Span.class)) .build(), additionalContext, diff --git a/components/http/okHttp/src/test/java/com/microsoft/kiota/http/middleware/AuthorizationHandlerTest.java b/components/http/okHttp/src/test/java/com/microsoft/kiota/http/middleware/AuthorizationHandlerTest.java index 950a62617..b35018c81 100644 --- a/components/http/okHttp/src/test/java/com/microsoft/kiota/http/middleware/AuthorizationHandlerTest.java +++ b/components/http/okHttp/src/test/java/com/microsoft/kiota/http/middleware/AuthorizationHandlerTest.java @@ -290,6 +290,38 @@ void testAuthorizationSpanParentsDownstreamRequests(boolean alreadyAuthenticated } } + @Test + void testClaimsReplayStartsWithFreshRetryAttemptHeader() + throws IOException, InterruptedException { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse().setResponseCode(429).setHeader("Retry-After", "0")); + server.enqueue(new MockResponse().setResponseCode(429).setHeader("Retry-After", "0")); + server.enqueue( + new MockResponse() + .setResponseCode(401) + .setHeader("WWW-Authenticate", CLAIMS_CHALLENGE_HEADER_VALUE)); + server.enqueue(new MockResponse().setResponseCode(429).setHeader("Retry-After", "0")); + server.enqueue(new MockResponse()); + final OkHttpClient client = + KiotaClientFactory.create(getMockAuthenticationProvider(server.url("/").host())) + .build(); + final Request request = new Request.Builder().url(server.url("/initial")).build(); + + try (Response response = client.newCall(request).execute()) { + assertEquals(200, response.code()); + } + + assertEquals(5, server.getRequestCount()); + assertNull(server.takeRequest().getHeader("Retry-Attempt")); + assertEquals("1", server.takeRequest().getHeader("Retry-Attempt")); + assertEquals("2", server.takeRequest().getHeader("Retry-Attempt")); + final RecordedRequest replay = server.takeRequest(); + assertEquals("Bearer " + TOKEN_AFTER_CAE, replay.getHeader(AUTHORIZATION_HEADER)); + assertNull(replay.getHeader("Retry-Attempt")); + assertEquals("1", server.takeRequest().getHeader("Retry-Attempt")); + } + } + @Test void testDifferentOriginDoesNotReceiveAuthorizationOrTriggerClaimsRetry() throws Exception { try (MockWebServer initial = new MockWebServer();