@azure/identity 4.5.0-beta.1 → 4.5.0-beta.3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (233) hide show
  1. package/README.md +67 -50
  2. package/dist/index.js +355 -170
  3. package/dist/index.js.map +1 -1
  4. package/dist-esm/src/client/identityClient.js +4 -4
  5. package/dist-esm/src/client/identityClient.js.map +1 -1
  6. package/dist-esm/src/constants.js +2 -2
  7. package/dist-esm/src/constants.js.map +1 -1
  8. package/dist-esm/src/credentials/authorityValidationOptions.js +1 -1
  9. package/dist-esm/src/credentials/authorityValidationOptions.js.map +1 -1
  10. package/dist-esm/src/credentials/authorizationCodeCredential.browser.js +1 -1
  11. package/dist-esm/src/credentials/authorizationCodeCredential.browser.js.map +1 -1
  12. package/dist-esm/src/credentials/authorizationCodeCredential.js +1 -1
  13. package/dist-esm/src/credentials/authorizationCodeCredential.js.map +1 -1
  14. package/dist-esm/src/credentials/authorizationCodeCredentialOptions.js +1 -1
  15. package/dist-esm/src/credentials/authorizationCodeCredentialOptions.js.map +1 -1
  16. package/dist-esm/src/credentials/azureApplicationCredential.browser.js +1 -1
  17. package/dist-esm/src/credentials/azureApplicationCredential.browser.js.map +1 -1
  18. package/dist-esm/src/credentials/azureApplicationCredential.js +1 -1
  19. package/dist-esm/src/credentials/azureApplicationCredential.js.map +1 -1
  20. package/dist-esm/src/credentials/azureApplicationCredentialOptions.js +1 -1
  21. package/dist-esm/src/credentials/azureApplicationCredentialOptions.js.map +1 -1
  22. package/dist-esm/src/credentials/azureCliCredential.browser.js +1 -1
  23. package/dist-esm/src/credentials/azureCliCredential.browser.js.map +1 -1
  24. package/dist-esm/src/credentials/azureCliCredential.js +1 -1
  25. package/dist-esm/src/credentials/azureCliCredential.js.map +1 -1
  26. package/dist-esm/src/credentials/azureCliCredentialOptions.js +1 -1
  27. package/dist-esm/src/credentials/azureCliCredentialOptions.js.map +1 -1
  28. package/dist-esm/src/credentials/azureDeveloperCliCredential.browser.js +1 -1
  29. package/dist-esm/src/credentials/azureDeveloperCliCredential.browser.js.map +1 -1
  30. package/dist-esm/src/credentials/azureDeveloperCliCredential.js +1 -1
  31. package/dist-esm/src/credentials/azureDeveloperCliCredential.js.map +1 -1
  32. package/dist-esm/src/credentials/azureDeveloperCliCredentialOptions.js +1 -1
  33. package/dist-esm/src/credentials/azureDeveloperCliCredentialOptions.js.map +1 -1
  34. package/dist-esm/src/credentials/azurePipelinesCredential.browser.js +1 -1
  35. package/dist-esm/src/credentials/azurePipelinesCredential.browser.js.map +1 -1
  36. package/dist-esm/src/credentials/azurePipelinesCredential.js +51 -27
  37. package/dist-esm/src/credentials/azurePipelinesCredential.js.map +1 -1
  38. package/dist-esm/src/credentials/azurePipelinesCredentialOptions.js +1 -1
  39. package/dist-esm/src/credentials/azurePipelinesCredentialOptions.js.map +1 -1
  40. package/dist-esm/src/credentials/azurePowerShellCredential.browser.js +1 -1
  41. package/dist-esm/src/credentials/azurePowerShellCredential.browser.js.map +1 -1
  42. package/dist-esm/src/credentials/azurePowerShellCredential.js +64 -20
  43. package/dist-esm/src/credentials/azurePowerShellCredential.js.map +1 -1
  44. package/dist-esm/src/credentials/azurePowerShellCredentialOptions.js +1 -1
  45. package/dist-esm/src/credentials/azurePowerShellCredentialOptions.js.map +1 -1
  46. package/dist-esm/src/credentials/brokerAuthOptions.js.map +1 -1
  47. package/dist-esm/src/credentials/browserCustomizationOptions.js +1 -1
  48. package/dist-esm/src/credentials/browserCustomizationOptions.js.map +1 -1
  49. package/dist-esm/src/credentials/chainedTokenCredential.js +1 -1
  50. package/dist-esm/src/credentials/chainedTokenCredential.js.map +1 -1
  51. package/dist-esm/src/credentials/clientAssertionCredential.browser.js +1 -1
  52. package/dist-esm/src/credentials/clientAssertionCredential.browser.js.map +1 -1
  53. package/dist-esm/src/credentials/clientAssertionCredential.js +10 -3
  54. package/dist-esm/src/credentials/clientAssertionCredential.js.map +1 -1
  55. package/dist-esm/src/credentials/clientAssertionCredentialOptions.js +1 -1
  56. package/dist-esm/src/credentials/clientAssertionCredentialOptions.js.map +1 -1
  57. package/dist-esm/src/credentials/clientCertificateCredential.browser.js +1 -1
  58. package/dist-esm/src/credentials/clientCertificateCredential.browser.js.map +1 -1
  59. package/dist-esm/src/credentials/clientCertificateCredential.js +36 -28
  60. package/dist-esm/src/credentials/clientCertificateCredential.js.map +1 -1
  61. package/dist-esm/src/credentials/clientCertificateCredentialOptions.js +1 -1
  62. package/dist-esm/src/credentials/clientCertificateCredentialOptions.js.map +1 -1
  63. package/dist-esm/src/credentials/clientSecretCredential.browser.js +1 -1
  64. package/dist-esm/src/credentials/clientSecretCredential.browser.js.map +1 -1
  65. package/dist-esm/src/credentials/clientSecretCredential.js +10 -3
  66. package/dist-esm/src/credentials/clientSecretCredential.js.map +1 -1
  67. package/dist-esm/src/credentials/clientSecretCredentialOptions.js +1 -1
  68. package/dist-esm/src/credentials/clientSecretCredentialOptions.js.map +1 -1
  69. package/dist-esm/src/credentials/credentialPersistenceOptions.js +1 -1
  70. package/dist-esm/src/credentials/credentialPersistenceOptions.js.map +1 -1
  71. package/dist-esm/src/credentials/defaultAzureCredential.browser.js +1 -1
  72. package/dist-esm/src/credentials/defaultAzureCredential.browser.js.map +1 -1
  73. package/dist-esm/src/credentials/defaultAzureCredential.js +1 -1
  74. package/dist-esm/src/credentials/defaultAzureCredential.js.map +1 -1
  75. package/dist-esm/src/credentials/defaultAzureCredentialOptions.js +1 -1
  76. package/dist-esm/src/credentials/defaultAzureCredentialOptions.js.map +1 -1
  77. package/dist-esm/src/credentials/deviceCodeCredential.browser.js +1 -1
  78. package/dist-esm/src/credentials/deviceCodeCredential.browser.js.map +1 -1
  79. package/dist-esm/src/credentials/deviceCodeCredential.js +2 -2
  80. package/dist-esm/src/credentials/deviceCodeCredential.js.map +1 -1
  81. package/dist-esm/src/credentials/deviceCodeCredentialOptions.js +1 -1
  82. package/dist-esm/src/credentials/deviceCodeCredentialOptions.js.map +1 -1
  83. package/dist-esm/src/credentials/environmentCredential.browser.js +1 -1
  84. package/dist-esm/src/credentials/environmentCredential.browser.js.map +1 -1
  85. package/dist-esm/src/credentials/environmentCredential.js +12 -2
  86. package/dist-esm/src/credentials/environmentCredential.js.map +1 -1
  87. package/dist-esm/src/credentials/environmentCredentialOptions.js +1 -1
  88. package/dist-esm/src/credentials/environmentCredentialOptions.js.map +1 -1
  89. package/dist-esm/src/credentials/interactiveBrowserCredential.browser.js +1 -1
  90. package/dist-esm/src/credentials/interactiveBrowserCredential.browser.js.map +1 -1
  91. package/dist-esm/src/credentials/interactiveBrowserCredential.js +2 -2
  92. package/dist-esm/src/credentials/interactiveBrowserCredential.js.map +1 -1
  93. package/dist-esm/src/credentials/interactiveBrowserCredentialOptions.js +1 -1
  94. package/dist-esm/src/credentials/interactiveBrowserCredentialOptions.js.map +1 -1
  95. package/dist-esm/src/credentials/interactiveCredentialOptions.js +1 -1
  96. package/dist-esm/src/credentials/interactiveCredentialOptions.js.map +1 -1
  97. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2017.js +1 -1
  98. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2017.js.map +1 -1
  99. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2019.js +1 -1
  100. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2019.js.map +1 -1
  101. package/dist-esm/src/credentials/managedIdentityCredential/arcMsi.js +1 -1
  102. package/dist-esm/src/credentials/managedIdentityCredential/arcMsi.js.map +1 -1
  103. package/dist-esm/src/credentials/managedIdentityCredential/cloudShellMsi.js +1 -1
  104. package/dist-esm/src/credentials/managedIdentityCredential/cloudShellMsi.js.map +1 -1
  105. package/dist-esm/src/credentials/managedIdentityCredential/constants.js +1 -1
  106. package/dist-esm/src/credentials/managedIdentityCredential/constants.js.map +1 -1
  107. package/dist-esm/src/credentials/managedIdentityCredential/fabricMsi.js +1 -1
  108. package/dist-esm/src/credentials/managedIdentityCredential/fabricMsi.js.map +1 -1
  109. package/dist-esm/src/credentials/managedIdentityCredential/imdsMsi.js +1 -1
  110. package/dist-esm/src/credentials/managedIdentityCredential/imdsMsi.js.map +1 -1
  111. package/dist-esm/src/credentials/managedIdentityCredential/imdsRetryPolicy.js +6 -10
  112. package/dist-esm/src/credentials/managedIdentityCredential/imdsRetryPolicy.js.map +1 -1
  113. package/dist-esm/src/credentials/managedIdentityCredential/index.browser.js +1 -1
  114. package/dist-esm/src/credentials/managedIdentityCredential/index.browser.js.map +1 -1
  115. package/dist-esm/src/credentials/managedIdentityCredential/index.js +1 -1
  116. package/dist-esm/src/credentials/managedIdentityCredential/index.js.map +1 -1
  117. package/dist-esm/src/credentials/managedIdentityCredential/legacyMsiProvider.js +7 -1
  118. package/dist-esm/src/credentials/managedIdentityCredential/legacyMsiProvider.js.map +1 -1
  119. package/dist-esm/src/credentials/managedIdentityCredential/models.js +1 -1
  120. package/dist-esm/src/credentials/managedIdentityCredential/models.js.map +1 -1
  121. package/dist-esm/src/credentials/managedIdentityCredential/msalMsiProvider.js +25 -8
  122. package/dist-esm/src/credentials/managedIdentityCredential/msalMsiProvider.js.map +1 -1
  123. package/dist-esm/src/credentials/managedIdentityCredential/tokenExchangeMsi.js +1 -1
  124. package/dist-esm/src/credentials/managedIdentityCredential/tokenExchangeMsi.js.map +1 -1
  125. package/dist-esm/src/credentials/managedIdentityCredential/utils.js +26 -1
  126. package/dist-esm/src/credentials/managedIdentityCredential/utils.js.map +1 -1
  127. package/dist-esm/src/credentials/multiTenantTokenCredentialOptions.js +1 -1
  128. package/dist-esm/src/credentials/multiTenantTokenCredentialOptions.js.map +1 -1
  129. package/dist-esm/src/credentials/onBehalfOfCredential.browser.js +1 -1
  130. package/dist-esm/src/credentials/onBehalfOfCredential.browser.js.map +1 -1
  131. package/dist-esm/src/credentials/onBehalfOfCredential.js +17 -10
  132. package/dist-esm/src/credentials/onBehalfOfCredential.js.map +1 -1
  133. package/dist-esm/src/credentials/onBehalfOfCredentialOptions.js +1 -1
  134. package/dist-esm/src/credentials/onBehalfOfCredentialOptions.js.map +1 -1
  135. package/dist-esm/src/credentials/usernamePasswordCredential.browser.js +1 -1
  136. package/dist-esm/src/credentials/usernamePasswordCredential.browser.js.map +1 -1
  137. package/dist-esm/src/credentials/usernamePasswordCredential.js +14 -4
  138. package/dist-esm/src/credentials/usernamePasswordCredential.js.map +1 -1
  139. package/dist-esm/src/credentials/usernamePasswordCredentialOptions.js +1 -1
  140. package/dist-esm/src/credentials/usernamePasswordCredentialOptions.js.map +1 -1
  141. package/dist-esm/src/credentials/visualStudioCodeCredential.browser.js +1 -1
  142. package/dist-esm/src/credentials/visualStudioCodeCredential.browser.js.map +1 -1
  143. package/dist-esm/src/credentials/visualStudioCodeCredential.js +1 -1
  144. package/dist-esm/src/credentials/visualStudioCodeCredential.js.map +1 -1
  145. package/dist-esm/src/credentials/visualStudioCodeCredentialOptions.js +1 -1
  146. package/dist-esm/src/credentials/visualStudioCodeCredentialOptions.js.map +1 -1
  147. package/dist-esm/src/credentials/visualStudioCodeCredentialPlugin.js +1 -1
  148. package/dist-esm/src/credentials/visualStudioCodeCredentialPlugin.js.map +1 -1
  149. package/dist-esm/src/credentials/workloadIdentityCredential.browser.js +1 -1
  150. package/dist-esm/src/credentials/workloadIdentityCredential.browser.js.map +1 -1
  151. package/dist-esm/src/credentials/workloadIdentityCredential.js +17 -7
  152. package/dist-esm/src/credentials/workloadIdentityCredential.js.map +1 -1
  153. package/dist-esm/src/credentials/workloadIdentityCredentialOptions.js +1 -1
  154. package/dist-esm/src/credentials/workloadIdentityCredentialOptions.js.map +1 -1
  155. package/dist-esm/src/errors.js +13 -9
  156. package/dist-esm/src/errors.js.map +1 -1
  157. package/dist-esm/src/index.js +1 -1
  158. package/dist-esm/src/index.js.map +1 -1
  159. package/dist-esm/src/msal/browserFlows/flows.js +4 -0
  160. package/dist-esm/src/msal/browserFlows/flows.js.map +1 -0
  161. package/dist-esm/src/msal/browserFlows/msalAuthCode.js +1 -1
  162. package/dist-esm/src/msal/browserFlows/msalAuthCode.js.map +1 -1
  163. package/dist-esm/src/msal/browserFlows/msalBrowserCommon.js +3 -1
  164. package/dist-esm/src/msal/browserFlows/msalBrowserCommon.js.map +1 -1
  165. package/dist-esm/src/msal/credentials.js +1 -1
  166. package/dist-esm/src/msal/credentials.js.map +1 -1
  167. package/dist-esm/src/msal/msal.browser.js +1 -1
  168. package/dist-esm/src/msal/msal.browser.js.map +1 -1
  169. package/dist-esm/src/msal/msal.js +1 -1
  170. package/dist-esm/src/msal/msal.js.map +1 -1
  171. package/dist-esm/src/msal/nodeFlows/brokerOptions.js.map +1 -1
  172. package/dist-esm/src/msal/nodeFlows/msalClient.js +25 -9
  173. package/dist-esm/src/msal/nodeFlows/msalClient.js.map +1 -1
  174. package/dist-esm/src/msal/nodeFlows/msalPlugins.js +1 -1
  175. package/dist-esm/src/msal/nodeFlows/msalPlugins.js.map +1 -1
  176. package/dist-esm/src/msal/nodeFlows/tokenCachePersistenceOptions.js +1 -1
  177. package/dist-esm/src/msal/nodeFlows/tokenCachePersistenceOptions.js.map +1 -1
  178. package/dist-esm/src/msal/types.js +1 -1
  179. package/dist-esm/src/msal/types.js.map +1 -1
  180. package/dist-esm/src/msal/utils.js +15 -2
  181. package/dist-esm/src/msal/utils.js.map +1 -1
  182. package/dist-esm/src/plugins/consumer.browser.js +1 -1
  183. package/dist-esm/src/plugins/consumer.browser.js.map +1 -1
  184. package/dist-esm/src/plugins/consumer.js +1 -1
  185. package/dist-esm/src/plugins/consumer.js.map +1 -1
  186. package/dist-esm/src/plugins/provider.js +1 -1
  187. package/dist-esm/src/plugins/provider.js.map +1 -1
  188. package/dist-esm/src/regionalAuthority.js +1 -1
  189. package/dist-esm/src/regionalAuthority.js.map +1 -1
  190. package/dist-esm/src/tokenCredentialOptions.js +1 -1
  191. package/dist-esm/src/tokenCredentialOptions.js.map +1 -1
  192. package/dist-esm/src/tokenProvider.js +1 -1
  193. package/dist-esm/src/tokenProvider.js.map +1 -1
  194. package/dist-esm/src/util/authHostEnv.browser.js +1 -1
  195. package/dist-esm/src/util/authHostEnv.browser.js.map +1 -1
  196. package/dist-esm/src/util/identityTokenEndpoint.js +1 -1
  197. package/dist-esm/src/util/identityTokenEndpoint.js.map +1 -1
  198. package/dist-esm/src/util/logging.js +1 -1
  199. package/dist-esm/src/util/logging.js.map +1 -1
  200. package/dist-esm/src/util/processMultiTenantRequest.browser.js +1 -1
  201. package/dist-esm/src/util/processMultiTenantRequest.browser.js.map +1 -1
  202. package/dist-esm/src/util/processMultiTenantRequest.js +1 -1
  203. package/dist-esm/src/util/processMultiTenantRequest.js.map +1 -1
  204. package/dist-esm/src/util/processUtils.js +1 -1
  205. package/dist-esm/src/util/processUtils.js.map +1 -1
  206. package/dist-esm/src/util/scopeUtils.js +1 -1
  207. package/dist-esm/src/util/scopeUtils.js.map +1 -1
  208. package/dist-esm/src/util/tenantIdUtils.js +1 -1
  209. package/dist-esm/src/util/tenantIdUtils.js.map +1 -1
  210. package/dist-esm/src/util/tracing.js +1 -1
  211. package/dist-esm/src/util/tracing.js.map +1 -1
  212. package/package.json +9 -9
  213. package/types/identity.d.ts +47 -11
  214. package/dist-esm/src/msal/flows.js +0 -4
  215. package/dist-esm/src/msal/flows.js.map +0 -1
  216. package/dist-esm/src/msal/nodeFlows/msalAuthorizationCode.js +0 -47
  217. package/dist-esm/src/msal/nodeFlows/msalAuthorizationCode.js.map +0 -1
  218. package/dist-esm/src/msal/nodeFlows/msalClientAssertion.js +0 -42
  219. package/dist-esm/src/msal/nodeFlows/msalClientAssertion.js.map +0 -1
  220. package/dist-esm/src/msal/nodeFlows/msalClientCertificate.js +0 -112
  221. package/dist-esm/src/msal/nodeFlows/msalClientCertificate.js.map +0 -1
  222. package/dist-esm/src/msal/nodeFlows/msalClientSecret.js +0 -33
  223. package/dist-esm/src/msal/nodeFlows/msalClientSecret.js.map +0 -1
  224. package/dist-esm/src/msal/nodeFlows/msalDeviceCode.js +0 -35
  225. package/dist-esm/src/msal/nodeFlows/msalDeviceCode.js.map +0 -1
  226. package/dist-esm/src/msal/nodeFlows/msalNodeCommon.js +0 -323
  227. package/dist-esm/src/msal/nodeFlows/msalNodeCommon.js.map +0 -1
  228. package/dist-esm/src/msal/nodeFlows/msalOnBehalfOf.js +0 -58
  229. package/dist-esm/src/msal/nodeFlows/msalOnBehalfOf.js.map +0 -1
  230. package/dist-esm/src/msal/nodeFlows/msalOpenBrowser.js +0 -113
  231. package/dist-esm/src/msal/nodeFlows/msalOpenBrowser.js.map +0 -1
  232. package/dist-esm/src/msal/nodeFlows/msalUsernamePassword.js +0 -33
  233. package/dist-esm/src/msal/nodeFlows/msalUsernamePassword.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"imdsMsi.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/imdsMsi.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAGL,iBAAiB,EACjB,qBAAqB,GACtB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEzE,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAEnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,MAAM,OAAO,GAAG,kCAAkC,CAAC;AACnD,MAAM,MAAM,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAEzC;;GAEG;AACH,SAAS,qBAAqB,CAC5B,MAAyB,EACzB,QAAiB,EACjB,UAAmB,EACnB,OAGC;;IAED,MAAM,QAAQ,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAC;IAC7C,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,MAAM,IAAI,KAAK,CAAC,GAAG,O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,CAAC,cAAc,CAAC;QAC7D,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,aAAa,CAAC,WAAW,CAAC,UAAU,EAAE,OAAO,EAAE,EAAE,CAAC;YAChF,IAAI,CAAC;gBACH,MAAM,OAAO,GAAG,qBAAqB,+BACnC,WAAW,EAAE,eAAe,CAAC,WAAW,IACrC,qBAAqB,CAAC,MAAM,EAAE,QAAQ,EAAE,UAAU,CAAC,KACtD,uBAAuB,EAAE,IAAI,IAC7B,CAAC;gBACH,MAAM,aAAa,GAAG,MAAM,cAAc,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;gBAErE,OAAO,CAAC,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC;YAC9D,CAAC;YAAC,OAAO,KAAU,EAAE,CAAC;gBACpB,IAAI,KAAK,CAAC,UAAU,KAAK,GAAG,EAAE,CAAC;oBAC7B,MAAM,KAAK,CAAC,aAAa,CAAC,CAAC;oBAC3B,aAAa,IAAI,aAAa,CAAC,WAAW,CAAC,iBAAiB,CAAC;oBAC7D,SAAS;gBACX,CAAC;gBACD,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC;QAED,MAAM,IAAI,mBAAmB,CAC3B,GAAG,EACH,GAAG,OAAO,yCAAyC,aAAa,CAAC,WAAW,CAAC,UAAU,WAAW,CACnG,CAAC;IACJ,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { MSI, MSIConfiguration, MSIToken } from \"./models\";\nimport {\n PipelineRequestOptions,\n PipelineResponse,\n createHttpHeaders,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { delay, isError } from \"@azure/core-util\";\nimport { imdsApiVersion, imdsEndpointPath, imdsHost } from \"./constants\";\n\nimport { AuthenticationError } from \"../../errors\";\nimport { GetTokenOptions } from \"@azure/core-auth\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { mapScopesToResource } from \"./utils\";\nimport { tracingClient } from \"../../util/tracing\";\n\nconst msiName = \"ManagedIdentityCredential - IMDS\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Generates the options used on the request for an access token.\n */\nfunction prepareRequestOptions(\n scopes: string | string[],\n clientId?: string,\n resourceId?: string,\n options?: {\n skipQuery?: boolean;\n skipMetadataHeader?: boolean;\n },\n): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const { skipQuery, skipMetadataHeader } = options || {};\n let query = \"\";\n\n // Pod Identity will try to process this request even if the Metadata header is missing.\n // We can exclude the request query to ensure no IMDS endpoint tries to process the ping request.\n if (!skipQuery) {\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": imdsApiVersion,\n };\n if (clientId) {\n queryParameters.client_id = clientId;\n }\n if (resourceId) {\n queryParameters.msi_res_id = resourceId;\n }\n const params = new URLSearchParams(queryParameters);\n query = `?${params.toString()}`;\n }\n\n const url = new URL(imdsEndpointPath, process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST ?? imdsHost);\n\n const rawHeaders: Record<string, string> = {\n Accept: \"application/json\",\n Metadata: \"true\",\n };\n\n // Remove the Metadata header to invoke a request error from some IMDS endpoints.\n if (skipMetadataHeader) {\n delete rawHeaders.Metadata;\n }\n\n return {\n // In this case, the `?` should be added in the \"query\" variable `skipQuery` is not set.\n url: `${url}${query}`,\n method: \"GET\",\n headers: createHttpHeaders(rawHeaders),\n };\n}\n\n/**\n * Defines how to determine whether the Azure IMDS MSI is available, and also how to retrieve a token from the Azure IMDS MSI.\n */\nexport const imdsMsi: MSI = {\n name: \"imdsMsi\",\n async isAvailable({\n scopes,\n identityClient,\n clientId,\n resourceId,\n getTokenOptions = {},\n }): Promise<boolean> {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);\n return false;\n }\n\n // if the PodIdentityEndpoint environment variable was set no need to probe the endpoint, it can be assumed to exist\n if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {\n return true;\n }\n\n if (!identityClient) {\n throw new Error(\"Missing IdentityClient\");\n }\n\n const requestOptions = prepareRequestOptions(resource, clientId, resourceId, {\n skipMetadataHeader: true,\n skipQuery: true,\n });\n\n return tracingClient.withSpan(\n \"ManagedIdentityCredential-pingImdsEndpoint\",\n getTokenOptions,\n async (options) => {\n requestOptions.tracingOptions = options.tracingOptions;\n\n // Create a request with a timeout since we expect that\n // not having a \"Metadata\" header should cause an error to be\n // returned quickly from the endpoint, proving its availability.\n const request = createPipelineRequest(requestOptions);\n\n // Default to 1000 if the default of 0 is used.\n // Negative values can still be used to disable the timeout.\n request.timeout = options.requestOptions?.timeout || 1000;\n\n // This MSI uses the imdsEndpoint to get the token, which only uses http://\n request.allowInsecureConnection = true;\n let response: PipelineResponse;\n try {\n logger.info(`${msiName}: Pinging the Azure IMDS endpoint`);\n response = await identityClient.sendRequest(request);\n } catch (err: unknown) {\n // If the request failed, or Node.js was unable to establish a connection,\n // or the host was down, we'll assume the IMDS endpoint isn't available.\n if (isError(err)) {\n logger.verbose(`${msiName}: Caught error ${err.name}: ${err.message}`);\n }\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`);\n return false;\n }\n if (response.status === 403) {\n if (response.bodyAsText?.includes(\"unreachable\")) {\n logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`);\n logger.info(`${msiName}: ${response.bodyAsText}`);\n return false;\n }\n }\n // If we received any response, the endpoint is available\n logger.info(`${msiName}: The Azure IMDS endpoint is available`);\n return true;\n },\n );\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {},\n ): Promise<MSIToken | null> {\n const { identityClient, scopes, clientId, resourceId } = configuration;\n\n if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {\n logger.info(\n `${msiName}: Using the Azure IMDS endpoint coming from the environment variable AZURE_POD_IDENTITY_AUTHORITY_HOST=${process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST}.`,\n );\n } else {\n logger.info(`${msiName}: Using the default Azure IMDS endpoint ${imdsHost}.`);\n }\n\n let nextDelayInMs = configuration.retryConfig.startDelayInMs;\n for (let retries = 0; retries < configuration.retryConfig.maxRetries; retries++) {\n try {\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId, resourceId),\n allowInsecureConnection: true,\n });\n const tokenResponse = await identityClient.sendTokenRequest(request);\n\n return (tokenResponse && tokenResponse.accessToken) || null;\n } catch (error: any) {\n if (error.statusCode === 404) {\n await delay(nextDelayInMs);\n nextDelayInMs *= configuration.retryConfig.intervalIncrement;\n continue;\n }\n throw error;\n }\n }\n\n throw new AuthenticationError(\n 404,\n `${msiName}: Failed to retrieve IMDS token after ${configuration.retryConfig.maxRetries} retries.`,\n );\n },\n};\n"]}
1
+ {"version":3,"file":"imdsMsi.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/imdsMsi.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAGL,iBAAiB,EACjB,qBAAqB,GACtB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEzE,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAEnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,MAAM,OAAO,GAAG,kCAAkC,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SIToken } from \"./models\";\nimport {\n PipelineRequestOptions,\n PipelineResponse,\n createHttpHeaders,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { delay, isError } from \"@azure/core-util\";\nimport { imdsApiVersion, imdsEndpointPath, imdsHost } from \"./constants\";\n\nimport { AuthenticationError } from \"../../errors\";\nimport { GetTokenOptions } from \"@azure/core-auth\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { mapScopesToResource } from \"./utils\";\nimport { tracingClient } from \"../../util/tracing\";\n\nconst msiName = \"ManagedIdentityCredential - IMDS\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Generates the options used on the request for an access token.\n */\nfunction prepareRequestOptions(\n scopes: string | string[],\n clientId?: string,\n resourceId?: string,\n options?: {\n skipQuery?: boolean;\n skipMetadataHeader?: boolean;\n },\n): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const { skipQuery, skipMetadataHeader } = options || {};\n let query = \"\";\n\n // Pod Identity will try to process this request even if the Metadata header is missing.\n // We can exclude the request query to ensure no IMDS endpoint tries to process the ping request.\n if (!skipQuery) {\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": imdsApiVersion,\n };\n if (clientId) {\n queryParameters.client_id = clientId;\n }\n if (resourceId) {\n queryParameters.msi_res_id = resourceId;\n }\n const params = new URLSearchParams(queryParameters);\n query = `?${params.toString()}`;\n }\n\n const url = new URL(imdsEndpointPath, process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST ?? imdsHost);\n\n const rawHeaders: Record<string, string> = {\n Accept: \"application/json\",\n Metadata: \"true\",\n };\n\n // Remove the Metadata header to invoke a request error from some IMDS endpoints.\n if (skipMetadataHeader) {\n delete rawHeaders.Metadata;\n }\n\n return {\n // In this case, the `?` should be added in the \"query\" variable `skipQuery` is not set.\n url: `${url}${query}`,\n method: \"GET\",\n headers: createHttpHeaders(rawHeaders),\n };\n}\n\n/**\n * Defines how to determine whether the Azure IMDS MSI is available, and also how to retrieve a token from the Azure IMDS MSI.\n */\nexport const imdsMsi: MSI = {\n name: \"imdsMsi\",\n async isAvailable({\n scopes,\n identityClient,\n clientId,\n resourceId,\n getTokenOptions = {},\n }): Promise<boolean> {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);\n return false;\n }\n\n // if the PodIdentityEndpoint environment variable was set no need to probe the endpoint, it can be assumed to exist\n if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {\n return true;\n }\n\n if (!identityClient) {\n throw new Error(\"Missing IdentityClient\");\n }\n\n const requestOptions = prepareRequestOptions(resource, clientId, resourceId, {\n skipMetadataHeader: true,\n skipQuery: true,\n });\n\n return tracingClient.withSpan(\n \"ManagedIdentityCredential-pingImdsEndpoint\",\n getTokenOptions,\n async (options) => {\n requestOptions.tracingOptions = options.tracingOptions;\n\n // Create a request with a timeout since we expect that\n // not having a \"Metadata\" header should cause an error to be\n // returned quickly from the endpoint, proving its availability.\n const request = createPipelineRequest(requestOptions);\n\n // Default to 1000 if the default of 0 is used.\n // Negative values can still be used to disable the timeout.\n request.timeout = options.requestOptions?.timeout || 1000;\n\n // This MSI uses the imdsEndpoint to get the token, which only uses http://\n request.allowInsecureConnection = true;\n let response: PipelineResponse;\n try {\n logger.info(`${msiName}: Pinging the Azure IMDS endpoint`);\n response = await identityClient.sendRequest(request);\n } catch (err: unknown) {\n // If the request failed, or Node.js was unable to establish a connection,\n // or the host was down, we'll assume the IMDS endpoint isn't available.\n if (isError(err)) {\n logger.verbose(`${msiName}: Caught error ${err.name}: ${err.message}`);\n }\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`);\n return false;\n }\n if (response.status === 403) {\n if (response.bodyAsText?.includes(\"unreachable\")) {\n logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`);\n logger.info(`${msiName}: ${response.bodyAsText}`);\n return false;\n }\n }\n // If we received any response, the endpoint is available\n logger.info(`${msiName}: The Azure IMDS endpoint is available`);\n return true;\n },\n );\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {},\n ): Promise<MSIToken | null> {\n const { identityClient, scopes, clientId, resourceId } = configuration;\n\n if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {\n logger.info(\n `${msiName}: Using the Azure IMDS endpoint coming from the environment variable AZURE_POD_IDENTITY_AUTHORITY_HOST=${process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST}.`,\n );\n } else {\n logger.info(`${msiName}: Using the default Azure IMDS endpoint ${imdsHost}.`);\n }\n\n let nextDelayInMs = configuration.retryConfig.startDelayInMs;\n for (let retries = 0; retries < configuration.retryConfig.maxRetries; retries++) {\n try {\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId, resourceId),\n allowInsecureConnection: true,\n });\n const tokenResponse = await identityClient.sendTokenRequest(request);\n\n return (tokenResponse && tokenResponse.accessToken) || null;\n } catch (error: any) {\n if (error.statusCode === 404) {\n await delay(nextDelayInMs);\n nextDelayInMs *= configuration.retryConfig.intervalIncrement;\n continue;\n }\n throw error;\n }\n }\n\n throw new AuthenticationError(\n 404,\n `${msiName}: Failed to retrieve IMDS token after ${configuration.retryConfig.maxRetries} retries.`,\n );\n },\n};\n"]}
@@ -1,7 +1,7 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  import { retryPolicy } from "@azure/core-rest-pipeline";
4
- import { getRandomIntegerInclusive } from "@azure/core-util";
4
+ import { calculateRetryDelay } from "@azure/core-util";
5
5
  // Matches the default retry configuration in expontentialRetryStrategy.ts
6
6
  const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64;
7
7
  /**
@@ -20,14 +20,10 @@ export function imdsRetryPolicy(msiRetryConfig) {
20
20
  if ((response === null || response === void 0 ? void 0 : response.status) !== 404) {
21
21
  return { skipStrategy: true };
22
22
  }
23
- // Exponentially increase the delay each time
24
- const exponentialDelay = msiRetryConfig.startDelayInMs * Math.pow(2, retryCount);
25
- // Don't let the delay exceed the maximum
26
- const clampedExponentialDelay = Math.min(DEFAULT_CLIENT_MAX_RETRY_INTERVAL, exponentialDelay);
27
- // Allow the final value to have some "jitter" (within 50% of the delay size) so
28
- // that retries across multiple clients don't occur simultaneously.
29
- const retryAfterInMs = clampedExponentialDelay / 2 + getRandomIntegerInclusive(0, clampedExponentialDelay / 2);
30
- return { retryAfterInMs };
23
+ return calculateRetryDelay(retryCount, {
24
+ retryDelayInMs: msiRetryConfig.startDelayInMs,
25
+ maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL,
26
+ });
31
27
  },
32
28
  },
33
29
  ], {
@@ -1 +1 @@
1
- {"version":3,"file":"imdsRetryPolicy.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/imdsRetryPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAkB,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAGxE,OAAO,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAE7D,0EAA0E;AAC1E,MAAM,iCAAiC,GAAG,IAAI,GAAG,EAAE,CAAC;AAEpD;;;;;;;GAOG;AACH,MAAM,UAAU,eAAe,CAAC,cAA+C;IAC7E,OAAO,WAAW,CAChB;QACE;YACE,IAAI,EAAE,iBAAiB;YACvB,KAAK,EAAE,CAAC,EAAE,UAAU,EAAE,QAAQ,EAAE,EAAE,EAAE;gBAClC,IAAI,CAAA,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,MAAM,MAAK,GAAG,EAAE,CAAC;oBAC7B,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC;gBAChC,CAAC;gBAED,6CAA6C;gBAC7C,MAAM,gBAAgB,GAAG,cAAc,CAAC,cAAc,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC;gBAEjF,yCAAyC;gBACzC,MAAM,uBAAuB,GAAG,IAAI,CAAC,GAAG,CACtC,iCAAiC,EACjC,gBAAgB,CACjB,CAAC;gBAEF,gFAAgF;gBAChF,mEAAmE;gBACnE,MAAM,cAAc,GAClB,uBAAuB,GAAG,CAAC,GAAG,yBAAyB,CAAC,CAAC,EAAE,uBAAuB,GAAG,CAAC,CAAC,CAAC;gBAE1F,OAAO,EAAE,cAAc,EAAE,CAAC;YAC5B,CAAC;SACF;KACF,EACD;QACE,UAAU,EAAE,cAAc,CAAC,UAAU;KACtC,CACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelinePolicy, retryPolicy } from \"@azure/core-rest-pipeline\";\n\nimport { MSIConfiguration } from \"./models\";\nimport { getRandomIntegerInclusive } from \"@azure/core-util\";\n\n// Matches the default retry configuration in expontentialRetryStrategy.ts\nconst DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64;\n\n/**\n * An additional policy that retries on 404 errors. The default retry policy does not retry on\n * 404s, but the IMDS endpoint can return 404s when the token is not yet available. This policy\n * will retry on 404s with an exponential backoff.\n *\n * @param msiRetryConfig - The retry configuration for the MSI credential.\n * @returns - The policy that will retry on 404s.\n */\nexport function imdsRetryPolicy(msiRetryConfig: MSIConfiguration[\"retryConfig\"]): PipelinePolicy {\n return retryPolicy(\n [\n {\n name: \"imdsRetryPolicy\",\n retry: ({ retryCount, response }) => {\n if (response?.status !== 404) {\n return { skipStrategy: true };\n }\n\n // Exponentially increase the delay each time\n const exponentialDelay = msiRetryConfig.startDelayInMs * Math.pow(2, retryCount);\n\n // Don't let the delay exceed the maximum\n const clampedExponentialDelay = Math.min(\n DEFAULT_CLIENT_MAX_RETRY_INTERVAL,\n exponentialDelay,\n );\n\n // Allow the final value to have some \"jitter\" (within 50% of the delay size) so\n // that retries across multiple clients don't occur simultaneously.\n const retryAfterInMs =\n clampedExponentialDelay / 2 + getRandomIntegerInclusive(0, clampedExponentialDelay / 2);\n\n return { retryAfterInMs };\n },\n },\n ],\n {\n maxRetries: msiRetryConfig.maxRetries,\n },\n );\n}\n"]}
1
+ {"version":3,"file":"imdsRetryPolicy.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/imdsRetryPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAkB,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAGxE,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAEvD,0EAA0E;AAC1E,MAAM,iCAAiC,GAAG,IAAI,GAAG,EAAE,CAAC;AAEpD;;;;;;;GAOG;AACH,MAAM,UAAU,eAAe,CAAC,cAA+C;IAC7E,OAAO,WAAW,CAChB;QACE;YACE,IAAI,EAAE,iBAAiB;YACvB,KAAK,EAAE,CAAC,EAAE,UAAU,EAAE,QAAQ,EAAE,EAAE,EAAE;gBAClC,IAAI,CAAA,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,MAAM,MAAK,GAAG,EAAE,CAAC;oBAC7B,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC;gBAChC,CAAC;gBAED,OAAO,mBAAmB,CAAC,UAAU,EAAE;oBACrC,cAAc,EAAE,cAAc,CAAC,cAAc;oBAC7C,iBAAiB,EAAE,iCAAiC;iBACrD,CAAC,CAAC;YACL,CAAC;SACF;KACF,EACD;QACE,UAAU,EAAE,cAAc,CAAC,UAAU;KACtC,CACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { PipelinePolicy, retryPolicy } from \"@azure/core-rest-pipeline\";\n\nimport { MSIConfiguration } from \"./models\";\nimport { calculateRetryDelay } from \"@azure/core-util\";\n\n// Matches the default retry configuration in expontentialRetryStrategy.ts\nconst DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64;\n\n/**\n * An additional policy that retries on 404 errors. The default retry policy does not retry on\n * 404s, but the IMDS endpoint can return 404s when the token is not yet available. This policy\n * will retry on 404s with an exponential backoff.\n *\n * @param msiRetryConfig - The retry configuration for the MSI credential.\n * @returns - The policy that will retry on 404s.\n */\nexport function imdsRetryPolicy(msiRetryConfig: MSIConfiguration[\"retryConfig\"]): PipelinePolicy {\n return retryPolicy(\n [\n {\n name: \"imdsRetryPolicy\",\n retry: ({ retryCount, response }) => {\n if (response?.status !== 404) {\n return { skipStrategy: true };\n }\n\n return calculateRetryDelay(retryCount, {\n retryDelayInMs: msiRetryConfig.startDelayInMs,\n maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL,\n });\n },\n },\n ],\n {\n maxRetries: msiRetryConfig.maxRetries,\n },\n );\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  import { credentialLogger, formatError } from "../../util/logging";
4
4
  const BrowserNotSupportedError = new Error("ManagedIdentityCredential is not supported in the browser.");
5
5
  const logger = credentialLogger("ManagedIdentityCredential");
@@ -1 +1 @@
1
- {"version":3,"file":"index.browser.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/index.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEnE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CACxC,4DAA4D,CAC7D,CAAC;AACF,MAAM,MAAM,GAAG,gBAAgB,CAAC,2BAA2B,CAAC,CAAC;AAE7D,MAAM,OAAO,yBAAyB;IAGpC;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAEM,KAAK,CAAC,QAAQ;QACnB,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, TokenCredential } from \"@azure/core-auth\";\n\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { credentialLogger, formatError } from \"../../util/logging\";\n\nconst BrowserNotSupportedError = new Error(\n \"ManagedIdentityCredential is not supported in the browser.\",\n);\nconst logger = credentialLogger(\"ManagedIdentityCredential\");\n\nexport class ManagedIdentityCredential implements TokenCredential {\n constructor(clientId: string, options?: TokenCredentialOptions);\n constructor(options?: TokenCredentialOptions);\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n public async getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}
1
+ {"version":3,"file":"index.browser.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/index.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEnE,MAAM,wBAAwB,GAAG,IAAI,KAAK,CACxC,4DAA4D,CAC7D,CAAC;AACF,MAAM,MAAM,GAAG,gBAAgB,CAAC,2BAA2B,CAAC,CAAC;AAE7D,MAAM,OAAO,yBAAyB;IAGpC;QACE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QACvD,MAAM,wBAAwB,CAAC;IACjC,CAAC;IAEM,KAAK,CAAC,QAAQ;QACnB,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAChE,MAAM,wBAAwB,CAAC;IACjC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, TokenCredential } from \"@azure/core-auth\";\n\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { credentialLogger, formatError } from \"../../util/logging\";\n\nconst BrowserNotSupportedError = new Error(\n \"ManagedIdentityCredential is not supported in the browser.\",\n);\nconst logger = credentialLogger(\"ManagedIdentityCredential\");\n\nexport class ManagedIdentityCredential implements TokenCredential {\n constructor(clientId: string, options?: TokenCredentialOptions);\n constructor(options?: TokenCredentialOptions);\n constructor() {\n logger.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n\n public async getToken(): Promise<AccessToken | null> {\n logger.getToken.info(formatError(\"\", BrowserNotSupportedError));\n throw BrowserNotSupportedError;\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  import { MsalMsiProvider } from "./msalMsiProvider";
4
4
  /**
5
5
  * Attempts authentication using a managed identity available at the deployment environment.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAMlC,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AA4BpD;;;;;;;GAOG;AACH,MAAM,OAAO,yBAAyB;IAuBpC;;;OAGG;IACH,YACE,iBAG8C,EAC9C,OAAgC;QAEhC,yDAAyD;QACzD,0HAA0H;QAC1H,yEAAyE;QACzE,+HAA+H;QAC/H,IAAI,CAAC,YAAY,GAAG,IAAI,eAAe,CAAC,iBAAiB,EAAE,OAAO,CAAC,CAAC;IACtE,CAAC;IAED;;;;;;;;OAQG;IACI,KAAK,CAAC,QAAQ,CACnB,MAAyB,EACzB,OAAyB;QAEzB,OAAO,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrD,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\n\nimport { LegacyMsiProvider } from \"./legacyMsiProvider\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { MsalMsiProvider } from \"./msalMsiProvider\";\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `clientId` and not `resourceId`, since only one of both is supported.\n */\nexport interface ManagedIdentityCredentialClientIdOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n}\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `resourceId` and not `clientId`, since only one of both is supported.\n */\nexport interface ManagedIdentityCredentialResourceIdOptions extends TokenCredentialOptions {\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId: string;\n}\n\n/**\n * Attempts authentication using a managed identity available at the deployment environment.\n * This authentication type works in Azure VMs, App Service instances, Azure Functions applications,\n * Azure Kubernetes Services, Azure Service Fabric instances and inside of the Azure Cloud Shell.\n *\n * More information about configuring managed identities can be found here:\n * https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview\n */\nexport class ManagedIdentityCredential implements TokenCredential {\n private implProvider: LegacyMsiProvider | MsalMsiProvider;\n\n /**\n * Creates an instance of ManagedIdentityCredential with the client ID of a\n * user-assigned identity, or app registration (when working with AKS pod-identity).\n *\n * @param clientId - The client ID of the user-assigned identity, or app registration (when working with AKS pod-identity).\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(clientId: string, options?: TokenCredentialOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with clientId\n *\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialClientIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with Resource Id\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialResourceIdOptions);\n /**\n * @internal\n * @hidden\n */\n constructor(\n clientIdOrOptions?:\n | string\n | ManagedIdentityCredentialClientIdOptions\n | ManagedIdentityCredentialResourceIdOptions,\n options?: TokenCredentialOptions,\n ) {\n // https://github.com/Azure/azure-sdk-for-js/issues/30189\n // If needed, you may release a hotfix to quickly rollback to the legacy implementation by changing the following line to:\n // this.implProvider = new LegacyMsiProvider(clientIdOrOptions, options);\n // Once stabilized, you can remove the legacy implementation and inline the msalMsiProvider code here as a drop-in replacement.\n this.implProvider = new MsalMsiProvider(clientIdOrOptions, options);\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions,\n ): Promise<AccessToken> {\n return this.implProvider.getToken(scopes, options);\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAMlC,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAwCpD;;;;;;;GAOG;AACH,MAAM,OAAO,yBAAyB;IA6BpC;;;OAGG;IACH,YACE,iBAI4C,EAC5C,OAAgC;QAEhC,yDAAyD;QACzD,0HAA0H;QAC1H,yEAAyE;QACzE,+HAA+H;QAC/H,IAAI,CAAC,YAAY,GAAG,IAAI,eAAe,CAAC,iBAAiB,EAAE,OAAO,CAAC,CAAC;IACtE,CAAC;IAED;;;;;;;;OAQG;IACI,KAAK,CAAC,QAAQ,CACnB,MAAyB,EACzB,OAAyB;QAEzB,OAAO,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrD,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\n\nimport { LegacyMsiProvider } from \"./legacyMsiProvider\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { MsalMsiProvider } from \"./msalMsiProvider\";\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `clientId` and not `resourceId`, since only one of both is supported.\n */\nexport interface ManagedIdentityCredentialClientIdOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n}\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `resourceId` and not `clientId`, since only one of both is supported.\n */\nexport interface ManagedIdentityCredentialResourceIdOptions extends TokenCredentialOptions {\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId: string;\n}\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `objectId` as a constructor argument.\n */\nexport interface ManagedIdentityCredentialObjectIdOptions extends TokenCredentialOptions {\n /**\n * Allows specifying the object ID of the underlying service principal used to authenticate a user-assigned managed identity.\n * This is an alternative to providing a client ID or resource ID and is not required for system-assigned managed identities.\n */\n objectId: string;\n}\n\n/**\n * Attempts authentication using a managed identity available at the deployment environment.\n * This authentication type works in Azure VMs, App Service instances, Azure Functions applications,\n * Azure Kubernetes Services, Azure Service Fabric instances and inside of the Azure Cloud Shell.\n *\n * More information about configuring managed identities can be found here:\n * https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview\n */\nexport class ManagedIdentityCredential implements TokenCredential {\n private implProvider: LegacyMsiProvider | MsalMsiProvider;\n\n /**\n * Creates an instance of ManagedIdentityCredential with the client ID of a\n * user-assigned identity, or app registration (when working with AKS pod-identity).\n *\n * @param clientId - The client ID of the user-assigned identity, or app registration (when working with AKS pod-identity).\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(clientId: string, options?: TokenCredentialOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with a client ID\n *\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialClientIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with a resource ID\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialResourceIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with an object ID\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialObjectIdOptions);\n /**\n * @internal\n * @hidden\n */\n constructor(\n clientIdOrOptions?:\n | string\n | ManagedIdentityCredentialClientIdOptions\n | ManagedIdentityCredentialResourceIdOptions\n | ManagedIdentityCredentialObjectIdOptions,\n options?: TokenCredentialOptions,\n ) {\n // https://github.com/Azure/azure-sdk-for-js/issues/30189\n // If needed, you may release a hotfix to quickly rollback to the legacy implementation by changing the following line to:\n // this.implProvider = new LegacyMsiProvider(clientIdOrOptions, options);\n // Once stabilized, you can remove the legacy implementation and inline the msalMsiProvider code here as a drop-in replacement.\n this.implProvider = new MsalMsiProvider(clientIdOrOptions, options);\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions,\n ): Promise<AccessToken> {\n return this.implProvider.getToken(scopes, options);\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  import { ConfidentialClientApplication } from "@azure/msal-node";
4
4
  import { AuthenticationError, AuthenticationRequiredError, CredentialUnavailableError, } from "../../errors";
5
5
  import { cloudShellMsi } from "./cloudShellMsi";
@@ -241,11 +241,13 @@ export class LegacyMsiProvider {
241
241
  * If the token received is invalid, an error will be thrown depending on what's missing.
242
242
  */
243
243
  handleResult(scopes, result, getTokenOptions) {
244
+ var _a;
244
245
  this.ensureValidMsalToken(scopes, result, getTokenOptions);
245
246
  logger.getToken.info(formatSuccess(scopes));
246
247
  return {
247
248
  token: result.accessToken,
248
249
  expiresOnTimestamp: result.expiresOn.getTime(),
250
+ refreshAfterTimestamp: (_a = result.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(),
249
251
  };
250
252
  }
251
253
  /**
@@ -282,9 +284,13 @@ export class LegacyMsiProvider {
282
284
  const expiresInSeconds = (resultToken === null || resultToken === void 0 ? void 0 : resultToken.expiresOnTimestamp)
283
285
  ? Math.floor((resultToken.expiresOnTimestamp - Date.now()) / 1000)
284
286
  : 0;
287
+ const refreshInSeconds = (resultToken === null || resultToken === void 0 ? void 0 : resultToken.refreshAfterTimestamp)
288
+ ? Math.floor((resultToken.refreshAfterTimestamp - Date.now()) / 1000)
289
+ : 0;
285
290
  return {
286
291
  accessToken: resultToken === null || resultToken === void 0 ? void 0 : resultToken.token,
287
292
  expiresInSeconds,
293
+ refreshInSeconds,
288
294
  };
289
295
  }
290
296
  else {
@@ -1 +1 @@
1
- {"version":3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,CAAC,GAAG,IAAI,CAAC;wBAClE,CAAC,CAAC,CAAC,CAAC;oBACN,OAAO;wBACL,WAAW,EAAE,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,KAAK;wBAC/B,gBAAgB;qBACjB,CAAC;gBACJ,CAAC;qBAAM,CAAC;oBACN,MAAM,CAAC,IAAI,CACT,6EAA6E,CAC9E,CAAC;oBACF,OAAO;wBACL,WAAW,EAAE,0BAA0B;wBACvC,gBAAgB,EAAE,CAAC;qBACpB,CAAC;gBACJ,CAAC;YACH,CAAC,CAAC,CAAC;YACH,IAAI,CAAC,6BAA6B,GAAG,IAAI,CAAC;QAC5C,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AppTokenProviderParameters, ConfidentialClientApplication } from \"@azure/msal-node\";\nimport {\n AuthenticationError,\n AuthenticationRequiredError,\n CredentialUnavailableError,\n} from \"../../errors\";\nimport { MSI, MSIConfiguration, MSIToken } from \"./models\";\nimport { MsalResult, MsalToken, ValidMsalToken } from \"../../msal/types\";\nimport { cloudShellMsi } from \"./cloudShellMsi\";\nimport { credentialLogger, formatError, formatSuccess } from \"../../util/logging\";\n\nimport { DeveloperSignOnClientId } from \"../../constants\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { appServiceMsi2017 } from \"./appServiceMsi2017\";\nimport { appServiceMsi2019 } from \"./appServiceMsi2019\";\nimport { arcMsi } from \"./arcMsi\";\nimport { fabricMsi } from \"./fabricMsi\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { getMSALLogLevel } from \"../../msal/utils\";\nimport { imdsMsi } from \"./imdsMsi\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi\";\nimport { tracingClient } from \"../../util/tracing\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential\");\n\n// As part of the migration of Managed Identity to MSAL, this legacy provider captures the existing behavior\n// ported over from the ManagedIdentityCredential verbatim. This is to ensure that the existing behavior\n// is maintained while the new implementation is being tested and validated.\n// https://github.com/Azure/azure-sdk-for-js/issues/30189 tracks deleting this provider once it is no longer needed.\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * Since this is an internal implementation, uses a looser interface than the public one.\n */\ninterface ManagedIdentityCredentialOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId?: string;\n}\n\nexport class LegacyMsiProvider {\n private identityClient: IdentityClient;\n private clientId: string | undefined;\n private resourceId: string | undefined;\n private isEndpointUnavailable: boolean | null = null;\n private isAvailableIdentityClient: IdentityClient;\n private confidentialApp: ConfidentialClientApplication;\n private isAppTokenProviderInitialized: boolean = false;\n private msiRetryConfig: MSIConfiguration[\"retryConfig\"] = {\n maxRetries: 5,\n startDelayInMs: 800,\n intervalIncrement: 2,\n };\n\n constructor(\n clientIdOrOptions?: string | ManagedIdentityCredentialOptions,\n options?: TokenCredentialOptions,\n ) {\n let _options: TokenCredentialOptions | undefined;\n if (typeof clientIdOrOptions === \"string\") {\n this.clientId = clientIdOrOptions;\n _options = options;\n } else {\n this.clientId = (clientIdOrOptions as ManagedIdentityCredentialOptions)?.clientId;\n _options = clientIdOrOptions;\n }\n this.resourceId = (_options as ManagedIdentityCredentialOptions)?.resourceId;\n // For JavaScript users.\n if (this.clientId && this.resourceId) {\n throw new Error(\n `ManagedIdentityCredential - Client Id and Resource Id can't be provided at the same time.`,\n );\n }\n if (_options?.retryOptions?.maxRetries !== undefined) {\n this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries;\n }\n this.identityClient = new IdentityClient(_options);\n this.isAvailableIdentityClient = new IdentityClient({\n ..._options,\n retryOptions: {\n maxRetries: 0,\n },\n });\n\n /** authority host validation and metadata discovery to be skipped in managed identity\n * since this wasn't done previously before adding token cache support\n */\n this.confidentialApp = new ConfidentialClientApplication({\n auth: {\n authority: \"https://login.microsoftonline.com/managed_identity\",\n clientId: this.clientId ?? DeveloperSignOnClientId,\n clientSecret: \"dummy-secret\",\n cloudDiscoveryMetadata:\n '{\"tenant_discovery_endpoint\":\"https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration\",\"api-version\":\"1.1\",\"metadata\":[{\"preferred_network\":\"login.microsoftonline.com\",\"preferred_cache\":\"login.windows.net\",\"aliases\":[\"login.microsoftonline.com\",\"login.windows.net\",\"login.microsoft.com\",\"sts.windows.net\"]},{\"preferred_network\":\"login.partner.microsoftonline.cn\",\"preferred_cache\":\"login.partner.microsoftonline.cn\",\"aliases\":[\"login.partner.microsoftonline.cn\",\"login.chinacloudapi.cn\"]},{\"preferred_network\":\"login.microsoftonline.de\",\"preferred_cache\":\"login.microsoftonline.de\",\"aliases\":[\"login.microsoftonline.de\"]},{\"preferred_network\":\"login.microsoftonline.us\",\"preferred_cache\":\"login.microsoftonline.us\",\"aliases\":[\"login.microsoftonline.us\",\"login.usgovcloudapi.net\"]},{\"preferred_network\":\"login-us.microsoftonline.com\",\"preferred_cache\":\"login-us.microsoftonline.com\",\"aliases\":[\"login-us.microsoftonline.com\"]}]}',\n authorityMetadata:\n '{\"token_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_post\",\"private_key_jwt\",\"client_secret_basic\"],\"jwks_uri\":\"https://login.microsoftonline.com/common/discovery/v2.0/keys\",\"response_modes_supported\":[\"query\",\"fragment\",\"form_post\"],\"subject_types_supported\":[\"pairwise\"],\"id_token_signing_alg_values_supported\":[\"RS256\"],\"response_types_supported\":[\"code\",\"id_token\",\"code id_token\",\"id_token token\"],\"scopes_supported\":[\"openid\",\"profile\",\"email\",\"offline_access\"],\"issuer\":\"https://login.microsoftonline.com/{tenantid}/v2.0\",\"request_uri_parameter_supported\":false,\"userinfo_endpoint\":\"https://graph.microsoft.com/oidc/userinfo\",\"authorization_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/authorize\",\"device_authorization_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/devicecode\",\"http_logout_supported\":true,\"frontchannel_logout_supported\":true,\"end_session_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/logout\",\"claims_supported\":[\"sub\",\"iss\",\"cloud_instance_name\",\"cloud_instance_host_name\",\"cloud_graph_host_name\",\"msgraph_host\",\"aud\",\"exp\",\"iat\",\"auth_time\",\"acr\",\"nonce\",\"preferred_username\",\"name\",\"tid\",\"ver\",\"at_hash\",\"c_hash\",\"email\"],\"kerberos_endpoint\":\"https://login.microsoftonline.com/common/kerberos\",\"tenant_region_scope\":null,\"cloud_instance_name\":\"microsoftonline.com\",\"cloud_graph_host_name\":\"graph.windows.net\",\"msgraph_host\":\"graph.microsoft.com\",\"rbac_url\":\"https://pas.windows.net\"}',\n clientCapabilities: [],\n },\n system: {\n loggerOptions: {\n logLevel: getMSALLogLevel(getLogLevel()),\n },\n },\n });\n }\n\n private cachedMSI: MSI | undefined;\n\n private async cachedAvailableMSI(\n scopes: string | string[],\n getTokenOptions?: GetTokenOptions,\n ): Promise<MSI> {\n if (this.cachedMSI) {\n return this.cachedMSI;\n }\n\n const MSIs = [\n arcMsi,\n fabricMsi,\n appServiceMsi2019,\n appServiceMsi2017,\n cloudShellMsi,\n tokenExchangeMsi,\n imdsMsi,\n ];\n\n for (const msi of MSIs) {\n if (\n await msi.isAvailable({\n scopes,\n identityClient: this.isAvailableIdentityClient,\n clientId: this.clientId,\n resourceId: this.resourceId,\n getTokenOptions,\n })\n ) {\n this.cachedMSI = msi;\n return msi;\n }\n }\n\n throw new CredentialUnavailableError(`ManagedIdentityCredential - No MSI credential available`);\n }\n\n private async authenticateManagedIdentity(\n scopes: string | string[],\n getTokenOptions?: GetTokenOptions,\n ): Promise<MSIToken | null> {\n const { span, updatedOptions } = tracingClient.startSpan(\n `ManagedIdentityCredential.authenticateManagedIdentity`,\n getTokenOptions,\n );\n\n try {\n // Determining the available MSI, and avoiding checking for other MSIs while the program is running.\n const availableMSI = await this.cachedAvailableMSI(scopes, updatedOptions);\n return availableMSI.getToken(\n {\n identityClient: this.identityClient,\n scopes,\n clientId: this.clientId,\n resourceId: this.resourceId,\n retryConfig: this.msiRetryConfig,\n },\n updatedOptions,\n );\n } catch (err: any) {\n span.setStatus({\n status: \"error\",\n error: err,\n });\n throw err;\n } finally {\n span.end();\n }\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions,\n ): Promise<AccessToken> {\n let result: AccessToken | null = null;\n const { span, updatedOptions } = tracingClient.startSpan(\n `ManagedIdentityCredential.getToken`,\n options,\n );\n try {\n // isEndpointAvailable can be true, false, or null,\n // If it's null, it means we don't yet know whether\n // the endpoint is available and need to check for it.\n if (this.isEndpointUnavailable !== true) {\n const availableMSI = await this.cachedAvailableMSI(scopes, updatedOptions);\n if (availableMSI.name === \"tokenExchangeMsi\") {\n result = await this.authenticateManagedIdentity(scopes, updatedOptions);\n } else {\n const appTokenParameters: AppTokenProviderParameters = {\n correlationId: this.identityClient.getCorrelationId(),\n tenantId: options?.tenantId || \"managed_identity\",\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n claims: options?.claims,\n };\n\n // Added a check to see if SetAppTokenProvider was already defined.\n this.initializeSetAppTokenProvider();\n const authenticationResult = await this.confidentialApp.acquireTokenByClientCredential({\n ...appTokenParameters,\n });\n result = this.handleResult(scopes, authenticationResult || undefined);\n }\n if (result === null) {\n // If authenticateManagedIdentity returns null,\n // it means no MSI endpoints are available.\n // If so, we avoid trying to reach to them in future requests.\n this.isEndpointUnavailable = true;\n\n // It also means that the endpoint answered with either 200 or 201 (see the sendTokenRequest method),\n // yet we had no access token. For this reason, we'll throw once with a specific message:\n const error = new CredentialUnavailableError(\n \"The managed identity endpoint was reached, yet no tokens were received.\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n // Since `authenticateManagedIdentity` didn't throw, and the result was not null,\n // We will assume that this endpoint is reachable from this point forward,\n // and avoid pinging again to it.\n this.isEndpointUnavailable = false;\n } else {\n // We've previously determined that the endpoint was unavailable,\n // either because it was unreachable or permanently unable to authenticate.\n const error = new CredentialUnavailableError(\n \"The managed identity endpoint is not currently available\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n logger.getToken.info(formatSuccess(scopes));\n return result;\n } catch (err: any) {\n // CredentialUnavailable errors are expected to reach here.\n // We intend them to bubble up, so that DefaultAzureCredential can catch them.\n if (err.name === \"AuthenticationRequiredError\") {\n throw err;\n }\n\n // Expected errors to reach this point:\n // - Errors coming from a method unexpectedly breaking.\n // - When identityClient.sendTokenRequest throws, in which case\n // if the status code was 400, it means that the endpoint is working,\n // but no identity is available.\n\n span.setStatus({\n status: \"error\",\n error: err,\n });\n\n // If either the network is unreachable,\n // we can safely assume the credential is unavailable.\n if (err.code === \"ENETUNREACH\") {\n const error = new CredentialUnavailableError(\n `ManagedIdentityCredential: Unavailable. Network unreachable. Message: ${err.message}`,\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n // If either the host was unreachable,\n // we can safely assume the credential is unavailable.\n if (err.code === \"EHOSTUNREACH\") {\n const error = new CredentialUnavailableError(\n `ManagedIdentityCredential: Unavailable. No managed identity endpoint found. Message: ${err.message}`,\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n // If err.statusCode has a value of 400, it comes from sendTokenRequest,\n // and it means that the endpoint is working, but that no identity is available.\n if (err.statusCode === 400) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: The managed identity endpoint is indicating there's no available identity. Message: ${err.message}`,\n );\n }\n\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n if (err.statusCode === 403 || err.code === 403) {\n if (err.message.includes(\"unreachable\")) {\n const error = new CredentialUnavailableError(\n `ManagedIdentityCredential: Unavailable. Network unreachable. Message: ${err.message}`,\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n }\n\n // If the error has no status code, we can assume there was no available identity.\n // This will throw silently during any ChainedTokenCredential.\n if (err.statusCode === undefined) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Authentication failed. Message ${err.message}`,\n );\n }\n\n // Any other error should break the chain.\n throw new AuthenticationError(err.statusCode, {\n error: `ManagedIdentityCredential authentication failed.`,\n error_description: err.message,\n });\n } finally {\n // Finally is always called, both if we return and if we throw in the above try/catch.\n span.end();\n }\n }\n\n /**\n * Handles the MSAL authentication result.\n * If the result has an account, we update the local account reference.\n * If the token received is invalid, an error will be thrown depending on what's missing.\n */\n private handleResult(\n scopes: string | string[],\n result?: MsalResult,\n getTokenOptions?: GetTokenOptions,\n ): AccessToken {\n this.ensureValidMsalToken(scopes, result, getTokenOptions);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: result.accessToken,\n expiresOnTimestamp: result.expiresOn.getTime(),\n };\n }\n\n /**\n * Ensures the validity of the MSAL token\n */\n private ensureValidMsalToken(\n scopes: string | string[],\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions,\n ): asserts msalToken is ValidMsalToken {\n const error = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw error(\"No response\");\n }\n if (!msalToken.expiresOn) {\n throw error(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw error(`Response had no \"accessToken\" property.`);\n }\n }\n\n private initializeSetAppTokenProvider(): void {\n if (!this.isAppTokenProviderInitialized) {\n this.confidentialApp.SetAppTokenProvider(async (appTokenProviderParameters) => {\n logger.info(\n `SetAppTokenProvider invoked with parameters- ${JSON.stringify(\n appTokenProviderParameters,\n )}`,\n );\n const getTokenOptions: GetTokenOptions = {\n ...appTokenProviderParameters,\n };\n logger.info(\n `authenticateManagedIdentity invoked with scopes- ${JSON.stringify(\n appTokenProviderParameters.scopes,\n )} and getTokenOptions - ${JSON.stringify(getTokenOptions)}`,\n );\n const resultToken = await this.authenticateManagedIdentity(\n appTokenProviderParameters.scopes,\n getTokenOptions,\n );\n\n if (resultToken) {\n logger.info(`SetAppTokenProvider will save the token in cache`);\n\n const expiresInSeconds = resultToken?.expiresOnTimestamp\n ? Math.floor((resultToken.expiresOnTimestamp - Date.now()) / 1000)\n : 0;\n return {\n accessToken: resultToken?.token,\n expiresInSeconds,\n };\n } else {\n logger.info(\n `SetAppTokenProvider token has \"no_access_token_returned\" as the saved token`,\n );\n return {\n accessToken: \"no_access_token_returned\",\n expiresInSeconds: 0,\n };\n }\n });\n this.isAppTokenProviderInitialized = true;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"legacyMsiProvider.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/legacyMsiProvider.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAA8B,6BAA6B,EAAE,MAAM,kBAAkB,CAAC;AAC7F,OAAO,EACL,mBAAmB,EACnB,2BAA2B,EAC3B,0BAA0B,GAC3B,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,oBAAoB,C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AAE,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,KAAK;wBAC/B,gBAAgB;wBAChB,gBAAgB;qBACjB,CAAC;gBACJ,CAAC;qBAAM,CAAC;oBACN,MAAM,CAAC,IAAI,CACT,6EAA6E,CAC9E,CAAC;oBACF,OAAO;wBACL,WAAW,EAAE,0BAA0B;wBACvC,gBAAgB,EAAE,CAAC;qBACpB,CAAC;gBACJ,CAAC;YACH,CAAC,CAAC,CAAC;YACH,IAAI,CAAC,6BAA6B,GAAG,IAAI,CAAC;QAC5C,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AppTokenProviderParameters, ConfidentialClientApplication } from \"@azure/msal-node\";\nimport {\n AuthenticationError,\n AuthenticationRequiredError,\n CredentialUnavailableError,\n} from \"../../errors\";\nimport { MSI, MSIConfiguration, MSIToken } from \"./models\";\nimport { MsalResult, MsalToken, ValidMsalToken } from \"../../msal/types\";\nimport { cloudShellMsi } from \"./cloudShellMsi\";\nimport { credentialLogger, formatError, formatSuccess } from \"../../util/logging\";\n\nimport { DeveloperSignOnClientId } from \"../../constants\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { appServiceMsi2017 } from \"./appServiceMsi2017\";\nimport { appServiceMsi2019 } from \"./appServiceMsi2019\";\nimport { arcMsi } from \"./arcMsi\";\nimport { fabricMsi } from \"./fabricMsi\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { getMSALLogLevel } from \"../../msal/utils\";\nimport { imdsMsi } from \"./imdsMsi\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi\";\nimport { tracingClient } from \"../../util/tracing\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential\");\n\n// As part of the migration of Managed Identity to MSAL, this legacy provider captures the existing behavior\n// ported over from the ManagedIdentityCredential verbatim. This is to ensure that the existing behavior\n// is maintained while the new implementation is being tested and validated.\n// https://github.com/Azure/azure-sdk-for-js/issues/30189 tracks deleting this provider once it is no longer needed.\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * Since this is an internal implementation, uses a looser interface than the public one.\n */\ninterface ManagedIdentityCredentialOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId?: string;\n}\n\nexport class LegacyMsiProvider {\n private identityClient: IdentityClient;\n private clientId: string | undefined;\n private resourceId: string | undefined;\n private isEndpointUnavailable: boolean | null = null;\n private isAvailableIdentityClient: IdentityClient;\n private confidentialApp: ConfidentialClientApplication;\n private isAppTokenProviderInitialized: boolean = false;\n private msiRetryConfig: MSIConfiguration[\"retryConfig\"] = {\n maxRetries: 5,\n startDelayInMs: 800,\n intervalIncrement: 2,\n };\n\n constructor(\n clientIdOrOptions?: string | ManagedIdentityCredentialOptions,\n options?: TokenCredentialOptions,\n ) {\n let _options: TokenCredentialOptions | undefined;\n if (typeof clientIdOrOptions === \"string\") {\n this.clientId = clientIdOrOptions;\n _options = options;\n } else {\n this.clientId = (clientIdOrOptions as ManagedIdentityCredentialOptions)?.clientId;\n _options = clientIdOrOptions;\n }\n this.resourceId = (_options as ManagedIdentityCredentialOptions)?.resourceId;\n // For JavaScript users.\n if (this.clientId && this.resourceId) {\n throw new Error(\n `ManagedIdentityCredential - Client Id and Resource Id can't be provided at the same time.`,\n );\n }\n if (_options?.retryOptions?.maxRetries !== undefined) {\n this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries;\n }\n this.identityClient = new IdentityClient(_options);\n this.isAvailableIdentityClient = new IdentityClient({\n ..._options,\n retryOptions: {\n maxRetries: 0,\n },\n });\n\n /** authority host validation and metadata discovery to be skipped in managed identity\n * since this wasn't done previously before adding token cache support\n */\n this.confidentialApp = new ConfidentialClientApplication({\n auth: {\n authority: \"https://login.microsoftonline.com/managed_identity\",\n clientId: this.clientId ?? DeveloperSignOnClientId,\n clientSecret: \"dummy-secret\",\n cloudDiscoveryMetadata:\n '{\"tenant_discovery_endpoint\":\"https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration\",\"api-version\":\"1.1\",\"metadata\":[{\"preferred_network\":\"login.microsoftonline.com\",\"preferred_cache\":\"login.windows.net\",\"aliases\":[\"login.microsoftonline.com\",\"login.windows.net\",\"login.microsoft.com\",\"sts.windows.net\"]},{\"preferred_network\":\"login.partner.microsoftonline.cn\",\"preferred_cache\":\"login.partner.microsoftonline.cn\",\"aliases\":[\"login.partner.microsoftonline.cn\",\"login.chinacloudapi.cn\"]},{\"preferred_network\":\"login.microsoftonline.de\",\"preferred_cache\":\"login.microsoftonline.de\",\"aliases\":[\"login.microsoftonline.de\"]},{\"preferred_network\":\"login.microsoftonline.us\",\"preferred_cache\":\"login.microsoftonline.us\",\"aliases\":[\"login.microsoftonline.us\",\"login.usgovcloudapi.net\"]},{\"preferred_network\":\"login-us.microsoftonline.com\",\"preferred_cache\":\"login-us.microsoftonline.com\",\"aliases\":[\"login-us.microsoftonline.com\"]}]}',\n authorityMetadata:\n '{\"token_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_post\",\"private_key_jwt\",\"client_secret_basic\"],\"jwks_uri\":\"https://login.microsoftonline.com/common/discovery/v2.0/keys\",\"response_modes_supported\":[\"query\",\"fragment\",\"form_post\"],\"subject_types_supported\":[\"pairwise\"],\"id_token_signing_alg_values_supported\":[\"RS256\"],\"response_types_supported\":[\"code\",\"id_token\",\"code id_token\",\"id_token token\"],\"scopes_supported\":[\"openid\",\"profile\",\"email\",\"offline_access\"],\"issuer\":\"https://login.microsoftonline.com/{tenantid}/v2.0\",\"request_uri_parameter_supported\":false,\"userinfo_endpoint\":\"https://graph.microsoft.com/oidc/userinfo\",\"authorization_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/authorize\",\"device_authorization_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/devicecode\",\"http_logout_supported\":true,\"frontchannel_logout_supported\":true,\"end_session_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/logout\",\"claims_supported\":[\"sub\",\"iss\",\"cloud_instance_name\",\"cloud_instance_host_name\",\"cloud_graph_host_name\",\"msgraph_host\",\"aud\",\"exp\",\"iat\",\"auth_time\",\"acr\",\"nonce\",\"preferred_username\",\"name\",\"tid\",\"ver\",\"at_hash\",\"c_hash\",\"email\"],\"kerberos_endpoint\":\"https://login.microsoftonline.com/common/kerberos\",\"tenant_region_scope\":null,\"cloud_instance_name\":\"microsoftonline.com\",\"cloud_graph_host_name\":\"graph.windows.net\",\"msgraph_host\":\"graph.microsoft.com\",\"rbac_url\":\"https://pas.windows.net\"}',\n clientCapabilities: [],\n },\n system: {\n loggerOptions: {\n logLevel: getMSALLogLevel(getLogLevel()),\n },\n },\n });\n }\n\n private cachedMSI: MSI | undefined;\n\n private async cachedAvailableMSI(\n scopes: string | string[],\n getTokenOptions?: GetTokenOptions,\n ): Promise<MSI> {\n if (this.cachedMSI) {\n return this.cachedMSI;\n }\n\n const MSIs = [\n arcMsi,\n fabricMsi,\n appServiceMsi2019,\n appServiceMsi2017,\n cloudShellMsi,\n tokenExchangeMsi,\n imdsMsi,\n ];\n\n for (const msi of MSIs) {\n if (\n await msi.isAvailable({\n scopes,\n identityClient: this.isAvailableIdentityClient,\n clientId: this.clientId,\n resourceId: this.resourceId,\n getTokenOptions,\n })\n ) {\n this.cachedMSI = msi;\n return msi;\n }\n }\n\n throw new CredentialUnavailableError(`ManagedIdentityCredential - No MSI credential available`);\n }\n\n private async authenticateManagedIdentity(\n scopes: string | string[],\n getTokenOptions?: GetTokenOptions,\n ): Promise<MSIToken | null> {\n const { span, updatedOptions } = tracingClient.startSpan(\n `ManagedIdentityCredential.authenticateManagedIdentity`,\n getTokenOptions,\n );\n\n try {\n // Determining the available MSI, and avoiding checking for other MSIs while the program is running.\n const availableMSI = await this.cachedAvailableMSI(scopes, updatedOptions);\n return availableMSI.getToken(\n {\n identityClient: this.identityClient,\n scopes,\n clientId: this.clientId,\n resourceId: this.resourceId,\n retryConfig: this.msiRetryConfig,\n },\n updatedOptions,\n );\n } catch (err: any) {\n span.setStatus({\n status: \"error\",\n error: err,\n });\n throw err;\n } finally {\n span.end();\n }\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions,\n ): Promise<AccessToken> {\n let result: AccessToken | null = null;\n const { span, updatedOptions } = tracingClient.startSpan(\n `ManagedIdentityCredential.getToken`,\n options,\n );\n try {\n // isEndpointAvailable can be true, false, or null,\n // If it's null, it means we don't yet know whether\n // the endpoint is available and need to check for it.\n if (this.isEndpointUnavailable !== true) {\n const availableMSI = await this.cachedAvailableMSI(scopes, updatedOptions);\n if (availableMSI.name === \"tokenExchangeMsi\") {\n result = await this.authenticateManagedIdentity(scopes, updatedOptions);\n } else {\n const appTokenParameters: AppTokenProviderParameters = {\n correlationId: this.identityClient.getCorrelationId(),\n tenantId: options?.tenantId || \"managed_identity\",\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n claims: options?.claims,\n };\n\n // Added a check to see if SetAppTokenProvider was already defined.\n this.initializeSetAppTokenProvider();\n const authenticationResult = await this.confidentialApp.acquireTokenByClientCredential({\n ...appTokenParameters,\n });\n result = this.handleResult(scopes, authenticationResult || undefined);\n }\n if (result === null) {\n // If authenticateManagedIdentity returns null,\n // it means no MSI endpoints are available.\n // If so, we avoid trying to reach to them in future requests.\n this.isEndpointUnavailable = true;\n\n // It also means that the endpoint answered with either 200 or 201 (see the sendTokenRequest method),\n // yet we had no access token. For this reason, we'll throw once with a specific message:\n const error = new CredentialUnavailableError(\n \"The managed identity endpoint was reached, yet no tokens were received.\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n // Since `authenticateManagedIdentity` didn't throw, and the result was not null,\n // We will assume that this endpoint is reachable from this point forward,\n // and avoid pinging again to it.\n this.isEndpointUnavailable = false;\n } else {\n // We've previously determined that the endpoint was unavailable,\n // either because it was unreachable or permanently unable to authenticate.\n const error = new CredentialUnavailableError(\n \"The managed identity endpoint is not currently available\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n logger.getToken.info(formatSuccess(scopes));\n return result;\n } catch (err: any) {\n // CredentialUnavailable errors are expected to reach here.\n // We intend them to bubble up, so that DefaultAzureCredential can catch them.\n if (err.name === \"AuthenticationRequiredError\") {\n throw err;\n }\n\n // Expected errors to reach this point:\n // - Errors coming from a method unexpectedly breaking.\n // - When identityClient.sendTokenRequest throws, in which case\n // if the status code was 400, it means that the endpoint is working,\n // but no identity is available.\n\n span.setStatus({\n status: \"error\",\n error: err,\n });\n\n // If either the network is unreachable,\n // we can safely assume the credential is unavailable.\n if (err.code === \"ENETUNREACH\") {\n const error = new CredentialUnavailableError(\n `ManagedIdentityCredential: Unavailable. Network unreachable. Message: ${err.message}`,\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n // If either the host was unreachable,\n // we can safely assume the credential is unavailable.\n if (err.code === \"EHOSTUNREACH\") {\n const error = new CredentialUnavailableError(\n `ManagedIdentityCredential: Unavailable. No managed identity endpoint found. Message: ${err.message}`,\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n // If err.statusCode has a value of 400, it comes from sendTokenRequest,\n // and it means that the endpoint is working, but that no identity is available.\n if (err.statusCode === 400) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: The managed identity endpoint is indicating there's no available identity. Message: ${err.message}`,\n );\n }\n\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n if (err.statusCode === 403 || err.code === 403) {\n if (err.message.includes(\"unreachable\")) {\n const error = new CredentialUnavailableError(\n `ManagedIdentityCredential: Unavailable. Network unreachable. Message: ${err.message}`,\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n }\n\n // If the error has no status code, we can assume there was no available identity.\n // This will throw silently during any ChainedTokenCredential.\n if (err.statusCode === undefined) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Authentication failed. Message ${err.message}`,\n );\n }\n\n // Any other error should break the chain.\n throw new AuthenticationError(err.statusCode, {\n error: `ManagedIdentityCredential authentication failed.`,\n error_description: err.message,\n });\n } finally {\n // Finally is always called, both if we return and if we throw in the above try/catch.\n span.end();\n }\n }\n\n /**\n * Handles the MSAL authentication result.\n * If the result has an account, we update the local account reference.\n * If the token received is invalid, an error will be thrown depending on what's missing.\n */\n private handleResult(\n scopes: string | string[],\n result?: MsalResult,\n getTokenOptions?: GetTokenOptions,\n ): AccessToken {\n this.ensureValidMsalToken(scopes, result, getTokenOptions);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: result.accessToken,\n expiresOnTimestamp: result.expiresOn.getTime(),\n refreshAfterTimestamp: result.refreshOn?.getTime(),\n };\n }\n\n /**\n * Ensures the validity of the MSAL token\n */\n private ensureValidMsalToken(\n scopes: string | string[],\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions,\n ): asserts msalToken is ValidMsalToken {\n const error = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw error(\"No response\");\n }\n if (!msalToken.expiresOn) {\n throw error(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw error(`Response had no \"accessToken\" property.`);\n }\n }\n\n private initializeSetAppTokenProvider(): void {\n if (!this.isAppTokenProviderInitialized) {\n this.confidentialApp.SetAppTokenProvider(async (appTokenProviderParameters) => {\n logger.info(\n `SetAppTokenProvider invoked with parameters- ${JSON.stringify(\n appTokenProviderParameters,\n )}`,\n );\n const getTokenOptions: GetTokenOptions = {\n ...appTokenProviderParameters,\n };\n logger.info(\n `authenticateManagedIdentity invoked with scopes- ${JSON.stringify(\n appTokenProviderParameters.scopes,\n )} and getTokenOptions - ${JSON.stringify(getTokenOptions)}`,\n );\n const resultToken = await this.authenticateManagedIdentity(\n appTokenProviderParameters.scopes,\n getTokenOptions,\n );\n\n if (resultToken) {\n logger.info(`SetAppTokenProvider will save the token in cache`);\n\n const expiresInSeconds = resultToken?.expiresOnTimestamp\n ? Math.floor((resultToken.expiresOnTimestamp - Date.now()) / 1000)\n : 0;\n const refreshInSeconds = resultToken?.refreshAfterTimestamp\n ? Math.floor((resultToken.refreshAfterTimestamp - Date.now()) / 1000)\n : 0;\n return {\n accessToken: resultToken?.token,\n expiresInSeconds,\n refreshInSeconds,\n };\n } else {\n logger.info(\n `SetAppTokenProvider token has \"no_access_token_returned\" as the saved token`,\n );\n return {\n accessToken: \"no_access_token_returned\",\n expiresInSeconds: 0,\n };\n }\n });\n this.isAppTokenProviderInitialized = true;\n }\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  export {};
4
4
  //# sourceMappingURL=models.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"models.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/models.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\n\nimport { IdentityClient } from \"../../client/identityClient\";\n\n/**\n * @internal\n */\nexport interface MSIConfiguration {\n retryConfig: {\n maxRetries: number;\n startDelayInMs: number;\n intervalIncrement: number;\n };\n identityClient: IdentityClient;\n scopes: string | string[];\n clientId?: string;\n resourceId?: string;\n}\n\n/**\n * @internal\n * Represents an access token for {@link ManagedIdentity} for internal usage,\n * with an expiration time and the time in which token should refresh.\n */\nexport declare interface MSIToken extends AccessToken {}\n\n/**\n * @internal\n */\nexport interface MSI {\n name: string;\n isAvailable(options: {\n scopes: string | string[];\n identityClient?: IdentityClient;\n clientId?: string;\n resourceId?: string;\n getTokenOptions?: GetTokenOptions;\n }): Promise<boolean>;\n getToken(\n configuration: MSIConfiguration,\n getTokenOptions?: GetTokenOptions,\n ): Promise<MSIToken | null>;\n}\n"]}
1
+ {"version":3,"file":"models.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/models.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\n\nimport { IdentityClient } from \"../../client/identityClient\";\n\n/**\n * @internal\n */\nexport interface MSIConfiguration {\n retryConfig: {\n maxRetries: number;\n startDelayInMs: number;\n intervalIncrement: number;\n };\n identityClient: IdentityClient;\n scopes: string | string[];\n clientId?: string;\n resourceId?: string;\n}\n\n/**\n * @internal\n * Represents an access token for {@link ManagedIdentity} for internal usage,\n * with an expiration time and the time in which token should refresh.\n */\nexport declare interface MSIToken extends AccessToken {}\n\n/**\n * @internal\n */\nexport interface MSI {\n name: string;\n isAvailable(options: {\n scopes: string | string[];\n identityClient?: IdentityClient;\n clientId?: string;\n resourceId?: string;\n getTokenOptions?: GetTokenOptions;\n }): Promise<boolean>;\n getToken(\n configuration: MSIConfiguration,\n getTokenOptions?: GetTokenOptions,\n ): Promise<MSIToken | null>;\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  import { AuthenticationRequiredError, CredentialUnavailableError } from "../../errors";
4
4
  import { credentialLogger, formatError, formatSuccess } from "../../util/logging";
5
5
  import { defaultLoggerCallback, getMSALLogLevel } from "../../msal/utils";
@@ -30,9 +30,11 @@ export class MsalMsiProvider {
30
30
  _options = clientIdOrOptions !== null && clientIdOrOptions !== void 0 ? clientIdOrOptions : {};
31
31
  }
32
32
  this.resourceId = _options === null || _options === void 0 ? void 0 : _options.resourceId;
33
+ this.objectId = _options === null || _options === void 0 ? void 0 : _options.objectId;
33
34
  // For JavaScript users.
34
- if (this.clientId && this.resourceId) {
35
- throw new Error(`ManagedIdentityCredential - Client Id and Resource Id can't be provided at the same time.`);
35
+ const providedIds = [this.clientId, this.resourceId, this.objectId].filter(Boolean);
36
+ if (providedIds.length > 1) {
37
+ throw new Error(`ManagedIdentityCredential: only one of 'clientId', 'resourceId', or 'objectId' can be provided. Received values: ${JSON.stringify({ clientId: this.clientId, resourceId: this.resourceId, objectId: this.objectId })}`);
36
38
  }
37
39
  // ManagedIdentity uses http for local requests
38
40
  _options.allowInsecureConnection = true;
@@ -44,6 +46,7 @@ export class MsalMsiProvider {
44
46
  managedIdentityIdParams: {
45
47
  userAssignedClientId: this.clientId,
46
48
  userAssignedResourceId: this.resourceId,
49
+ userAssignedObjectId: this.objectId,
47
50
  },
48
51
  system: {
49
52
  // todo: proxyUrl?
@@ -59,6 +62,17 @@ export class MsalMsiProvider {
59
62
  this.isAvailableIdentityClient = new IdentityClient(Object.assign(Object.assign({}, _options), { retryOptions: {
60
63
  maxRetries: 0,
61
64
  } }));
65
+ // CloudShell MSI will ignore any user-assigned identity passed as parameters. To avoid confusion, we prevent this from happening as early as possible.
66
+ if (this.managedIdentityApp.getManagedIdentitySource() === "CloudShell") {
67
+ if (this.clientId || this.resourceId || this.objectId) {
68
+ logger.warning(`CloudShell MSI detected with user-provided IDs - throwing. Received values: ${JSON.stringify({
69
+ clientId: this.clientId,
70
+ resourceId: this.resourceId,
71
+ objectId: this.objectId,
72
+ })}.`);
73
+ throw new CredentialUnavailableError("ManagedIdentityCredential: Specifying a user-assigned managed identity is not supported for CloudShell at runtime. When using Managed Identity in CloudShell, omit the clientId, resourceId, and objectId parameters.");
74
+ }
75
+ }
62
76
  }
63
77
  /**
64
78
  * Authenticates with Microsoft Entra ID and returns an access token if successful.
@@ -76,6 +90,7 @@ export class MsalMsiProvider {
76
90
  throw new CredentialUnavailableError(`ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(scopes)}`);
77
91
  }
78
92
  return tracingClient.withSpan("ManagedIdentityCredential.getToken", options, async () => {
93
+ var _a;
79
94
  try {
80
95
  const isTokenExchangeMsi = await tokenExchangeMsi.isAvailable({
81
96
  scopes,
@@ -91,6 +106,7 @@ export class MsalMsiProvider {
91
106
  // We will continue to implement these features in the Identity library.
92
107
  const identitySource = this.managedIdentityApp.getManagedIdentitySource();
93
108
  const isImdsMsi = identitySource === "DefaultToImds" || identitySource === "Imds"; // Neither actually checks that IMDS endpoint is available, just that it's the source the MSAL _would_ try to use.
109
+ logger.getToken.info(`MSAL Identity source: ${identitySource}`);
94
110
  if (isTokenExchangeMsi) {
95
111
  // In the AKS scenario we will use the existing tokenExchangeMsi indefinitely.
96
112
  logger.getToken.info("Using the token exchange managed identity.");
@@ -102,7 +118,7 @@ export class MsalMsiProvider {
102
118
  resourceId: this.resourceId,
103
119
  });
104
120
  if (result === null) {
105
- throw new CredentialUnavailableError("The managed identity endpoint was reached, yet no tokens were received.");
121
+ throw new CredentialUnavailableError("Attempted to use the token exchange managed identity, but received a null response.");
106
122
  }
107
123
  return result;
108
124
  }
@@ -118,7 +134,7 @@ export class MsalMsiProvider {
118
134
  resourceId: this.resourceId,
119
135
  });
120
136
  if (!isAvailable) {
121
- throw new CredentialUnavailableError(`ManagedIdentityCredential: The managed identity endpoint is not available.`);
137
+ throw new CredentialUnavailableError(`Attempted to use the IMDS endpoint, but it is not available.`);
122
138
  }
123
139
  }
124
140
  // If we got this far, it means:
@@ -134,6 +150,7 @@ export class MsalMsiProvider {
134
150
  return {
135
151
  expiresOnTimestamp: token.expiresOn.getTime(),
136
152
  token: token.accessToken,
153
+ refreshAfterTimestamp: (_a = token.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(),
137
154
  };
138
155
  }
139
156
  catch (err) {
@@ -144,9 +161,9 @@ export class MsalMsiProvider {
144
161
  throw err;
145
162
  }
146
163
  if (isNetworkError(err)) {
147
- throw new CredentialUnavailableError(`ManagedIdentityCredential: Network unreachable. Message: ${err.message}`);
164
+ throw new CredentialUnavailableError(`ManagedIdentityCredential: Network unreachable. Message: ${err.message}`, { cause: err });
148
165
  }
149
- throw new CredentialUnavailableError(`ManagedIdentityCredential: Authentication failed. Message ${err.message}`);
166
+ throw new CredentialUnavailableError(`ManagedIdentityCredential: Authentication failed. Message ${err.message}`, { cause: err });
150
167
  }
151
168
  });
152
169
  }
@@ -163,7 +180,7 @@ export class MsalMsiProvider {
163
180
  });
164
181
  };
165
182
  if (!msalToken) {
166
- throw createError("No response");
183
+ throw createError("No response.");
167
184
  }
168
185
  if (!msalToken.expiresOn) {
169
186
  throw createError(`Response had no "expiresOn" property.`);
@@ -1 +1 @@
1
- {"version":3,"file":"msalMsiProvider.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/msalMsiProvider.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAEvF,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAClF,OAAO,EAAE,qBAAqB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAE1E,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAE7D,OAA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IAC5C,IAAI,GAAG,CAAC,UAAU,KAAK,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,EAAE,CAAC;QAC/C,IAAI,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAC;YACxC,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../../errors\";\nimport { MsalToken, ValidMsalToken } from \"../../msal/types\";\nimport { credentialLogger, formatError, formatSuccess } from \"../../util/logging\";\nimport { defaultLoggerCallback, getMSALLogLevel } from \"../../msal/utils\";\n\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { MSIConfiguration } from \"./models\";\nimport { ManagedIdentityApplication } from \"@azure/msal-node\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { imdsMsi } from \"./imdsMsi\";\nimport { imdsRetryPolicy } from \"./imdsRetryPolicy\";\nimport { mapScopesToResource } from \"./utils\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi\";\nimport { tracingClient } from \"../../util/tracing\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential(MSAL)\");\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * Since this is an internal implementation, uses a looser interface than the public one.\n */\ninterface ManagedIdentityCredentialOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId?: string;\n}\n\nexport class MsalMsiProvider {\n private managedIdentityApp: ManagedIdentityApplication;\n private identityClient: IdentityClient;\n private clientId?: string;\n private resourceId?: string;\n private msiRetryConfig: MSIConfiguration[\"retryConfig\"] = {\n maxRetries: 5,\n startDelayInMs: 800,\n intervalIncrement: 2,\n };\n private isAvailableIdentityClient: IdentityClient;\n\n constructor(\n clientIdOrOptions?: string | ManagedIdentityCredentialOptions,\n options: ManagedIdentityCredentialOptions = {},\n ) {\n let _options: ManagedIdentityCredentialOptions = {};\n if (typeof clientIdOrOptions === \"string\") {\n this.clientId = clientIdOrOptions;\n _options = options;\n } else {\n this.clientId = clientIdOrOptions?.clientId;\n _options = clientIdOrOptions ?? {};\n }\n this.resourceId = _options?.resourceId;\n\n // For JavaScript users.\n if (this.clientId && this.resourceId) {\n throw new Error(\n `ManagedIdentityCredential - Client Id and Resource Id can't be provided at the same time.`,\n );\n }\n\n // ManagedIdentity uses http for local requests\n _options.allowInsecureConnection = true;\n\n if (_options?.retryOptions?.maxRetries !== undefined) {\n this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries;\n }\n\n this.identityClient = new IdentityClient({\n ..._options,\n additionalPolicies: [{ policy: imdsRetryPolicy(this.msiRetryConfig), position: \"perCall\" }],\n });\n\n this.managedIdentityApp = new ManagedIdentityApplication({\n managedIdentityIdParams: {\n userAssignedClientId: this.clientId,\n userAssignedResourceId: this.resourceId,\n },\n system: {\n // todo: proxyUrl?\n disableInternalRetries: true,\n networkClient: this.identityClient,\n loggerOptions: {\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: options.loggingOptions?.enableUnsafeSupportLogging,\n loggerCallback: defaultLoggerCallback(logger),\n },\n },\n });\n\n this.isAvailableIdentityClient = new IdentityClient({\n ..._options,\n retryOptions: {\n maxRetries: 0,\n },\n });\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n logger.getToken.info(\"Using the MSAL provider for Managed Identity.\");\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(scopes)}`,\n );\n }\n\n return tracingClient.withSpan(\"ManagedIdentityCredential.getToken\", options, async () => {\n try {\n const isTokenExchangeMsi = await tokenExchangeMsi.isAvailable({\n scopes,\n clientId: this.clientId,\n getTokenOptions: options,\n identityClient: this.identityClient,\n resourceId: this.resourceId,\n });\n\n // Most scenarios are handled by MSAL except for two:\n // AKS pod identity - MSAL does not implement the token exchange flow.\n // IMDS Endpoint probing - MSAL does not do any probing before trying to get a token.\n // As a DefaultAzureCredential optimization we probe the IMDS endpoint with a short timeout and no retries before actually trying to get a token\n // We will continue to implement these features in the Identity library.\n\n const identitySource = this.managedIdentityApp.getManagedIdentitySource();\n const isImdsMsi = identitySource === \"DefaultToImds\" || identitySource === \"Imds\"; // Neither actually checks that IMDS endpoint is available, just that it's the source the MSAL _would_ try to use.\n\n if (isTokenExchangeMsi) {\n // In the AKS scenario we will use the existing tokenExchangeMsi indefinitely.\n logger.getToken.info(\"Using the token exchange managed identity.\");\n const result = await tokenExchangeMsi.getToken({\n scopes,\n clientId: this.clientId,\n identityClient: this.identityClient,\n retryConfig: this.msiRetryConfig,\n resourceId: this.resourceId,\n });\n\n if (result === null) {\n throw new CredentialUnavailableError(\n \"The managed identity endpoint was reached, yet no tokens were received.\",\n );\n }\n\n return result;\n } else if (isImdsMsi) {\n // In the IMDS scenario we will probe the IMDS endpoint to ensure it's available before trying to get a token.\n // If the IMDS endpoint is not available and this is the source that MSAL will use, we will fail-fast with an error that tells DAC to move to the next credential.\n logger.getToken.info(\"Using the IMDS endpoint to probe for availability.\");\n const isAvailable = await imdsMsi.isAvailable({\n scopes,\n clientId: this.clientId,\n getTokenOptions: options,\n identityClient: this.isAvailableIdentityClient,\n resourceId: this.resourceId,\n });\n\n if (!isAvailable) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: The managed identity endpoint is not available.`,\n );\n }\n }\n\n // If we got this far, it means:\n // - This is not a tokenExchangeMsi,\n // - We already probed for IMDS endpoint availability and failed-fast if it's unreachable.\n // We can proceed normally by calling MSAL for a token.\n logger.getToken.info(\"Calling into MSAL for managed identity token.\");\n const token = await this.managedIdentityApp.acquireToken({\n resource,\n });\n\n this.ensureValidMsalToken(scopes, token, options);\n logger.getToken.info(formatSuccess(scopes));\n\n return {\n expiresOnTimestamp: token.expiresOn.getTime(),\n token: token.accessToken,\n };\n } catch (err: any) {\n logger.getToken.error(formatError(scopes, err));\n\n // AuthenticationRequiredError described as Error to enforce authentication after trying to retrieve a token silently.\n // TODO: why would this _ever_ happen considering we're not trying the silent request in this flow?\n if (err.name === \"AuthenticationRequiredError\") {\n throw err;\n }\n\n if (isNetworkError(err)) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Network unreachable. Message: ${err.message}`,\n );\n }\n\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Authentication failed. Message ${err.message}`,\n );\n }\n });\n }\n\n /**\n * Ensures the validity of the MSAL token\n */\n private ensureValidMsalToken(\n scopes: string | string[],\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions,\n ): asserts msalToken is ValidMsalToken {\n const createError = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw createError(\"No response\");\n }\n if (!msalToken.expiresOn) {\n throw createError(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw createError(`Response had no \"accessToken\" property.`);\n }\n }\n}\n\nfunction isNetworkError(err: any): boolean {\n // MSAL error\n if (err.errorCode === \"network_error\") {\n return true;\n }\n\n // Probe errors\n if (err.code === \"ENETUNREACH\" || err.code === \"EHOSTUNREACH\") {\n return true;\n }\n\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n if (err.statusCode === 403 || err.code === 403) {\n if (err.message.includes(\"unreachable\")) {\n return true;\n }\n }\n\n return false;\n}\n"]}
1
+ {"version":3,"file":"msalMsiProvider.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/msalMsiProvider.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAEvF,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAClF,OAAO,EAAE,qBAAqB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAE1E,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAE7D,OAAO,EAAE,0BAA0B,EAAE,MAAM,kBAAkB,CAAC;AAE9D,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,MAAM,MAAM,GAAG,gBAAgB,CAAC,iCAAiC,CAAC,CAAC;AA4BnE,MAAM,OAAO,eAAe;IAa1B,YACE,iBAA6D,EAC7D,UAA4C,EAAE;;QATxC,mBAAc,GAAoC;YACxD,UAAU,EAAE,CAAC;YACb,cAAc,EAAE,GAAG;YAC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,CAAC,CAAC;QACpC,CAAC;QACD,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE,CAAC;YACzB,MAAM,WAAW,CAAC,uCAAuC,CAAC,CAAC;QAC7D,CAAC;QACD,IAAI,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC;YAC3B,MAAM,WAAW,CAAC,yCAAyC,CAAC,CAAC;QAC/D,CAAC;IACH,CAAC;CACF;AAED,SAAS,cAAc,CAAC,GAAQ;IAC9B,aAAa;IACb,IAAI,GAAG,CAAC,SAAS,KAAK,eAAe,EAAE,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,eAAe;IACf,IAAI,GAAG,CAAC,IAAI,KAAK,aAAa,IAAI,GAAG,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;QAC9D,OAAO,IAAI,CAAC;IACd,CAAC;IAED,6NAA6N;IAC7N,4CAA4C;IAC5C,IAAI,GAAG,CAAC,UAAU,KAAK,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,EAAE,CAAC;QAC/C,IAAI,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAC;YACxC,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../../errors\";\nimport { MsalToken, ValidMsalToken } from \"../../msal/types\";\nimport { credentialLogger, formatError, formatSuccess } from \"../../util/logging\";\nimport { defaultLoggerCallback, getMSALLogLevel } from \"../../msal/utils\";\n\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { MSIConfiguration } from \"./models\";\nimport { ManagedIdentityApplication } from \"@azure/msal-node\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { imdsMsi } from \"./imdsMsi\";\nimport { imdsRetryPolicy } from \"./imdsRetryPolicy\";\nimport { mapScopesToResource } from \"./utils\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi\";\nimport { tracingClient } from \"../../util/tracing\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential(MSAL)\");\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * Since this is an internal implementation, uses a looser interface than the public one.\n */\ninterface ManagedIdentityCredentialOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId?: string;\n\n /**\n * Allows specifying the object ID of the underlying service principal used to authenticate a user-assigned managed identity.\n * This is an alternative to providing a client ID and is not required for system-assigned managed identities.\n */\n objectId?: string;\n}\n\nexport class MsalMsiProvider {\n private managedIdentityApp: ManagedIdentityApplication;\n private identityClient: IdentityClient;\n private clientId?: string;\n private resourceId?: string;\n private objectId?: string;\n private msiRetryConfig: MSIConfiguration[\"retryConfig\"] = {\n maxRetries: 5,\n startDelayInMs: 800,\n intervalIncrement: 2,\n };\n private isAvailableIdentityClient: IdentityClient;\n\n constructor(\n clientIdOrOptions?: string | ManagedIdentityCredentialOptions,\n options: ManagedIdentityCredentialOptions = {},\n ) {\n let _options: ManagedIdentityCredentialOptions = {};\n if (typeof clientIdOrOptions === \"string\") {\n this.clientId = clientIdOrOptions;\n _options = options;\n } else {\n this.clientId = clientIdOrOptions?.clientId;\n _options = clientIdOrOptions ?? {};\n }\n this.resourceId = _options?.resourceId;\n this.objectId = _options?.objectId;\n\n // For JavaScript users.\n const providedIds = [this.clientId, this.resourceId, this.objectId].filter(Boolean);\n if (providedIds.length > 1) {\n throw new Error(\n `ManagedIdentityCredential: only one of 'clientId', 'resourceId', or 'objectId' can be provided. Received values: ${JSON.stringify(\n { clientId: this.clientId, resourceId: this.resourceId, objectId: this.objectId },\n )}`,\n );\n }\n\n // ManagedIdentity uses http for local requests\n _options.allowInsecureConnection = true;\n\n if (_options?.retryOptions?.maxRetries !== undefined) {\n this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries;\n }\n\n this.identityClient = new IdentityClient({\n ..._options,\n additionalPolicies: [{ policy: imdsRetryPolicy(this.msiRetryConfig), position: \"perCall\" }],\n });\n\n this.managedIdentityApp = new ManagedIdentityApplication({\n managedIdentityIdParams: {\n userAssignedClientId: this.clientId,\n userAssignedResourceId: this.resourceId,\n userAssignedObjectId: this.objectId,\n },\n system: {\n // todo: proxyUrl?\n disableInternalRetries: true,\n networkClient: this.identityClient,\n loggerOptions: {\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: options.loggingOptions?.enableUnsafeSupportLogging,\n loggerCallback: defaultLoggerCallback(logger),\n },\n },\n });\n\n this.isAvailableIdentityClient = new IdentityClient({\n ..._options,\n retryOptions: {\n maxRetries: 0,\n },\n });\n\n // CloudShell MSI will ignore any user-assigned identity passed as parameters. To avoid confusion, we prevent this from happening as early as possible.\n if (this.managedIdentityApp.getManagedIdentitySource() === \"CloudShell\") {\n if (this.clientId || this.resourceId || this.objectId) {\n logger.warning(\n `CloudShell MSI detected with user-provided IDs - throwing. Received values: ${JSON.stringify(\n {\n clientId: this.clientId,\n resourceId: this.resourceId,\n objectId: this.objectId,\n },\n )}.`,\n );\n throw new CredentialUnavailableError(\n \"ManagedIdentityCredential: Specifying a user-assigned managed identity is not supported for CloudShell at runtime. When using Managed Identity in CloudShell, omit the clientId, resourceId, and objectId parameters.\",\n );\n }\n }\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n logger.getToken.info(\"Using the MSAL provider for Managed Identity.\");\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(scopes)}`,\n );\n }\n\n return tracingClient.withSpan(\"ManagedIdentityCredential.getToken\", options, async () => {\n try {\n const isTokenExchangeMsi = await tokenExchangeMsi.isAvailable({\n scopes,\n clientId: this.clientId,\n getTokenOptions: options,\n identityClient: this.identityClient,\n resourceId: this.resourceId,\n });\n\n // Most scenarios are handled by MSAL except for two:\n // AKS pod identity - MSAL does not implement the token exchange flow.\n // IMDS Endpoint probing - MSAL does not do any probing before trying to get a token.\n // As a DefaultAzureCredential optimization we probe the IMDS endpoint with a short timeout and no retries before actually trying to get a token\n // We will continue to implement these features in the Identity library.\n\n const identitySource = this.managedIdentityApp.getManagedIdentitySource();\n const isImdsMsi = identitySource === \"DefaultToImds\" || identitySource === \"Imds\"; // Neither actually checks that IMDS endpoint is available, just that it's the source the MSAL _would_ try to use.\n\n logger.getToken.info(`MSAL Identity source: ${identitySource}`);\n\n if (isTokenExchangeMsi) {\n // In the AKS scenario we will use the existing tokenExchangeMsi indefinitely.\n logger.getToken.info(\"Using the token exchange managed identity.\");\n const result = await tokenExchangeMsi.getToken({\n scopes,\n clientId: this.clientId,\n identityClient: this.identityClient,\n retryConfig: this.msiRetryConfig,\n resourceId: this.resourceId,\n });\n\n if (result === null) {\n throw new CredentialUnavailableError(\n \"Attempted to use the token exchange managed identity, but received a null response.\",\n );\n }\n\n return result;\n } else if (isImdsMsi) {\n // In the IMDS scenario we will probe the IMDS endpoint to ensure it's available before trying to get a token.\n // If the IMDS endpoint is not available and this is the source that MSAL will use, we will fail-fast with an error that tells DAC to move to the next credential.\n logger.getToken.info(\"Using the IMDS endpoint to probe for availability.\");\n const isAvailable = await imdsMsi.isAvailable({\n scopes,\n clientId: this.clientId,\n getTokenOptions: options,\n identityClient: this.isAvailableIdentityClient,\n resourceId: this.resourceId,\n });\n\n if (!isAvailable) {\n throw new CredentialUnavailableError(\n `Attempted to use the IMDS endpoint, but it is not available.`,\n );\n }\n }\n\n // If we got this far, it means:\n // - This is not a tokenExchangeMsi,\n // - We already probed for IMDS endpoint availability and failed-fast if it's unreachable.\n // We can proceed normally by calling MSAL for a token.\n logger.getToken.info(\"Calling into MSAL for managed identity token.\");\n const token = await this.managedIdentityApp.acquireToken({\n resource,\n });\n\n this.ensureValidMsalToken(scopes, token, options);\n logger.getToken.info(formatSuccess(scopes));\n\n return {\n expiresOnTimestamp: token.expiresOn.getTime(),\n token: token.accessToken,\n refreshAfterTimestamp: token.refreshOn?.getTime(),\n };\n } catch (err: any) {\n logger.getToken.error(formatError(scopes, err));\n\n // AuthenticationRequiredError described as Error to enforce authentication after trying to retrieve a token silently.\n // TODO: why would this _ever_ happen considering we're not trying the silent request in this flow?\n if (err.name === \"AuthenticationRequiredError\") {\n throw err;\n }\n\n if (isNetworkError(err)) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Network unreachable. Message: ${err.message}`,\n { cause: err },\n );\n }\n\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Authentication failed. Message ${err.message}`,\n { cause: err },\n );\n }\n });\n }\n\n /**\n * Ensures the validity of the MSAL token\n */\n private ensureValidMsalToken(\n scopes: string | string[],\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions,\n ): asserts msalToken is ValidMsalToken {\n const createError = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw createError(\"No response.\");\n }\n if (!msalToken.expiresOn) {\n throw createError(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw createError(`Response had no \"accessToken\" property.`);\n }\n }\n}\n\nfunction isNetworkError(err: any): boolean {\n // MSAL error\n if (err.errorCode === \"network_error\") {\n return true;\n }\n\n // Probe errors\n if (err.code === \"ENETUNREACH\" || err.code === \"EHOSTUNREACH\") {\n return true;\n }\n\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n if (err.statusCode === 403 || err.code === 403) {\n if (err.message.includes(\"unreachable\")) {\n return true;\n }\n }\n\n return false;\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  import { WorkloadIdentityCredential } from "../workloadIdentityCredential";
4
4
  import { credentialLogger } from "../../util/logging";
5
5
  const msiName = "ManagedIdentityCredential - Token Exchange";
@@ -1 +1 @@
1
- {"version":3,"file":"tokenExchangeMsi.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/tokenExchangeMsi.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAGtD,MAAM,OAAO,GAAG,4CAA4C,CAAC;AAC7D,MAAM,MAAM,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAEzC;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAQ;IACnC,IAAI,EAAE,kBAAkB;IACxB,KAAK,CAAC,WAAW,CAAC,EAAE,QAAQ,EAAE;QAC5B,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;QACxB,MAAM,MAAM,GAAG,OAAO,CACpB,CAAC,QAAQ,IAAI,GAAG,CAAC,eAAe,CAAC;YAC/B,GAAG,CAAC,eAAe;YACnB,OAAO,CAAC,GAAG,CAAC,0BAA0B,CACzC,CAAC;QACF,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,CAAC,IAAI,CACT,GAAG,OAAO,qKAAqK,CAChL,CAAC;QACJ,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,KAAK,CAAC,QAAQ,CACZ,aAA+B,EAC/B,kBAAmC,EAAE;QAErC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,aAAa,CAAC;QAC3C,MAAM,oCAAoC,GAAG,EAAE,CAAC;QAChD,MAAM,0BAA0B,GAAG,IAAI,0BAA0B,CAAC,8BAChE,QAAQ,EACR,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,eAAe,EACrC,aAAa,EAAE,OAAO,CAAC,GAAG,CAAC,0BAA0B,IAClD,oCAAoC,KACvC,wBAAwB,EAAE,IAAI,GACM,CAAC,CAAC;QACxC,OAAO,0BAA0B,CAAC,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IACtE,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { MSI, MSIConfiguration } from \"./models\";\nimport { WorkloadIdentityCredential } from \"../workloadIdentityCredential\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { WorkloadIdentityCredentialOptions } from \"../workloadIdentityCredentialOptions\";\n\nconst msiName = \"ManagedIdentityCredential - Token Exchange\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Defines how to determine whether the token exchange MSI is available, and also how to retrieve a token from the token exchange MSI.\n */\nexport const tokenExchangeMsi: MSI = {\n name: \"tokenExchangeMsi\",\n async isAvailable({ clientId }): Promise<boolean> {\n const env = process.env;\n const result = Boolean(\n (clientId || env.AZURE_CLIENT_ID) &&\n env.AZURE_TENANT_ID &&\n process.env.AZURE_FEDERATED_TOKEN_FILE,\n );\n if (!result) {\n logger.info(\n `${msiName}: Unavailable. The environment variables needed are: AZURE_CLIENT_ID (or the client ID sent through the parameters), AZURE_TENANT_ID and AZURE_FEDERATED_TOKEN_FILE`,\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {},\n ): Promise<AccessToken | null> {\n const { scopes, clientId } = configuration;\n const identityClientTokenCredentialOptions = {};\n const workloadIdentityCredential = new WorkloadIdentityCredential({\n clientId,\n tenantId: process.env.AZURE_TENANT_ID,\n tokenFilePath: process.env.AZURE_FEDERATED_TOKEN_FILE,\n ...identityClientTokenCredentialOptions,\n disableInstanceDiscovery: true,\n } as WorkloadIdentityCredentialOptions);\n return workloadIdentityCredential.getToken(scopes, getTokenOptions);\n },\n};\n"]}
1
+ {"version":3,"file":"tokenExchangeMsi.js","sourceRoot":"","sources":["../../../../src/credentials/managedIdentityCredential/tokenExchangeMsi.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAGtD,MAAM,OAAO,GAAG,4CAA4C,CAAC;AAC7D,MAAM,MAAM,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAEzC;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAQ;IACnC,IAAI,EAAE,kBAAkB;IACxB,KAAK,CAAC,WAAW,CAAC,EAAE,QAAQ,EAAE;QAC5B,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;QACxB,MAAM,MAAM,GAAG,OAAO,CACpB,CAAC,QAAQ,IAAI,GAAG,CAAC,eAAe,CAAC;YAC/B,GAAG,CAAC,eAAe;YACnB,OAAO,CAAC,GAAG,CAAC,0BAA0B,CACzC,CAAC;QACF,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,CAAC,IAAI,CACT,GAAG,OAAO,qKAAqK,CAChL,CAAC;QACJ,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,KAAK,CAAC,QAAQ,CACZ,aAA+B,EAC/B,kBAAmC,EAAE;QAErC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,aAAa,CAAC;QAC3C,MAAM,oCAAoC,GAAG,EAAE,CAAC;QAChD,MAAM,0BAA0B,GAAG,IAAI,0BAA0B,CAAC,8BAChE,QAAQ,EACR,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,eAAe,EACrC,aAAa,EAAE,OAAO,CAAC,GAAG,CAAC,0BAA0B,IAClD,oCAAoC,KACvC,wBAAwB,EAAE,IAAI,GACM,CAAC,CAAC;QACxC,OAAO,0BAA0B,CAAC,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IACtE,CAAC;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { MSI, MSIConfiguration } from \"./models\";\nimport { WorkloadIdentityCredential } from \"../workloadIdentityCredential\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { WorkloadIdentityCredentialOptions } from \"../workloadIdentityCredentialOptions\";\n\nconst msiName = \"ManagedIdentityCredential - Token Exchange\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Defines how to determine whether the token exchange MSI is available, and also how to retrieve a token from the token exchange MSI.\n */\nexport const tokenExchangeMsi: MSI = {\n name: \"tokenExchangeMsi\",\n async isAvailable({ clientId }): Promise<boolean> {\n const env = process.env;\n const result = Boolean(\n (clientId || env.AZURE_CLIENT_ID) &&\n env.AZURE_TENANT_ID &&\n process.env.AZURE_FEDERATED_TOKEN_FILE,\n );\n if (!result) {\n logger.info(\n `${msiName}: Unavailable. The environment variables needed are: AZURE_CLIENT_ID (or the client ID sent through the parameters), AZURE_TENANT_ID and AZURE_FEDERATED_TOKEN_FILE`,\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {},\n ): Promise<AccessToken | null> {\n const { scopes, clientId } = configuration;\n const identityClientTokenCredentialOptions = {};\n const workloadIdentityCredential = new WorkloadIdentityCredential({\n clientId,\n tenantId: process.env.AZURE_TENANT_ID,\n tokenFilePath: process.env.AZURE_FEDERATED_TOKEN_FILE,\n ...identityClientTokenCredentialOptions,\n disableInstanceDiscovery: true,\n } as WorkloadIdentityCredentialOptions);\n return workloadIdentityCredential.getToken(scopes, getTokenOptions);\n },\n};\n"]}