|
| 1 | +/** |
| 2 | + * ------------------------------------------------------------------------------------------- |
| 3 | + * Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. |
| 4 | + * See License in the project root for license information. |
| 5 | + * ------------------------------------------------------------------------------------------- |
| 6 | + */ |
| 7 | + |
| 8 | +import { type RequestOption } from "@microsoft/kiota-abstractions"; |
| 9 | +import { Span, trace } from "@opentelemetry/api"; |
| 10 | + |
| 11 | +import { getObservabilityOptionsFromRequest } from "../observabilityOptions"; |
| 12 | +import type { Middleware } from "./middleware"; |
| 13 | +import type { FetchRequestInit } from "../utils/fetchDefinitions"; |
| 14 | +import { getRequestHeader, setRequestHeader } from "../utils/headersUtil"; |
| 15 | +import { type AccessTokenProvider } from "@microsoft/kiota-abstractions/src"; |
| 16 | + |
| 17 | +export class AuthorizationHandler implements Middleware { |
| 18 | + next: Middleware | undefined; |
| 19 | + |
| 20 | + /** |
| 21 | + * A member holding the name of content range header |
| 22 | + */ |
| 23 | + private static readonly AUTHORIZATION_HEADER = "Authorization"; |
| 24 | + |
| 25 | + public constructor(private readonly accessTokenProvider: AccessTokenProvider) { |
| 26 | + if (!accessTokenProvider) { |
| 27 | + throw new Error("accessTokenProvider cannot be undefined"); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + public execute(url: string, requestInit: RequestInit, requestOptions?: Record<string, RequestOption>): Promise<Response> { |
| 32 | + const obsOptions = getObservabilityOptionsFromRequest(requestOptions); |
| 33 | + if (obsOptions) { |
| 34 | + return trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("authorizationHandler - execute", (span) => { |
| 35 | + try { |
| 36 | + span.setAttribute("com.microsoft.kiota.handler.authorization.enable", true); |
| 37 | + return this.executeInternal(url, requestInit as FetchRequestInit, requestOptions, span); |
| 38 | + } finally { |
| 39 | + span.end(); |
| 40 | + } |
| 41 | + }); |
| 42 | + } |
| 43 | + return this.executeInternal(url, requestInit as FetchRequestInit, requestOptions, undefined); |
| 44 | + } |
| 45 | + |
| 46 | + private async executeInternal(url: string, fetchRequestInit: FetchRequestInit, requestOptions?: Record<string, RequestOption>, span?: Span): Promise<Response> { |
| 47 | + if (this.authorizationIsPresent(fetchRequestInit)) { |
| 48 | + span?.setAttribute("com.microsoft.kiota.handler.authorization.token_present", true); |
| 49 | + return await this.next!.execute(url, fetchRequestInit as RequestInit, requestOptions); |
| 50 | + } |
| 51 | + |
| 52 | + const token = await this.authenticateRequest(url); |
| 53 | + setRequestHeader(fetchRequestInit, AuthorizationHandler.AUTHORIZATION_HEADER, `Bearer ${token}`); |
| 54 | + const response = await this.next?.execute(url, fetchRequestInit as RequestInit, requestOptions); |
| 55 | + if (!response) { |
| 56 | + throw new Error("Response is undefined"); |
| 57 | + } |
| 58 | + if (response.status !== 401) { |
| 59 | + return response; |
| 60 | + } |
| 61 | + const claims = this.getClaimsFromResponse(response); |
| 62 | + if (!claims) { |
| 63 | + return response; |
| 64 | + } |
| 65 | + span?.addEvent("com.microsoft.kiota.handler.authorization.challenge_received"); |
| 66 | + const claimsToken = await this.authenticateRequest(url, claims); |
| 67 | + setRequestHeader(fetchRequestInit, AuthorizationHandler.AUTHORIZATION_HEADER, `Bearer ${claimsToken}`); |
| 68 | + span?.setAttribute("http.request.resend_count", 1); |
| 69 | + const retryResponse = await this.next?.execute(url, fetchRequestInit as RequestInit, requestOptions); |
| 70 | + if (!retryResponse) { |
| 71 | + throw new Error("Response is undefined"); |
| 72 | + } |
| 73 | + return retryResponse; |
| 74 | + } |
| 75 | + |
| 76 | + private authorizationIsPresent(request: FetchRequestInit | undefined): boolean { |
| 77 | + if (!request) { |
| 78 | + return false; |
| 79 | + } |
| 80 | + const authorizationHeader = getRequestHeader(request, AuthorizationHandler.AUTHORIZATION_HEADER); |
| 81 | + return authorizationHeader !== undefined && authorizationHeader !== null; |
| 82 | + } |
| 83 | + |
| 84 | + private async authenticateRequest(url: string, claims?: string): Promise<string> { |
| 85 | + const additionalAuthenticationContext = {} as Record<string, unknown>; |
| 86 | + if (claims) { |
| 87 | + additionalAuthenticationContext.claims = claims; |
| 88 | + } |
| 89 | + return await this.accessTokenProvider.getAuthorizationToken(url, additionalAuthenticationContext); |
| 90 | + } |
| 91 | + |
| 92 | + private readonly getClaimsFromResponse = (response: Response, claims?: string) => { |
| 93 | + if (response.status === 401 && !claims) { |
| 94 | + // avoid infinite loop, we only retry once |
| 95 | + // no need to check for the content since it's an array and it doesn't need to be rewound |
| 96 | + const rawAuthenticateHeader = response.headers.get("WWW-Authenticate"); |
| 97 | + if (rawAuthenticateHeader && /^Bearer /gi.test(rawAuthenticateHeader)) { |
| 98 | + const rawParameters = rawAuthenticateHeader.replace(/^Bearer /gi, "").split(","); |
| 99 | + for (const rawParameter of rawParameters) { |
| 100 | + const trimmedParameter = rawParameter.trim(); |
| 101 | + if (/claims="[^"]+"/gi.test(trimmedParameter)) { |
| 102 | + return trimmedParameter.replace(/claims="([^"]+)"/gi, "$1"); |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | + } |
| 107 | + return undefined; |
| 108 | + }; |
| 109 | +} |
0 commit comments