@azure/msal-node 5.4.3 → 5.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/dist/cache/CacheHelpers.mjs +32 -6
  2. package/dist/cache/CacheHelpers.mjs.map +1 -1
  3. package/dist/cache/NodeStorage.mjs +10 -7
  4. package/dist/cache/NodeStorage.mjs.map +1 -1
  5. package/dist/cache/TokenCache.mjs +1 -1
  6. package/dist/cache/distributed/DistributedCachePlugin.mjs +1 -1
  7. package/dist/cache/serializer/Deserializer.mjs +1 -1
  8. package/dist/cache/serializer/Serializer.mjs +1 -1
  9. package/dist/client/BaseClient.mjs +1 -1
  10. package/dist/client/ClientApplication.mjs +16 -6
  11. package/dist/client/ClientApplication.mjs.map +1 -1
  12. package/dist/client/ClientAssertion.mjs +1 -1
  13. package/dist/client/ClientCredentialClient.mjs +30 -7
  14. package/dist/client/ClientCredentialClient.mjs.map +1 -1
  15. package/dist/client/ConfidentialClientApplication.mjs +1 -1
  16. package/dist/client/DeviceCodeClient.mjs +2 -2
  17. package/dist/client/DeviceCodeClient.mjs.map +1 -1
  18. package/dist/client/ManagedIdentityApplication.mjs +1 -1
  19. package/dist/client/ManagedIdentityClient.mjs +1 -1
  20. package/dist/client/ManagedIdentitySources/AppService.mjs +1 -1
  21. package/dist/client/ManagedIdentitySources/AzureArc.mjs +93 -16
  22. package/dist/client/ManagedIdentitySources/AzureArc.mjs.map +1 -1
  23. package/dist/client/ManagedIdentitySources/BaseManagedIdentitySource.mjs +1 -1
  24. package/dist/client/ManagedIdentitySources/CloudShell.mjs +1 -1
  25. package/dist/client/ManagedIdentitySources/Imds.mjs +1 -1
  26. package/dist/client/ManagedIdentitySources/MachineLearning.mjs +1 -1
  27. package/dist/client/ManagedIdentitySources/ServiceFabric.mjs +1 -1
  28. package/dist/client/OnBehalfOfClient.mjs +44 -15
  29. package/dist/client/OnBehalfOfClient.mjs.map +1 -1
  30. package/dist/client/PublicClientApplication.mjs +1 -1
  31. package/dist/client/UserFederatedIdentityCredentialClient.mjs +11 -5
  32. package/dist/client/UserFederatedIdentityCredentialClient.mjs.map +1 -1
  33. package/dist/client/UsernamePasswordClient.mjs +2 -2
  34. package/dist/client/UsernamePasswordClient.mjs.map +1 -1
  35. package/dist/config/Configuration.mjs +1 -1
  36. package/dist/config/ManagedIdentityId.mjs +1 -1
  37. package/dist/config/ManagedIdentityRequestParameters.mjs +1 -1
  38. package/dist/crypto/CryptoProvider.mjs +13 -13
  39. package/dist/crypto/CryptoProvider.mjs.map +1 -1
  40. package/dist/crypto/GuidGenerator.mjs +1 -1
  41. package/dist/crypto/HashUtils.mjs +1 -1
  42. package/dist/crypto/PkceGenerator.mjs +1 -1
  43. package/dist/error/ClientAuthErrorCodes.mjs +1 -1
  44. package/dist/error/ManagedIdentityError.mjs +5 -4
  45. package/dist/error/ManagedIdentityError.mjs.map +1 -1
  46. package/dist/error/ManagedIdentityErrorCodes.mjs +3 -2
  47. package/dist/error/ManagedIdentityErrorCodes.mjs.map +1 -1
  48. package/dist/error/NodeAuthError.mjs +1 -1
  49. package/dist/index.mjs +1 -1
  50. package/dist/internals.mjs +1 -1
  51. package/dist/network/HttpClient.mjs +1 -1
  52. package/dist/network/HttpClientWithRetries.mjs +1 -1
  53. package/dist/network/LoopbackClient.mjs +1 -1
  54. package/dist/packageMetadata.mjs +2 -2
  55. package/dist/protocol/Authorize.mjs +1 -1
  56. package/dist/retry/DefaultManagedIdentityRetryPolicy.mjs +1 -1
  57. package/dist/retry/ExponentialRetryStrategy.mjs +1 -1
  58. package/dist/retry/ImdsRetryPolicy.mjs +1 -1
  59. package/dist/retry/LinearRetryStrategy.mjs +1 -1
  60. package/dist/utils/Constants.mjs +1 -1
  61. package/dist/utils/EncodingUtils.mjs +1 -1
  62. package/dist/utils/TimeUtils.mjs +1 -1
  63. package/lib/msal-node.cjs +709 -198
  64. package/lib/msal-node.cjs.map +1 -1
  65. package/package.json +2 -2
  66. package/src/cache/CacheHelpers.ts +36 -7
  67. package/src/cache/NodeStorage.ts +18 -6
  68. package/src/client/ClientApplication.ts +15 -5
  69. package/src/client/ClientCredentialClient.ts +34 -5
  70. package/src/client/DeviceCodeClient.ts +2 -1
  71. package/src/client/ManagedIdentitySources/AzureArc.ts +139 -19
  72. package/src/client/OnBehalfOfClient.ts +58 -14
  73. package/src/client/UserFederatedIdentityCredentialClient.ts +13 -3
  74. package/src/client/UsernamePasswordClient.ts +2 -1
  75. package/src/crypto/CryptoProvider.ts +31 -13
  76. package/src/error/ManagedIdentityError.ts +4 -2
  77. package/src/error/ManagedIdentityErrorCodes.ts +2 -0
  78. package/src/packageMetadata.ts +1 -1
  79. package/src/request/AuthorizationCodeRequest.ts +4 -0
  80. package/src/request/CommonClientCredentialRequest.ts +7 -0
  81. package/src/request/CommonOnBehalfOfRequest.ts +7 -0
  82. package/src/request/CommonUserFederatedIdentityCredentialRequest.ts +7 -0
  83. package/src/response/ManagedIdentityTokenResponse.ts +3 -0
  84. package/types/cache/CacheHelpers.d.ts +1 -1
  85. package/types/cache/CacheHelpers.d.ts.map +1 -1
  86. package/types/cache/NodeStorage.d.ts +7 -4
  87. package/types/cache/NodeStorage.d.ts.map +1 -1
  88. package/types/client/ClientApplication.d.ts.map +1 -1
  89. package/types/client/ClientCredentialClient.d.ts.map +1 -1
  90. package/types/client/DeviceCodeClient.d.ts.map +1 -1
  91. package/types/client/ManagedIdentitySources/AzureArc.d.ts +22 -8
  92. package/types/client/ManagedIdentitySources/AzureArc.d.ts.map +1 -1
  93. package/types/client/OnBehalfOfClient.d.ts.map +1 -1
  94. package/types/client/UserFederatedIdentityCredentialClient.d.ts.map +1 -1
  95. package/types/client/UsernamePasswordClient.d.ts.map +1 -1
  96. package/types/crypto/CryptoProvider.d.ts +11 -9
  97. package/types/crypto/CryptoProvider.d.ts.map +1 -1
  98. package/types/error/ManagedIdentityError.d.ts +1 -0
  99. package/types/error/ManagedIdentityError.d.ts.map +1 -1
  100. package/types/error/ManagedIdentityErrorCodes.d.ts +1 -0
  101. package/types/error/ManagedIdentityErrorCodes.d.ts.map +1 -1
  102. package/types/packageMetadata.d.ts +1 -1
  103. package/types/request/AuthorizationCodeRequest.d.ts +4 -0
  104. package/types/request/AuthorizationCodeRequest.d.ts.map +1 -1
  105. package/types/request/CommonClientCredentialRequest.d.ts +7 -0
  106. package/types/request/CommonClientCredentialRequest.d.ts.map +1 -1
  107. package/types/request/CommonOnBehalfOfRequest.d.ts +7 -0
  108. package/types/request/CommonOnBehalfOfRequest.d.ts.map +1 -1
  109. package/types/request/CommonUserFederatedIdentityCredentialRequest.d.ts +7 -0
  110. package/types/request/CommonUserFederatedIdentityCredentialRequest.d.ts.map +1 -1
  111. package/types/response/ManagedIdentityTokenResponse.d.ts +3 -0
  112. package/types/response/ManagedIdentityTokenResponse.d.ts.map +1 -1
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@azure/msal-node",
4
- "version": "5.4.3",
4
+ "version": "5.6.0",
5
5
  "author": {
6
6
  "name": "Microsoft",
7
7
  "email": "nugetaad@microsoft.com",
@@ -84,7 +84,7 @@
84
84
  "yargs": "^17.3.1"
85
85
  },
86
86
  "dependencies": {
87
- "@azure/msal-common": "16.11.3",
87
+ "@azure/msal-common": "16.13.0",
88
88
  "jsonwebtoken": "^9.0.0"
89
89
  },
90
90
  "engines": {
@@ -13,17 +13,41 @@ import { CACHE } from "../utils/Constants.js";
13
13
 
14
14
  /**
15
15
  * Computes a combined hash from additional cache key components.
16
- * Matches the cross-SDK algorithm: sort keys → concatenate key+value → SHA-256 → Base64URL (no padding).
16
+ *
17
+ * Matches the cross-SDK algorithm: sort keys ascending → for each key append a
18
+ * length-prefixed (netstring-style) encoding of the key and value → SHA-256 →
19
+ * Base64URL (no padding).
20
+ *
21
+ * Each entry is encoded as `<byteLen(key)>:<key><byteLen(value)>:<value>` where the
22
+ * lengths are the UTF-8 **byte** lengths (via `Buffer.byteLength`, not `String.length`
23
+ * which counts UTF-16 code units). The length prefixes make the serialization injective
24
+ * so that semantically different component sets can never serialize to the same byte
25
+ * string. A plain delimiter-less concatenation of key+value is ambiguous
26
+ * (e.g. `{fmi_path:"value"}` and `{fmi_pat:"hvalue"}` would both yield `fmi_pathvalue`),
27
+ * which would collide into the same credential cache slot.
28
+ *
29
+ * The encoding is byte-identical to the other MSAL SDKs (Go/.NET/Java/Python), so the
30
+ * resulting hash is a stable cross-SDK cache key. The final credential key is lowercased
31
+ * downstream in `generateCredentialKey`.
17
32
  */
18
33
  function computeAdditionalCacheKeyHash(
19
34
  components: Record<string, string>
20
35
  ): string {
21
36
  const sortedKeys = Object.keys(components).sort();
22
- const input = sortedKeys.map((k) => k + components[k]).join("");
37
+ let input = "";
38
+ for (const key of sortedKeys) {
39
+ const value = components[key];
40
+ input +=
41
+ `${Buffer.byteLength(key, "utf8")}:${key}` +
42
+ `${Buffer.byteLength(value, "utf8")}:${value}`;
43
+ }
23
44
  return createHash("sha256").update(input, "utf8").digest("base64url");
24
45
  }
25
46
 
26
- export function generateCredentialKey(credential: CredentialEntity): string {
47
+ export function generateCredentialKey(
48
+ credential: CredentialEntity,
49
+ hash?: string
50
+ ): string {
27
51
  const familyId =
28
52
  (credential.credentialType === Constants.CredentialType.REFRESH_TOKEN &&
29
53
  credential.familyId) ||
@@ -44,15 +68,20 @@ export function generateCredentialKey(credential: CredentialEntity): string {
44
68
  scheme,
45
69
  ];
46
70
 
47
- // Compute and append a combined hash from additional cache key components (e.g., fmi_path)
71
+ /*
72
+ * Compute and append a combined hash from additional cache key components (e.g., fmi_path).
73
+ * Use the explicitly passed hash if available; fall back to synchronous inline compute
74
+ * for lookup paths where the entity was read from storage without a cached hash.
75
+ */
48
76
  if (
49
77
  credential.additionalCacheKeyComponents &&
50
78
  Object.keys(credential.additionalCacheKeyComponents).length > 0
51
79
  ) {
52
80
  credentialKey.push(
53
- computeAdditionalCacheKeyHash(
54
- credential.additionalCacheKeyComponents
55
- )
81
+ hash ??
82
+ computeAdditionalCacheKeyHash(
83
+ credential.additionalCacheKeyComponents
84
+ )
56
85
  );
57
86
  }
58
87
 
@@ -206,8 +206,11 @@ export class NodeStorage extends CacheManager {
206
206
  this.setCache(cache);
207
207
  }
208
208
 
209
- generateCredentialKey(credential: CredentialEntity): string {
210
- return generateCredentialKey(credential);
209
+ generateCredentialKey(
210
+ credential: CredentialEntity,
211
+ additionalCacheKeyHash?: string
212
+ ): string {
213
+ return generateCredentialKey(credential, additionalCacheKeyHash);
211
214
  }
212
215
 
213
216
  generateAccountKey(account: AccountInfo): string {
@@ -289,13 +292,22 @@ export class NodeStorage extends CacheManager {
289
292
  }
290
293
 
291
294
  /**
292
- * set accessToken credential
293
- * @param accessToken - cache value to be set of type AccessTokenEntity
295
+ * Set accessToken credential to the cache
296
+ * @param accessToken - the access token entity to cache
297
+ * @param _correlationId - unique identifier for the request
298
+ * @param _kmsi - keep me signed in flag
299
+ * @param additionalCacheKeyHash - optional precomputed hash of additionalCacheKeyComponents used in key generation
294
300
  */
295
301
  async setAccessTokenCredential(
296
- accessToken: AccessTokenEntity
302
+ accessToken: AccessTokenEntity,
303
+ _correlationId: string,
304
+ _kmsi: boolean,
305
+ additionalCacheKeyHash?: string
297
306
  ): Promise<void> {
298
- const accessTokenKey = this.generateCredentialKey(accessToken);
307
+ const accessTokenKey = this.generateCredentialKey(
308
+ accessToken,
309
+ additionalCacheKeyHash
310
+ );
299
311
  this.setItem(accessTokenKey, accessToken);
300
312
  }
301
313
 
@@ -161,18 +161,28 @@ export abstract class ClientApplication {
161
161
  "acquireTokenByCode called",
162
162
  request.correlationId || ""
163
163
  );
164
- if (request.state && authCodePayLoad) {
164
+ let validatedAuthCodePayload = authCodePayLoad;
165
+ if (request.state && validatedAuthCodePayload) {
165
166
  this.logger.info(
166
167
  "acquireTokenByCode - validating state",
167
168
  request.correlationId || ""
168
169
  );
169
170
  this.validateState(
170
171
  request.state,
171
- authCodePayLoad.state || "",
172
+ validatedAuthCodePayload.state || "",
172
173
  request.correlationId || ""
173
174
  );
174
- // eslint-disable-next-line no-param-reassign
175
- authCodePayLoad = { ...authCodePayLoad, state: "" };
175
+ validatedAuthCodePayload = {
176
+ ...validatedAuthCodePayload,
177
+ state: "",
178
+ };
179
+ }
180
+ if (request.nonce) {
181
+ validatedAuthCodePayload = {
182
+ ...validatedAuthCodePayload,
183
+ code: request.code,
184
+ nonce: request.nonce,
185
+ };
176
186
  }
177
187
  const validRequest: CommonAuthorizationCodeRequest = {
178
188
  ...request,
@@ -208,7 +218,7 @@ export abstract class ClientApplication {
208
218
  return await authorizationCodeClient.acquireToken(
209
219
  validRequest,
210
220
  ApiId.acquireTokenByCode,
211
- authCodePayLoad
221
+ validatedAuthCodePayload
212
222
  );
213
223
  } catch (e) {
214
224
  if (e instanceof AuthError) {
@@ -60,15 +60,32 @@ export class ClientCredentialClient extends BaseClient {
60
60
  public async acquireToken(
61
61
  request: CommonClientCredentialRequest
62
62
  ): Promise<AuthenticationResult | null> {
63
- // Build additional cache key components for FMI cache isolation
63
+ // Build additional cache key components for cache isolation
64
64
  let additionalCacheKeyComponents: Record<string, string> | undefined;
65
65
  if (request.fmiPath) {
66
66
  additionalCacheKeyComponents = {
67
+ ...additionalCacheKeyComponents,
67
68
  fmi_path: request.fmiPath,
68
69
  };
69
70
  }
71
+ /*
72
+ * Client-originated claims participate in the cache key (unlike server-issued `claims`,
73
+ * which bypasses the cache). Identical claims values are served from cache; different
74
+ * values produce separate cache entries. Gate on `!isEmptyObj` (not just `trim()`) so an
75
+ * empty/whitespace or empty-object (`{}`) value - which contributes nothing to the request
76
+ * body - does not fragment the cache from an omitted `claimsFromClient`.
77
+ */
78
+ if (
79
+ request.claimsFromClient &&
80
+ !StringUtils.isEmptyObj(request.claimsFromClient)
81
+ ) {
82
+ additionalCacheKeyComponents = {
83
+ ...additionalCacheKeyComponents,
84
+ client_claims: request.claimsFromClient,
85
+ };
86
+ }
70
87
 
71
- if (request.skipCache || request.claims) {
88
+ if (request.skipCache || !StringUtils.isEmptyObj(request.claims)) {
72
89
  return this.executeTokenRequest(
73
90
  request,
74
91
  this.authority,
@@ -221,7 +238,10 @@ export class ClientCredentialClient extends BaseClient {
221
238
  },
222
239
  true,
223
240
  request,
224
- this.performanceClient
241
+ this.performanceClient,
242
+ {
243
+ tokenBindingKeyManager: this.config.tokenBindingKeyManager,
244
+ }
225
245
  ),
226
246
  lastCacheOutcome,
227
247
  ];
@@ -353,7 +373,8 @@ export class ClientCredentialClient extends BaseClient {
353
373
  this.logger,
354
374
  this.performanceClient,
355
375
  this.config.serializableCache,
356
- this.config.persistencePlugin
376
+ this.config.persistencePlugin,
377
+ this.config.tokenBindingKeyManager
357
378
  );
358
379
 
359
380
  responseHandler.validateTokenResponse(
@@ -460,8 +481,14 @@ export class ClientCredentialClient extends BaseClient {
460
481
  parameters.set(AADServerParamKeys.FMI_PATH, request.fmiPath);
461
482
  }
462
483
 
484
+ /*
485
+ * Deep-merge the server-issued `claims` challenge with client-originated `claimsFromClient`
486
+ * (via addClaims -> buildMergedClaims) so both are sent on the wire. Client capabilities
487
+ * are appended by buildMergedClaims.
488
+ */
463
489
  if (
464
490
  !StringUtils.isEmptyObj(request.claims) ||
491
+ !StringUtils.isEmptyObj(request.claimsFromClient) ||
465
492
  (this.config.authOptions.clientCapabilities &&
466
493
  this.config.authOptions.clientCapabilities.length > 0)
467
494
  ) {
@@ -469,7 +496,9 @@ export class ClientCredentialClient extends BaseClient {
469
496
  parameters,
470
497
  request.correlationId,
471
498
  request.claims,
472
- this.config.authOptions.clientCapabilities
499
+ this.config.authOptions.clientCapabilities,
500
+ undefined,
501
+ request.claimsFromClient
473
502
  );
474
503
  }
475
504
 
@@ -58,7 +58,8 @@ export class DeviceCodeClient extends BaseClient {
58
58
  this.logger,
59
59
  this.performanceClient,
60
60
  this.config.serializableCache,
61
- this.config.persistencePlugin
61
+ this.config.persistencePlugin,
62
+ this.config.tokenBindingKeyManager
62
63
  );
63
64
 
64
65
  // Validate response. This function throws a server error if an error is returned by the server.
@@ -15,7 +15,10 @@ import {
15
15
  Constants,
16
16
  } from "@azure/msal-common/node";
17
17
  import { ManagedIdentityRequestParameters } from "../../config/ManagedIdentityRequestParameters.js";
18
- import { BaseManagedIdentitySource } from "./BaseManagedIdentitySource.js";
18
+ import {
19
+ BaseManagedIdentitySource,
20
+ ManagedIdentityUserAssignedIdQueryParameterNames,
21
+ } from "./BaseManagedIdentitySource.js";
19
22
  import { CryptoProvider } from "../../crypto/CryptoProvider.js";
20
23
  import {
21
24
  ManagedIdentityErrorCodes,
@@ -153,20 +156,20 @@ export class AzureArc extends BaseManagedIdentitySource {
153
156
  * Attempts to create an AzureArc managed identity source instance.
154
157
  *
155
158
  * Validates the Azure Arc environment by checking environment variables
156
- * and performing file-based detection. It ensures that only system-assigned managed identities
157
- * are supported for Azure Arc scenarios. The method performs comprehensive validation of
158
- * endpoint URLs and logs detailed information about the detection process.
159
+ * and performing file-based detection. Azure Arc supports both system-assigned and user-assigned
160
+ * managed identities; when a user-assigned identity is requested, its selector is forwarded on the
161
+ * request and validated against the token response echo (fail closed). The method performs
162
+ * comprehensive validation of endpoint URLs and logs detailed information about the detection process.
159
163
  *
160
164
  * @param logger - Logger instance for capturing creation and validation steps
161
165
  * @param nodeStorage - Storage implementation for the managed identity source
162
166
  * @param networkClient - Network client for HTTP communication
163
167
  * @param cryptoProvider - Cryptographic operations provider
164
168
  * @param disableInternalRetries - Whether to disable automatic retry mechanisms
165
- * @param managedIdentityId - The managed identity configuration, must be system-assigned
169
+ * @param _managedIdentityId - Unused; Azure Arc now supports user-assigned identities, which are
170
+ * forwarded on the request and validated against the token response echo (fail closed).
166
171
  *
167
172
  * @returns AzureArc instance if the environment supports Azure Arc managed identity, null otherwise
168
- *
169
- * @throws {ManagedIdentityError} When a user-assigned managed identity is specified (not supported for Azure Arc)
170
173
  */
171
174
  public static tryCreate(
172
175
  logger: Logger,
@@ -174,7 +177,8 @@ export class AzureArc extends BaseManagedIdentitySource {
174
177
  networkClient: INetworkModule,
175
178
  cryptoProvider: CryptoProvider,
176
179
  disableInternalRetries: boolean,
177
- managedIdentityId: ManagedIdentityId
180
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
181
+ _managedIdentityId: ManagedIdentityId
178
182
  ): AzureArc | null {
179
183
  const [identityEndpoint, imdsEndpoint] =
180
184
  AzureArc.getEnvironmentVariables();
@@ -223,15 +227,6 @@ export class AzureArc extends BaseManagedIdentitySource {
223
227
  );
224
228
  }
225
229
 
226
- if (
227
- managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED
228
- ) {
229
- throw createManagedIdentityError(
230
- ManagedIdentityErrorCodes.unableToCreateAzureArc,
231
- ""
232
- );
233
- }
234
-
235
230
  return new AzureArc(
236
231
  logger,
237
232
  nodeStorage,
@@ -253,7 +248,10 @@ export class AzureArc extends BaseManagedIdentitySource {
253
248
  *
254
249
  * @returns A configured ManagedIdentityRequestParameters object ready for network execution
255
250
  */
256
- public createRequest(resource: string): ManagedIdentityRequestParameters {
251
+ public createRequest(
252
+ resource: string,
253
+ managedIdentityId: ManagedIdentityId
254
+ ): ManagedIdentityRequestParameters {
257
255
  const request: ManagedIdentityRequestParameters =
258
256
  new ManagedIdentityRequestParameters(
259
257
  HttpMethod.GET,
@@ -267,11 +265,118 @@ export class AzureArc extends BaseManagedIdentitySource {
267
265
  request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] =
268
266
  resource;
269
267
 
268
+ if (
269
+ managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED
270
+ ) {
271
+ /*
272
+ * Forward the user-assigned selector. Azure Arc honors the IMDS "msi_res_id" spelling for
273
+ * the resource-id selector (isImds = true); "mi_res_id" is silently ignored and returns
274
+ * the system-assigned identity.
275
+ */
276
+ request.queryParameters[
277
+ this.getManagedIdentityUserAssignedIdQueryParameterKey(
278
+ managedIdentityId.idType,
279
+ true // isImds -> msi_res_id for the resource-id selector
280
+ )
281
+ ] = managedIdentityId.id;
282
+ }
283
+
270
284
  // bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity
271
285
 
272
286
  return request;
273
287
  }
274
288
 
289
+ /**
290
+ * Fails closed when a user-assigned identity was requested but the Azure Arc token response does
291
+ * not confirm it. A legacy Azure Arc agent ignores the client_id / object_id / msi_res_id selector
292
+ * and silently returns the machine's system-assigned identity; an agent that supports user-assigned
293
+ * managed identity echoes the identity it used. When the echoed identity is missing or does not
294
+ * match the requested selector, MSAL must not return a token for a different identity than requested.
295
+ *
296
+ * @param networkRequest - The request that produced this response; its query parameters carry the
297
+ * requested user-assigned selector (client_id / object_id / msi_res_id)
298
+ * @param responseBody - The deserialized Azure Arc token response
299
+ *
300
+ * @throws {ManagedIdentityError} When a user-assigned identity was requested but not confirmed
301
+ */
302
+ private validateUserAssignedIdentityWasHonored(
303
+ networkRequest: ManagedIdentityRequestParameters,
304
+ responseBody: ManagedIdentityTokenResponse
305
+ ): void {
306
+ /*
307
+ * Derive the requested selector from the request that produced this response rather than from
308
+ * instance state. The managed identity source instance is cached and reused across acquireToken
309
+ * calls, so relying on a stored field could compare against a different identity than the one
310
+ * this request actually asked for. The network request is scoped to this call and carries exactly
311
+ * one user-assigned selector (client_id, object_id, or msi_res_id) when a UAMI was requested.
312
+ */
313
+ const queryParameters: Record<string, string> =
314
+ networkRequest.queryParameters;
315
+
316
+ let requestedIdentity: string | undefined;
317
+ let echoedIdentity: string | undefined;
318
+
319
+ if (
320
+ queryParameters[
321
+ ManagedIdentityUserAssignedIdQueryParameterNames
322
+ .MANAGED_IDENTITY_CLIENT_ID
323
+ ]
324
+ ) {
325
+ requestedIdentity =
326
+ queryParameters[
327
+ ManagedIdentityUserAssignedIdQueryParameterNames
328
+ .MANAGED_IDENTITY_CLIENT_ID
329
+ ];
330
+ echoedIdentity = responseBody.client_id;
331
+ } else if (
332
+ queryParameters[
333
+ ManagedIdentityUserAssignedIdQueryParameterNames
334
+ .MANAGED_IDENTITY_OBJECT_ID
335
+ ]
336
+ ) {
337
+ requestedIdentity =
338
+ queryParameters[
339
+ ManagedIdentityUserAssignedIdQueryParameterNames
340
+ .MANAGED_IDENTITY_OBJECT_ID
341
+ ];
342
+ echoedIdentity = responseBody.object_id;
343
+ } else if (
344
+ queryParameters[
345
+ ManagedIdentityUserAssignedIdQueryParameterNames
346
+ .MANAGED_IDENTITY_RESOURCE_ID_IMDS
347
+ ]
348
+ ) {
349
+ requestedIdentity =
350
+ queryParameters[
351
+ ManagedIdentityUserAssignedIdQueryParameterNames
352
+ .MANAGED_IDENTITY_RESOURCE_ID_IMDS
353
+ ];
354
+ // Accept either spelling on the echo as a safety net; Azure Arc returns msi_res_id.
355
+ echoedIdentity = responseBody.msi_res_id || responseBody.mi_res_id;
356
+ } else {
357
+ // System-assigned (no user-assigned selector forwarded): nothing to confirm.
358
+ return;
359
+ }
360
+
361
+ /*
362
+ * Compare case-insensitively: client_id / object_id are GUIDs, and an ARM resource id can
363
+ * legitimately differ in segment casing.
364
+ */
365
+ if (
366
+ !echoedIdentity ||
367
+ echoedIdentity.toLowerCase() !== requestedIdentity.toLowerCase()
368
+ ) {
369
+ this.logger.error(
370
+ "[Managed Identity] Azure Arc did not confirm the requested user-assigned identity in the token response. The agent likely does not support user-assigned managed identity and returned the system-assigned identity.",
371
+ ""
372
+ );
373
+ throw createManagedIdentityError(
374
+ ManagedIdentityErrorCodes.userAssignedManagedIdentityNotConfirmed,
375
+ ""
376
+ );
377
+ }
378
+ }
379
+
275
380
  /**
276
381
  * Processes the server response and handles Azure Arc-specific authentication challenges.
277
382
  *
@@ -420,6 +525,21 @@ export class AzureArc extends BaseManagedIdentitySource {
420
525
  }
421
526
  }
422
527
 
423
- return this.getServerTokenResponse(retryResponse || originalResponse);
528
+ const finalResponse: NetworkResponse<ManagedIdentityTokenResponse> =
529
+ retryResponse || originalResponse;
530
+
531
+ /*
532
+ * Fail closed: when a user-assigned identity was requested and the agent returned a token,
533
+ * ensure the echoed identity matches. A genuine service error (no access_token, e.g. a 404
534
+ * for a non-existent identity) is surfaced normally by the response handler.
535
+ */
536
+ if (finalResponse.body.access_token) {
537
+ this.validateUserAssignedIdentityWasHonored(
538
+ networkRequest,
539
+ finalResponse.body
540
+ );
541
+ }
542
+
543
+ return this.getServerTokenResponse(finalResponse);
424
544
  }
425
545
  }
@@ -21,6 +21,7 @@ import {
21
21
  RequestThumbprint,
22
22
  ResponseHandler,
23
23
  ScopeSet,
24
+ StringUtils,
24
25
  TimeUtils,
25
26
  TokenClaims,
26
27
  UrlString,
@@ -62,22 +63,44 @@ export class OnBehalfOfClient extends BaseClient {
62
63
  request.oboAssertion
63
64
  );
64
65
 
65
- if (request.skipCache || request.claims) {
66
+ /*
67
+ * Client-originated claims participate in the cache key (unlike server-issued `claims`,
68
+ * which bypasses the cache). Identical claims values are served from cache; different
69
+ * values produce separate cache entries. Gate on `!isEmptyObj` (not just `trim()`) so an
70
+ * empty/whitespace or empty-object (`{}`) value - which contributes nothing to the request
71
+ * body - does not fragment the cache from an omitted `claimsFromClient`.
72
+ */
73
+ let additionalCacheKeyComponents: Record<string, string> | undefined;
74
+ if (
75
+ request.claimsFromClient &&
76
+ !StringUtils.isEmptyObj(request.claimsFromClient)
77
+ ) {
78
+ additionalCacheKeyComponents = {
79
+ client_claims: request.claimsFromClient,
80
+ };
81
+ }
82
+
83
+ if (request.skipCache || !StringUtils.isEmptyObj(request.claims)) {
66
84
  return this.executeTokenRequest(
67
85
  request,
68
86
  this.authority,
69
- this.userAssertionHash
87
+ this.userAssertionHash,
88
+ additionalCacheKeyComponents
70
89
  );
71
90
  }
72
91
 
73
92
  try {
74
- return await this.getCachedAuthenticationResult(request);
93
+ return await this.getCachedAuthenticationResult(
94
+ request,
95
+ additionalCacheKeyComponents
96
+ );
75
97
  } catch (e) {
76
98
  // Any failure falls back to interactive request, once we implement distributed cache, we plan to handle `createRefreshRequiredError` to refresh using the RT
77
99
  return await this.executeTokenRequest(
78
100
  request,
79
101
  this.authority,
80
- this.userAssertionHash
102
+ this.userAssertionHash,
103
+ additionalCacheKeyComponents
81
104
  );
82
105
  }
83
106
  }
@@ -91,12 +114,14 @@ export class OnBehalfOfClient extends BaseClient {
91
114
  * @param request - developer provided CommonOnBehalfOfRequest
92
115
  */
93
116
  private async getCachedAuthenticationResult(
94
- request: CommonOnBehalfOfRequest
117
+ request: CommonOnBehalfOfRequest,
118
+ additionalCacheKeyComponents?: Record<string, string>
95
119
  ): Promise<AuthenticationResult | null> {
96
120
  // look in the cache for the access_token which matches the incoming_assertion
97
121
  const cachedAccessToken = this.readAccessTokenFromCacheForOBO(
98
122
  this.config.authOptions.clientId,
99
- request
123
+ request,
124
+ additionalCacheKeyComponents
100
125
  );
101
126
  if (!cachedAccessToken) {
102
127
  // Must refresh due to non-existent access_token.
@@ -177,7 +202,10 @@ export class OnBehalfOfClient extends BaseClient {
177
202
  true,
178
203
  request,
179
204
  this.performanceClient,
180
- idTokenClaims
205
+ {
206
+ idTokenClaims,
207
+ tokenBindingKeyManager: this.config.tokenBindingKeyManager,
208
+ }
181
209
  );
182
210
  }
183
211
 
@@ -216,7 +244,8 @@ export class OnBehalfOfClient extends BaseClient {
216
244
  */
217
245
  private readAccessTokenFromCacheForOBO(
218
246
  clientId: string,
219
- request: CommonOnBehalfOfRequest
247
+ request: CommonOnBehalfOfRequest,
248
+ additionalCacheKeyComponents?: Record<string, string>
220
249
  ) {
221
250
  const authScheme =
222
251
  request.authenticationScheme ||
@@ -242,6 +271,7 @@ export class OnBehalfOfClient extends BaseClient {
242
271
  tokenType: authScheme,
243
272
  keyId: request.sshKid,
244
273
  userAssertionHash: this.userAssertionHash,
274
+ additionalCacheKeyComponents: additionalCacheKeyComponents,
245
275
  };
246
276
 
247
277
  const accessTokens = this.cacheManager.getAccessTokensByFilter(
@@ -270,7 +300,8 @@ export class OnBehalfOfClient extends BaseClient {
270
300
  private async executeTokenRequest(
271
301
  request: CommonOnBehalfOfRequest,
272
302
  authority: Authority,
273
- userAssertionHash: string
303
+ userAssertionHash: string,
304
+ additionalCacheKeyComponents?: Record<string, string>
274
305
  ): Promise<AuthenticationResult | null> {
275
306
  const queryParametersString = this.createTokenQueryParameters(request);
276
307
  const endpoint = UrlString.appendQueryString(
@@ -308,7 +339,8 @@ export class OnBehalfOfClient extends BaseClient {
308
339
  this.logger,
309
340
  this.performanceClient,
310
341
  this.config.serializableCache,
311
- this.config.persistencePlugin
342
+ this.config.persistencePlugin,
343
+ this.config.tokenBindingKeyManager
312
344
  );
313
345
 
314
346
  responseHandler.validateTokenResponse(
@@ -321,8 +353,12 @@ export class OnBehalfOfClient extends BaseClient {
321
353
  reqTimestamp,
322
354
  request,
323
355
  ApiId.acquireTokenByOBO,
324
- undefined,
325
- userAssertionHash
356
+ undefined, // authCodePayload
357
+ userAssertionHash, // userAssertionHash
358
+ undefined, // handlingRefreshTokenResponse
359
+ undefined, // forceCacheRefreshTokenResponse
360
+ undefined, // serverRequestId
361
+ additionalCacheKeyComponents
326
362
  );
327
363
 
328
364
  return tokenResponse;
@@ -412,8 +448,14 @@ export class OnBehalfOfClient extends BaseClient {
412
448
  );
413
449
  }
414
450
 
451
+ /*
452
+ * Deep-merge the server-issued `claims` challenge with client-originated `claimsFromClient`
453
+ * (via addClaims -> buildMergedClaims) so both are sent on the wire. Client capabilities
454
+ * are appended by buildMergedClaims.
455
+ */
415
456
  if (
416
- request.claims ||
457
+ !StringUtils.isEmptyObj(request.claims) ||
458
+ !StringUtils.isEmptyObj(request.claimsFromClient) ||
417
459
  (this.config.authOptions.clientCapabilities &&
418
460
  this.config.authOptions.clientCapabilities.length > 0)
419
461
  ) {
@@ -421,7 +463,9 @@ export class OnBehalfOfClient extends BaseClient {
421
463
  parameters,
422
464
  request.correlationId,
423
465
  request.claims,
424
- this.config.authOptions.clientCapabilities
466
+ this.config.authOptions.clientCapabilities,
467
+ undefined,
468
+ request.claimsFromClient
425
469
  );
426
470
  }
427
471