Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds Authorization Handler #1562

Merged
merged 16 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from 11 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
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,8 @@ public void authenticateRequest(
}
}
}

public @Nonnull AccessTokenProvider getAccessTokenProvider() {
return this.accessTokenProvider;
}
}
6 changes: 3 additions & 3 deletions components/http/okHttp/spotBugsExcludeFilter.xml
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@
</Match>
<Match>
<Bug pattern="CT_CONSTRUCTOR_THROW" />
<Class name="com.microsoft.kiota.http.HeadersInspectionHandlerTest" />
<Class name="com.microsoft.kiota.http.middleware.HeadersInspectionHandlerTest" />
</Match>
<Match>
<Bug pattern="CT_CONSTRUCTOR_THROW" />
<Class name="~com\.microsoft\.kiota\.http\.OkHttpRequestAdapterTest.*" />
</Match>
<Match>
<Bug pattern="CT_CONSTRUCTOR_THROW" />
<Class name="com.microsoft.kiota.http.UserAgentHandlerTest" />
<Class name="com.microsoft.kiota.http.middleware.UserAgentHandlerTest" />
</Match>
</FindBugsFilter>
</FindBugsFilter>
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.microsoft.kiota.http;

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

import okhttp3.Response;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* Helper class to extract the claims from the WWW-Authenticate header in a response.
* https://learn.microsoft.com/en-us/entra/identity/conditional-access/concept-continuous-access-evaluation
*/
public final class ContinuousAccessEvaluationClaims {
baywet marked this conversation as resolved.
Show resolved Hide resolved

private static final Pattern bearerPattern =
Pattern.compile("^Bearer\\s.*", Pattern.CASE_INSENSITIVE);
private static final Pattern claimsPattern =
Pattern.compile("\\s?claims=\"([^\"]+)\"", Pattern.CASE_INSENSITIVE);

private static final String wwwAuthenticateHeader = "WWW-Authenticate";

/**
* Extracts the claims from the WWW-Authenticate header in a response.
* @param response the response to extract the claims from.
* @return the claims
*/
public static @Nullable String getClaimsFromResponse(@Nonnull Response response) {
if (response == null || response.code() != 401) {
return null;
}
final List<String> authenticateHeader = response.headers(wwwAuthenticateHeader);
if (!authenticateHeader.isEmpty()) {
String rawHeaderValue = null;
for (final String authenticateEntry : authenticateHeader) {
final Matcher matcher = bearerPattern.matcher(authenticateEntry);
if (matcher.matches()) {
rawHeaderValue = authenticateEntry.replaceFirst("^Bearer\\s", "");
break;
}
}
if (rawHeaderValue != null) {
final String[] parameters = rawHeaderValue.split(",");
for (final String parameter : parameters) {
final Matcher matcher = claimsPattern.matcher(parameter);
if (matcher.matches()) {
return matcher.group(1);
}
}
}
}
return null;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.microsoft.kiota.http;

import com.microsoft.kiota.authentication.BaseBearerTokenAuthenticationProvider;
import com.microsoft.kiota.http.middleware.AuthorizationHandler;
import com.microsoft.kiota.http.middleware.HeadersInspectionHandler;
import com.microsoft.kiota.http.middleware.ParametersNameDecodingHandler;
import com.microsoft.kiota.http.middleware.RedirectHandler;
Expand All @@ -13,6 +15,8 @@
import okhttp3.OkHttpClient;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;

/** This class is used to build the HttpClient instance used by the core service. */
public class KiotaClientFactory {
Expand All @@ -23,7 +27,7 @@ private KiotaClientFactory() {}
* @return an OkHttpClient Builder instance.
*/
@Nonnull public static OkHttpClient.Builder create() {
return create(null);
return create(createDefaultInterceptors());
}

/**
Expand All @@ -48,6 +52,18 @@ private KiotaClientFactory() {}
return builder;
}

/**
* Creates an OkHttpClient Builder with the default configuration and middleware including the AuthorizationHandler.
* @param authenticationProvider authentication provider to use for the AuthorizationHandler.
* @return an OkHttpClient Builder instance.
*/
@Nonnull public static OkHttpClient.Builder create(
@Nonnull final BaseBearerTokenAuthenticationProvider authenticationProvider) {
List<Interceptor> interceptors = Arrays.asList(createDefaultInterceptors());
interceptors.add(new AuthorizationHandler(authenticationProvider));
return create((Interceptor[]) interceptors.toArray());
}

/**
* Creates the default interceptors for the client.
* @return an array of interceptors.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** RequestAdapter implementation for OkHttp */
Expand Down Expand Up @@ -753,11 +752,6 @@ private String getHeaderValue(final Response response, String key) {
return null;
}

private static final Pattern bearerPattern =
Pattern.compile("^Bearer\\s.*", Pattern.CASE_INSENSITIVE);
private static final Pattern claimsPattern =
Pattern.compile("\\s?claims=\"([^\"]+)\"", Pattern.CASE_INSENSITIVE);

/** Key used for events when an authentication challenge is returned by the API */
@Nonnull public static final String authenticateChallengedEventKey =
"com.microsoft.kiota.authenticate_challenge_received";
Expand Down Expand Up @@ -804,26 +798,7 @@ String getClaimsFromResponse(
&& (claims == null || claims.isEmpty())
&& // we avoid infinite loops and retry only once
(requestInfo.content == null || requestInfo.content.markSupported())) {
final List<String> authenticateHeader = response.headers("WWW-Authenticate");
if (!authenticateHeader.isEmpty()) {
String rawHeaderValue = null;
for (final String authenticateEntry : authenticateHeader) {
final Matcher matcher = bearerPattern.matcher(authenticateEntry);
if (matcher.matches()) {
rawHeaderValue = authenticateEntry.replaceFirst("^Bearer\\s", "");
break;
}
}
if (rawHeaderValue != null) {
final String[] parameters = rawHeaderValue.split(",");
for (final String parameter : parameters) {
final Matcher matcher = claimsPattern.matcher(parameter);
if (matcher.matches()) {
return matcher.group(1);
}
}
}
}
return ContinuousAccessEvaluationClaims.getClaimsFromResponse(response);
}
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,79 @@

import io.opentelemetry.api.common.AttributeKey;

/**
* This class contains the telemetry attribute keys used by this library.
*/
public final class TelemetrySemanticConventions {
private TelemetrySemanticConventions() {}

// https://opentelemetry.io/docs/specs/semconv/attributes-registry/

/**
* HTTP Response status code
*/
public static final AttributeKey<Long> HTTP_RESPONSE_STATUS_CODE =
longKey("http.response.status_code"); // stable

/**
* HTTP Request resend count
*/
public static final AttributeKey<Long> HTTP_REQUEST_RESEND_COUNT =
longKey("http.request.resend_count"); // stable

/**
* HTTP Request method
*/
public static final AttributeKey<String> HTTP_REQUEST_METHOD =
stringKey("http.request.method"); // stable

/**
* Network connection protocol version
*/
public static final AttributeKey<String> NETWORK_PROTOCOL_VERSION =
stringKey("network.protocol.version"); // stable

/**
* Full HTTP request URL
*/
public static final AttributeKey<String> URL_FULL = stringKey("url.full"); // stable

/**
* HTTP request URL scheme
*/
public static final AttributeKey<String> URL_SCHEME = stringKey("url.scheme"); // stable

/**
* HTTP request destination server address
*/
public static final AttributeKey<String> SERVER_ADDRESS = stringKey("server.address"); // stable

/**
* HTTP request destination server port
*/
public static final AttributeKey<Long> SERVER_PORT = longKey("server.port"); // stable

/**
* HTTP response body size
*/
public static final AttributeKey<Long> EXPERIMENTAL_HTTP_RESPONSE_BODY_SIZE =
longKey("http.response.body.size"); // experimental

/**
* HTTP request body size
*/
public static final AttributeKey<Long> EXPERIMENTAL_HTTP_REQUEST_BODY_SIZE =
longKey("http.request.body.size"); // experimental

/**
* HTTP response content type
*/
public static final AttributeKey<String> CUSTOM_HTTP_RESPONSE_CONTENT_TYPE =
stringKey("http.response_content_type"); // custom

/**
* HTTP request content type
*/
public static final AttributeKey<String> CUSTOM_HTTP_REQUEST_CONTENT_TYPE =
stringKey("http.request_content_type"); // custom
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package com.microsoft.kiota.http.middleware;

import static com.microsoft.kiota.http.TelemetrySemanticConventions.HTTP_REQUEST_RESEND_COUNT;

import com.microsoft.kiota.authentication.AccessTokenProvider;
import com.microsoft.kiota.authentication.BaseBearerTokenAuthenticationProvider;
import com.microsoft.kiota.http.ContinuousAccessEvaluationClaims;
import com.microsoft.kiota.http.ObservabilityOptions;

import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.context.Scope;

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

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
* This interceptor is responsible for adding the Authorization header to the request
* if the header is not already present. It also handles Continuous Access Evaluation (CAE) claims
* challenges if the token request was made using this interceptor. It does this using the provided AuthenticationProvider
*/
public class AuthorizationHandler implements Interceptor {
Ndiritu marked this conversation as resolved.
Show resolved Hide resolved

@Nonnull private final BaseBearerTokenAuthenticationProvider authenticationProvider;
private static final String authorizationHeaderKey = "Authorization";

/**
* Instantiates a new AuthorizationHandler.
* @param authenticationProvider the authentication provider.
*/
public AuthorizationHandler(
@Nonnull final BaseBearerTokenAuthenticationProvider authenticationProvider) {
this.authenticationProvider =
Objects.requireNonNull(
authenticationProvider, "AuthenticationProvider cannot be null");
}

@Override
public Response intercept(final Chain chain) throws IOException {
Objects.requireNonNull(chain, "parameter chain cannot be null");
final Request request = chain.request();

final Span span =
GlobalOpenTelemetry.getTracer(
(new ObservabilityOptions()).getTracerInstrumentationName())
.spanBuilder("AuthorizationHandler_Intercept")
.startSpan();
Scope scope = null;
if (span != null) {
scope = span.makeCurrent();
span.setAttribute("com.microsoft.kiota.handler.authorization.enable", true);
}

try {
// Auth provider already added auth header
if (request.headers().names().contains(authorizationHeaderKey)) {
if (span != null)
span.setAttribute(
"com.microsoft.kiota.handler.authorization.token_present", true);
return chain.proceed(request);
}

final HashMap<String, Object> additionalContext = new HashMap<>();
additionalContext.put("parent-span", span);
final Request authenticatedRequest =
authenticateRequest(request, additionalContext, span);
final Response response = chain.proceed(authenticatedRequest);

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

// Attempt CAE claims challenge
final String claims = ContinuousAccessEvaluationClaims.getClaimsFromResponse(response);
if (claims == null || claims.isEmpty()) {
return response;
}

span.addEvent("com.microsoft.kiota.handler.authorization.challenge_received");

// We cannot replay one-shot requests after claims challenge
RequestBody requestBody = request.body();
Ndiritu marked this conversation as resolved.
Show resolved Hide resolved
if (requestBody != null && requestBody.isOneShot()) {
return response;
}

response.close();
additionalContext.put("claims", claims);
// Retry claims challenge only once
span.setAttribute(HTTP_REQUEST_RESEND_COUNT, 1);
final Request authenticatedRequestAfterCAE =
authenticateRequest(request, additionalContext, span);
return chain.proceed(authenticatedRequestAfterCAE);
} finally {
if (scope != null) {
scope.close();
}
if (span != null) {
span.end();
}
}
}

private @Nonnull Request authenticateRequest(
@Nonnull final Request request,
@Nullable final Map<String, Object> additionalAuthenticationContext,
@Nonnull final Span span) {

final AccessTokenProvider accessTokenProvider =
authenticationProvider.getAccessTokenProvider();
if (!accessTokenProvider.getAllowedHostsValidator().isUrlHostValid(request.url().uri())) {
return request;
}
final String accessToken =
accessTokenProvider.getAuthorizationToken(
request.url().uri(), additionalAuthenticationContext);
if (accessToken != null && !accessToken.isEmpty()) {
span.setAttribute("com.microsoft.kiota.handler.authorization.token_obtained", true);
Request.Builder requestBuilder = request.newBuilder();
Ndiritu marked this conversation as resolved.
Show resolved Hide resolved
requestBuilder.addHeader(authorizationHeaderKey, "Bearer " + accessToken);
return requestBuilder.build();
}
return request;
}
}
Loading
Loading