wangzhibo
2026-05-09 53418655c061ac26f66058253f39200aced1ab1d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { parseWWWAuthenticateHeader } from "./parseWWWAuthenticate.js";
import { createTokenCycler } from "./tokenCycler.js";
import { logger } from "./logger.js";
function verifyChallengeResource(scope, request) {
    let scopeAsUrl;
    try {
        scopeAsUrl = new URL(scope);
    }
    catch (e) {
        throw new Error(`The challenge contains invalid scope '${scope}'`);
    }
    const requestUrl = new URL(request.url);
    if (!requestUrl.hostname.endsWith(`.${scopeAsUrl.hostname}`)) {
        throw new Error(`The challenge resource '${scopeAsUrl.hostname}' does not match the requested domain. Set disableChallengeResourceVerification to true in your client options to disable. See https://aka.ms/azsdk/blog/vault-uri for more information.`);
    }
}
/**
 * Name of the Key Vault authentication policy.
 */
export const keyVaultAuthenticationPolicyName = "keyVaultAuthenticationPolicy";
/**
 * A custom implementation of the bearer-token authentication policy that handles Key Vault and CAE challenges.
 *
 * Key Vault supports other authentication schemes, but we ensure challenge authentication
 * is used by first sending a copy of the request, without authorization or content.
 *
 * when the challenge is received, it will be authenticated and used to send the original
 * request with authorization.
 *
 * Following the first request of a client, follow-up requests will get the cached token
 * if possible.
 *
 */
export function keyVaultAuthenticationPolicy(credential, options = {}) {
    const { disableChallengeResourceVerification } = options;
    let challengeState = { status: "none" };
    const getAccessToken = createTokenCycler(credential);
    function requestToOptions(request) {
        return {
            abortSignal: request.abortSignal,
            requestOptions: {
                timeout: request.timeout > 0 ? request.timeout : undefined,
            },
            tracingOptions: request.tracingOptions,
        };
    }
    async function authorizeRequest(request) {
        const requestOptions = requestToOptions(request);
        switch (challengeState.status) {
            case "none":
                challengeState = {
                    status: "started",
                    originalBody: request.body,
                };
                request.body = null;
                break;
            case "started":
                break; // Retry, we should not overwrite the original body
            case "complete": {
                const token = await getAccessToken(challengeState.scopes, {
                    ...requestOptions,
                    enableCae: true,
                    tenantId: challengeState.tenantId,
                });
                if (token) {
                    request.headers.set("authorization", `Bearer ${token.token}`);
                }
                break;
            }
        }
    }
    async function handleChallenge(request, response, next) {
        // If status is not 401, this is a no-op
        if (response.status !== 401) {
            return response;
        }
        if (request.body === null && challengeState.status === "started") {
            // Reset the original body before doing anything else.
            // Note: If successful status will be "complete", otherwise "none" will
            // restart the process.
            request.body = challengeState.originalBody;
        }
        const getTokenOptions = requestToOptions(request);
        const challenge = response.headers.get("WWW-Authenticate");
        if (!challenge) {
            logger.warning("keyVaultAuthentication policy encountered a 401 response without a corresponding WWW-Authenticate header. This is unexpected. Not handling the 401 response.");
            return response;
        }
        const parsedChallenge = parseWWWAuthenticateHeader(challenge);
        const scope = parsedChallenge.resource
            ? parsedChallenge.resource + "/.default"
            : parsedChallenge.scope;
        if (!scope) {
            // Cannot handle this kind of challenge here (if scope is not present, may be a CAE challenge)
            return response;
        }
        if (!disableChallengeResourceVerification) {
            verifyChallengeResource(scope, request);
        }
        const accessToken = await getAccessToken([scope], {
            ...getTokenOptions,
            enableCae: true,
            tenantId: parsedChallenge.tenantId,
        });
        if (!accessToken) {
            // No access token provided, treat as no-op
            return response;
        }
        request.headers.set("Authorization", `Bearer ${accessToken.token}`);
        challengeState = {
            status: "complete",
            scopes: [scope],
            tenantId: parsedChallenge.tenantId,
        };
        // We have a token now, so try send the request again
        return next(request);
    }
    async function handleCaeChallenge(request, response, next) {
        // Cannot handle CAE challenge if a regular challenge has not been completed first
        if (challengeState.status !== "complete") {
            return response;
        }
        // If status is not 401, this is a no-op
        if (response.status !== 401) {
            return response;
        }
        const getTokenOptions = requestToOptions(request);
        const challenge = response.headers.get("WWW-Authenticate");
        if (!challenge) {
            return response;
        }
        const { claims: base64EncodedClaims, error } = parseWWWAuthenticateHeader(challenge);
        if (error !== "insufficient_claims" || base64EncodedClaims === undefined) {
            return response;
        }
        const claims = atob(base64EncodedClaims);
        const accessToken = await getAccessToken(challengeState.scopes, {
            ...getTokenOptions,
            enableCae: true,
            tenantId: challengeState.tenantId,
            claims,
        });
        request.headers.set("Authorization", `Bearer ${accessToken.token}`);
        return next(request);
    }
    async function sendRequest(request, next) {
        // Add token if possible
        await authorizeRequest(request);
        // Try send request (first attempt)
        let response = await next(request);
        // Handle standard challenge if present
        response = await handleChallenge(request, response, next);
        // Handle CAE challenge if present
        response = await handleCaeChallenge(request, response, next);
        return response;
    }
    return {
        name: keyVaultAuthenticationPolicyName,
        sendRequest,
    };
}
//# sourceMappingURL=keyVaultAuthenticationPolicy.js.map