rebase: bump the github-dependencies group with 2 updates

Bumps the github-dependencies group with 2 updates: [github.com/aws/aws-sdk-go-v2/service/sts](https://github.com/aws/aws-sdk-go-v2) and [github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://github.com/Azure/azure-sdk-for-go).


Updates `github.com/aws/aws-sdk-go-v2/service/sts` from 1.32.1 to 1.32.2
- [Release notes](https://github.com/aws/aws-sdk-go-v2/releases)
- [Commits](https://github.com/aws/aws-sdk-go-v2/compare/v1.32.1...v1.32.2)

Updates `github.com/Azure/azure-sdk-for-go/sdk/azidentity` from 1.7.0 to 1.8.0
- [Release notes](https://github.com/Azure/azure-sdk-for-go/releases)
- [Changelog](https://github.com/Azure/azure-sdk-for-go/blob/main/documentation/release.md)
- [Commits](https://github.com/Azure/azure-sdk-for-go/compare/sdk/azcore/v1.7.0...sdk/azcore/v1.8.0)

---
updated-dependencies:
- dependency-name: github.com/aws/aws-sdk-go-v2/service/sts
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: github-dependencies
- dependency-name: github.com/Azure/azure-sdk-for-go/sdk/azidentity
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
This commit is contained in:
dependabot[bot] 2024-10-14 20:55:15 +00:00 committed by mergify[bot]
parent d1c28fa57a
commit e75fec74f9
59 changed files with 734 additions and 414 deletions

16
go.mod
View File

@ -5,7 +5,7 @@ go 1.22.5
require ( require (
github.com/IBM/keyprotect-go-client v0.15.1 github.com/IBM/keyprotect-go-client v0.15.1
github.com/aws/aws-sdk-go v1.55.5 github.com/aws/aws-sdk-go v1.55.5
github.com/aws/aws-sdk-go-v2/service/sts v1.32.1 github.com/aws/aws-sdk-go-v2/service/sts v1.32.2
github.com/ceph/ceph-csi/api v0.0.0-00010101000000-000000000000 github.com/ceph/ceph-csi/api v0.0.0-00010101000000-000000000000
github.com/ceph/go-ceph v0.29.1-0.20240925141413-065319c78733 github.com/ceph/go-ceph v0.29.1-0.20240925141413-065319c78733
github.com/container-storage-interface/spec v1.10.0 github.com/container-storage-interface/spec v1.10.0
@ -46,13 +46,13 @@ require (
) )
require ( require (
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.1.0 github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.1.0
) )
require ( require (
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.11.1 // indirect github.com/Azure/azure-sdk-for-go/sdk/azcore v1.14.0 // indirect
github.com/Azure/azure-sdk-for-go/sdk/internal v1.8.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.0.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.0.0 // indirect
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 // indirect github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 // indirect
github.com/NYTimes/gziphandler v1.1.1 // indirect github.com/NYTimes/gziphandler v1.1.1 // indirect
@ -60,11 +60,11 @@ require (
github.com/ansel1/merry/v2 v2.0.1 // indirect github.com/ansel1/merry/v2 v2.0.1 // indirect
github.com/antlr4-go/antlr/v4 v4.13.0 // indirect github.com/antlr4-go/antlr/v4 v4.13.0 // indirect
github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a // indirect github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a // indirect
github.com/aws/aws-sdk-go-v2 v1.32.1 // indirect github.com/aws/aws-sdk-go-v2 v1.32.2 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.20 // indirect github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.21 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.20 // indirect github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.21 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.0 // indirect github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.0 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.1 // indirect github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.2 // indirect
github.com/aws/smithy-go v1.22.0 // indirect github.com/aws/smithy-go v1.22.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect github.com/beorn7/perks v1.0.1 // indirect
github.com/blang/semver/v4 v4.0.0 // indirect github.com/blang/semver/v4 v4.0.0 // indirect

43
go.sum
View File

@ -1318,13 +1318,16 @@ cloud.google.com/go/workflows v1.12.4/go.mod h1:yQ7HUqOkdJK4duVtMeBCAOPiN1ZF1E9p
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
gioui.org v0.0.0-20210308172011-57750fc8a0a6/go.mod h1:RSH6KIUZ0p2xy5zHDxgAM4zumjgTw83q2ge/PI+yyw8= gioui.org v0.0.0-20210308172011-57750fc8a0a6/go.mod h1:RSH6KIUZ0p2xy5zHDxgAM4zumjgTw83q2ge/PI+yyw8=
git.sr.ht/~sbinet/gg v0.3.1/go.mod h1:KGYtlADtqsqANL9ueOFkWymvzUvLMQllU5Ixo+8v3pc= git.sr.ht/~sbinet/gg v0.3.1/go.mod h1:KGYtlADtqsqANL9ueOFkWymvzUvLMQllU5Ixo+8v3pc=
github.com/Azure/azure-sdk-for-go v62.0.0+incompatible h1:8N2k27SYtc12qj5nTsuFMFJPZn5CGmgMWqTy4y9I7Jw=
github.com/Azure/azure-sdk-for-go v62.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/azure-sdk-for-go v62.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.11.1 h1:E+OJmp2tPvt1W+amx48v1eqbjDYsgN+RzP4q16yV5eM= github.com/Azure/azure-sdk-for-go/sdk/azcore v1.14.0 h1:nyQWyZvwGTvunIMxi1Y9uXkcyr+I7TeNrr/foo4Kpk8=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.11.1/go.mod h1:a6xsAQUZg+VsS3TJ05SRp524Hs4pZ/AeFSr5ENf0Yjo= github.com/Azure/azure-sdk-for-go/sdk/azcore v1.14.0/go.mod h1:l38EPgmsp71HHLq9j7De57JcKOWPyhrsW1Awm1JS6K0=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 h1:tfLQ34V6F7tVSwoTf/4lH5sE0o6eCJuNDTmH09nDpbc= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0 h1:B/dfvscEQtew9dVuoxqxrUKKv8Ih2f55PydknDamU+g=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0/go.mod h1:9kIvujWAA58nmPmWB1m23fyWic1kYZMxD9CxaWn4Qpg= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0/go.mod h1:fiPSssYvltE08HJchL04dOy+RD4hgrjph0cwGGMntdI=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.8.0 h1:jBQA3cKT4L2rWMpgE7Yt3Hwh2aUj8KXjIGLxjHeYNNo= github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.0 h1:+m0M/LFxN43KvULkDNfdXOgrjtg6UYJPFBJyuEcRCAw=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.8.0/go.mod h1:4OG6tQ9EOP/MT0NMjDlRzWoVFxfu9rN9B2X+tlSVktg= github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.0/go.mod h1:PwOyop78lveYMRs6oCxjiVyBdyCgIYH6XHIVZO9/SFQ=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 h1:ywEEhmNahHBihViHepv3xPBn1663uRv2t2q/ESv9seY=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0/go.mod h1:iZDifYGJTIgIIkYRNWPENUnqx6bJ2xnSDFI2tjwZNuY=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.1.0 h1:h4Zxgmi9oyZL2l8jeg1iRTqPloHktywWcu0nlJmo1tA= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.1.0 h1:h4Zxgmi9oyZL2l8jeg1iRTqPloHktywWcu0nlJmo1tA=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.1.0/go.mod h1:LgLGXawqSreJz135Elog0ywTJDsm0Hz2k+N+6ZK35u8= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.1.0/go.mod h1:LgLGXawqSreJz135Elog0ywTJDsm0Hz2k+N+6ZK35u8=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.0.0 h1:D3occbWoio4EBLkbkevetNMAVX197GkzbUMtqjGWn80= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.0.0 h1:D3occbWoio4EBLkbkevetNMAVX197GkzbUMtqjGWn80=
@ -1341,6 +1344,8 @@ github.com/Azure/go-autorest/autorest/to v0.4.0/go.mod h1:fE8iZBn7LQR7zH/9XU2NcP
github.com/Azure/go-autorest/autorest/validation v0.3.1/go.mod h1:yhLgjC0Wda5DYXl6JAsWyUe4KVNffhoDhG0zVzUMo3E= github.com/Azure/go-autorest/autorest/validation v0.3.1/go.mod h1:yhLgjC0Wda5DYXl6JAsWyUe4KVNffhoDhG0zVzUMo3E=
github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8=
github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU= github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU=
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM=
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE=
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 h1:XHOnouVk1mxXfQidrMEnLlPk9UMeRtyBTnEFtxkV0kU= github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 h1:XHOnouVk1mxXfQidrMEnLlPk9UMeRtyBTnEFtxkV0kU=
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
@ -1406,18 +1411,18 @@ github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:l
github.com/aws/aws-sdk-go v1.44.164/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= github.com/aws/aws-sdk-go v1.44.164/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI=
github.com/aws/aws-sdk-go v1.55.5 h1:KKUZBfBoyqy5d3swXyiC7Q76ic40rYcbqH7qjh59kzU= github.com/aws/aws-sdk-go v1.55.5 h1:KKUZBfBoyqy5d3swXyiC7Q76ic40rYcbqH7qjh59kzU=
github.com/aws/aws-sdk-go v1.55.5/go.mod h1:eRwEWoyTWFMVYVQzKMNHWP5/RV4xIUGMQfXQHfHkpNU= github.com/aws/aws-sdk-go v1.55.5/go.mod h1:eRwEWoyTWFMVYVQzKMNHWP5/RV4xIUGMQfXQHfHkpNU=
github.com/aws/aws-sdk-go-v2 v1.32.1 h1:8WuZ43ytA+TV6QEPT/R23mr7pWyI7bSSiEHdt9BS2Pw= github.com/aws/aws-sdk-go-v2 v1.32.2 h1:AkNLZEyYMLnx/Q/mSKkcMqwNFXMAvFto9bNsHqcTduI=
github.com/aws/aws-sdk-go-v2 v1.32.1/go.mod h1:2SK5n0a2karNTv5tbP1SjsX0uhttou00v/HpXKM1ZUo= github.com/aws/aws-sdk-go-v2 v1.32.2/go.mod h1:2SK5n0a2karNTv5tbP1SjsX0uhttou00v/HpXKM1ZUo=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.20 h1:OErdlGnt+hg3tTwGYAlKvFkKVUo/TXkoHcxDxuhYYU8= github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.21 h1:UAsR3xA31QGf79WzpG/ixT9FZvQlh5HY1NRqSHBNOCk=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.20/go.mod h1:HsPfuL5gs+407ByRXBMgpYoyrV1sgMrzd18yMXQHJpo= github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.21/go.mod h1:JNr43NFf5L9YaG3eKTm7HQzls9J+A9YYcGI5Quh1r2Y=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.20 h1:822cE1CYSwY/EZnErlF46pyynuxvf1p+VydHRQW+XNs= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.21 h1:6jZVETqmYCadGFvrYEQfC5fAQmlo80CeL5psbno6r0s=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.20/go.mod h1:79/Tn7H7hYC5Gjz6fbnOV4OeBpkao7E8Tv95RO72pMM= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.21/go.mod h1:1SR0GbLlnN3QUmYaflZNiH1ql+1qrSiB2vwcJ+4UM60=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.0 h1:TToQNkvGguu209puTojY/ozlqy2d/SFNcoLIqTFi42g= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.0 h1:TToQNkvGguu209puTojY/ozlqy2d/SFNcoLIqTFi42g=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.0/go.mod h1:0jp+ltwkf+SwG2fm/PKo8t4y8pJSgOCO4D8Lz3k0aHQ= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.0/go.mod h1:0jp+ltwkf+SwG2fm/PKo8t4y8pJSgOCO4D8Lz3k0aHQ=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.1 h1:5vBMBTakOvtd8aNaicswcrr9qqCYUlasuzyoU6/0g8I= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.2 h1:s7NA1SOw8q/5c0wr8477yOPp0z+uBaXBnLE0XYb0POA=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.1/go.mod h1:WSUbDa5qdg05Q558KXx2Scb+EDvOPXT9gfET0fyrJSk= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.2/go.mod h1:fnjjWyAW/Pj5HYOxl9LJqWtEwS7W2qgcRLWP+uWbss0=
github.com/aws/aws-sdk-go-v2/service/sts v1.32.1 h1:q76Ig4OaJzVJGNUSGO3wjSTBS94g+EhHIbpY9rPvkxs= github.com/aws/aws-sdk-go-v2/service/sts v1.32.2 h1:CiS7i0+FUe+/YY1GvIBLLrR/XNGZ4CtM1Ll0XavNuVo=
github.com/aws/aws-sdk-go-v2/service/sts v1.32.1/go.mod h1:664dajZ7uS7JMUMUG0R5bWbtN97KECNCVdFDdQ6Ipu8= github.com/aws/aws-sdk-go-v2/service/sts v1.32.2/go.mod h1:HtaiBI8CjYoNVde8arShXb94UbQQi9L4EMr6D+xGBwo=
github.com/aws/smithy-go v1.22.0 h1:uunKnWlcoL3zO7q+gG2Pk53joueEOsnNB28QdMsmiMM= github.com/aws/smithy-go v1.22.0 h1:uunKnWlcoL3zO7q+gG2Pk53joueEOsnNB28QdMsmiMM=
github.com/aws/smithy-go v1.22.0/go.mod h1:irrKGvNn1InZwb2d7fkIRNucdfwR8R+Ts3wxYa/cJHg= github.com/aws/smithy-go v1.22.0/go.mod h1:irrKGvNn1InZwb2d7fkIRNucdfwR8R+Ts3wxYa/cJHg=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
@ -1506,6 +1511,8 @@ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/distribution/reference v0.5.0 h1:/FUIFXtfc/x2gpa5/VGfiGLuOIdYa1t65IKK2OFGvA0= github.com/distribution/reference v0.5.0 h1:/FUIFXtfc/x2gpa5/VGfiGLuOIdYa1t65IKK2OFGvA0=
github.com/distribution/reference v0.5.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= github.com/distribution/reference v0.5.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
@ -1932,6 +1939,8 @@ github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E
github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k= github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k=
github.com/k0kubun/pp v2.3.0+incompatible/go.mod h1:GWse8YhT0p8pT4ir3ZgBbfZild3tgzSScAn6HmfYukg= github.com/k0kubun/pp v2.3.0+incompatible/go.mod h1:GWse8YhT0p8pT4ir3ZgBbfZild3tgzSScAn6HmfYukg=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
github.com/keybase/go-keychain v0.0.0-20231219164618-57a3676c3af6 h1:IsMZxCuZqKuao2vNdfD82fjjgPLfyHLpR41Z88viRWs=
github.com/keybase/go-keychain v0.0.0-20231219164618-57a3676c3af6/go.mod h1:3VeWNIJaW+O5xpRQbPp0Ybqu1vJd/pm7s2F473HRrkw=
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
@ -2198,6 +2207,8 @@ github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3c
github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
github.com/redis/go-redis/v9 v9.6.1 h1:HHDteefn6ZkTtY5fGUE8tj8uy85AHk6zP7CpzIAM0y4=
github.com/redis/go-redis/v9 v9.6.1/go.mod h1:0C0c6ycQsdpVNQpxb1njEQIqkx5UcsM8FJCQLgE9+RA=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=

View File

@ -1,5 +1,36 @@
# Release History # Release History
## 1.14.0 (2024-08-07)
### Features Added
* Added field `Attributes` to `runtime.StartSpanOptions` to simplify creating spans with attributes.
### Other Changes
* Include the HTTP verb and URL in `log.EventRetryPolicy` log entries so it's clear which operation is being retried.
## 1.13.0 (2024-07-16)
### Features Added
- Added runtime.NewRequestFromRequest(), allowing for a policy.Request to be created from an existing *http.Request.
## 1.12.0 (2024-06-06)
### Features Added
* Added field `StatusCodes` to `runtime.FetcherForNextLinkOptions` allowing for additional HTTP status codes indicating success.
* Added func `NewUUID` to the `runtime` package for generating UUIDs.
### Bugs Fixed
* Fixed an issue that prevented pollers using the `Operation-Location` strategy from unmarshaling the final result in some cases.
### Other Changes
* Updated dependencies.
## 1.11.1 (2024-04-02) ## 1.11.1 (2024-04-02)
### Bugs Fixed ### Bugs Fixed

View File

@ -192,7 +192,7 @@ func appendNext(parent *ResourceID, parts []string, id string) (*ResourceID, err
} }
if strings.EqualFold(parts[0], providersKey) && (len(parts) == 2 || strings.EqualFold(parts[2], providersKey)) { if strings.EqualFold(parts[0], providersKey) && (len(parts) == 2 || strings.EqualFold(parts[2], providersKey)) {
//provider resource can only be on a tenant or a subscription parent // provider resource can only be on a tenant or a subscription parent
if parent.ResourceType.String() != SubscriptionResourceType.String() && parent.ResourceType.String() != TenantResourceType.String() { if parent.ResourceType.String() != SubscriptionResourceType.String() && parent.ResourceType.String() != TenantResourceType.String() {
return nil, fmt.Errorf("invalid resource ID: %s", id) return nil, fmt.Errorf("invalid resource ID: %s", id)
} }

View File

@ -34,18 +34,22 @@ func NewPipeline(module, version string, cred azcore.TokenCredential, plOpts azr
InsecureAllowCredentialWithHTTP: options.InsecureAllowCredentialWithHTTP, InsecureAllowCredentialWithHTTP: options.InsecureAllowCredentialWithHTTP,
Scopes: []string{conf.Audience + "/.default"}, Scopes: []string{conf.Audience + "/.default"},
}) })
// we don't want to modify the underlying array in plOpts.PerRetry
perRetry := make([]azpolicy.Policy, len(plOpts.PerRetry), len(plOpts.PerRetry)+1) perRetry := make([]azpolicy.Policy, len(plOpts.PerRetry), len(plOpts.PerRetry)+1)
copy(perRetry, plOpts.PerRetry) copy(perRetry, plOpts.PerRetry)
plOpts.PerRetry = append(perRetry, authPolicy, exported.PolicyFunc(httpTraceNamespacePolicy)) perRetry = append(perRetry, authPolicy, exported.PolicyFunc(httpTraceNamespacePolicy))
plOpts.PerRetry = perRetry
if !options.DisableRPRegistration { if !options.DisableRPRegistration {
regRPOpts := armpolicy.RegistrationOptions{ClientOptions: options.ClientOptions} regRPOpts := armpolicy.RegistrationOptions{ClientOptions: options.ClientOptions}
regPolicy, err := NewRPRegistrationPolicy(cred, &regRPOpts) regPolicy, err := NewRPRegistrationPolicy(cred, &regRPOpts)
if err != nil { if err != nil {
return azruntime.Pipeline{}, err return azruntime.Pipeline{}, err
} }
// we don't want to modify the underlying array in plOpts.PerCall
perCall := make([]azpolicy.Policy, len(plOpts.PerCall), len(plOpts.PerCall)+1) perCall := make([]azpolicy.Policy, len(plOpts.PerCall), len(plOpts.PerCall)+1)
copy(perCall, plOpts.PerCall) copy(perCall, plOpts.PerCall)
plOpts.PerCall = append(perCall, regPolicy) perCall = append(perCall, regPolicy)
plOpts.PerCall = perCall
} }
if plOpts.APIVersion.Name == "" { if plOpts.APIVersion.Name == "" {
plOpts.APIVersion.Name = "api-version" plOpts.APIVersion.Name = "api-version"

View File

@ -7,6 +7,7 @@
package exported package exported
import ( import (
"bytes"
"context" "context"
"encoding/base64" "encoding/base64"
"errors" "errors"
@ -67,6 +68,42 @@ func (ov opValues) get(value any) bool {
return ok return ok
} }
// NewRequestFromRequest creates a new policy.Request with an existing *http.Request
// Exported as runtime.NewRequestFromRequest().
func NewRequestFromRequest(req *http.Request) (*Request, error) {
policyReq := &Request{req: req}
if req.Body != nil {
// we can avoid a body copy here if the underlying stream is already a
// ReadSeekCloser.
readSeekCloser, isReadSeekCloser := req.Body.(io.ReadSeekCloser)
if !isReadSeekCloser {
// since this is an already populated http.Request we want to copy
// over its body, if it has one.
bodyBytes, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
if err := req.Body.Close(); err != nil {
return nil, err
}
readSeekCloser = NopCloser(bytes.NewReader(bodyBytes))
}
// SetBody also takes care of updating the http.Request's body
// as well, so they should stay in-sync from this point.
if err := policyReq.SetBody(readSeekCloser, req.Header.Get("Content-Type")); err != nil {
return nil, err
}
}
return policyReq, nil
}
// NewRequest creates a new Request with the specified input. // NewRequest creates a new Request with the specified input.
// Exported as runtime.NewRequest(). // Exported as runtime.NewRequest().
func NewRequest(ctx context.Context, httpMethod string, endpoint string) (*Request, error) { func NewRequest(ctx context.Context, httpMethod string, endpoint string) (*Request, error) {

View File

@ -155,5 +155,5 @@ func (p *Poller[T]) Result(ctx context.Context, out *T) error {
p.resp = resp p.resp = resp
} }
return pollers.ResultHelper(p.resp, poller.Failed(p.CurState), out) return pollers.ResultHelper(p.resp, poller.Failed(p.CurState), "", out)
} }

View File

@ -131,5 +131,5 @@ func (p *Poller[T]) Poll(ctx context.Context) (*http.Response, error) {
} }
func (p *Poller[T]) Result(ctx context.Context, out *T) error { func (p *Poller[T]) Result(ctx context.Context, out *T) error {
return pollers.ResultHelper(p.resp, poller.Failed(p.CurState), out) return pollers.ResultHelper(p.resp, poller.Failed(p.CurState), "", out)
} }

View File

@ -124,7 +124,7 @@ func (p *Poller[T]) Result(ctx context.Context, out *T) error {
return exported.NewResponseError(p.resp) return exported.NewResponseError(p.resp)
} }
return pollers.ResultHelper(p.resp, poller.Failed(p.FakeStatus), out) return pollers.ResultHelper(p.resp, poller.Failed(p.FakeStatus), "", out)
} }
// SanitizePollerPath removes any fake-appended suffix from a URL's path. // SanitizePollerPath removes any fake-appended suffix from a URL's path.

View File

@ -119,5 +119,5 @@ func (p *Poller[T]) Poll(ctx context.Context) (*http.Response, error) {
} }
func (p *Poller[T]) Result(ctx context.Context, out *T) error { func (p *Poller[T]) Result(ctx context.Context, out *T) error {
return pollers.ResultHelper(p.resp, poller.Failed(p.CurState), out) return pollers.ResultHelper(p.resp, poller.Failed(p.CurState), "", out)
} }

View File

@ -115,10 +115,13 @@ func (p *Poller[T]) Poll(ctx context.Context) (*http.Response, error) {
func (p *Poller[T]) Result(ctx context.Context, out *T) error { func (p *Poller[T]) Result(ctx context.Context, out *T) error {
var req *exported.Request var req *exported.Request
var err error var err error
// when the payload is included with the status monitor on
// terminal success it's in the "result" JSON property
payloadPath := "result"
if p.FinalState == pollers.FinalStateViaLocation && p.LocURL != "" { if p.FinalState == pollers.FinalStateViaLocation && p.LocURL != "" {
req, err = exported.NewRequest(ctx, http.MethodGet, p.LocURL) req, err = exported.NewRequest(ctx, http.MethodGet, p.LocURL)
} else if p.FinalState == pollers.FinalStateViaOpLocation && p.Method == http.MethodPost {
// no final GET required, terminal response should have it
} else if rl, rlErr := poller.GetResourceLocation(p.resp); rlErr != nil && !errors.Is(rlErr, poller.ErrNoBody) { } else if rl, rlErr := poller.GetResourceLocation(p.resp); rlErr != nil && !errors.Is(rlErr, poller.ErrNoBody) {
return rlErr return rlErr
} else if rl != "" { } else if rl != "" {
@ -134,6 +137,8 @@ func (p *Poller[T]) Result(ctx context.Context, out *T) error {
// if a final GET request has been created, execute it // if a final GET request has been created, execute it
if req != nil { if req != nil {
// no JSON path when making a final GET request
payloadPath = ""
resp, err := p.pl.Do(req) resp, err := p.pl.Do(req)
if err != nil { if err != nil {
return err return err
@ -141,5 +146,5 @@ func (p *Poller[T]) Result(ctx context.Context, out *T) error {
p.resp = resp p.resp = resp
} }
return pollers.ResultHelper(p.resp, poller.Failed(p.CurState), out) return pollers.ResultHelper(p.resp, poller.Failed(p.CurState), payloadPath, out)
} }

View File

@ -159,7 +159,7 @@ func PollHelper(ctx context.Context, endpoint string, pl azexported.Pipeline, up
// ResultHelper processes the response as success or failure. // ResultHelper processes the response as success or failure.
// In the success case, it unmarshals the payload into either a new instance of T or out. // In the success case, it unmarshals the payload into either a new instance of T or out.
// In the failure case, it creates an *azcore.Response error from the response. // In the failure case, it creates an *azcore.Response error from the response.
func ResultHelper[T any](resp *http.Response, failed bool, out *T) error { func ResultHelper[T any](resp *http.Response, failed bool, jsonPath string, out *T) error {
// short-circuit the simple success case with no response body to unmarshal // short-circuit the simple success case with no response body to unmarshal
if resp.StatusCode == http.StatusNoContent { if resp.StatusCode == http.StatusNoContent {
return nil return nil
@ -176,6 +176,18 @@ func ResultHelper[T any](resp *http.Response, failed bool, out *T) error {
if err != nil { if err != nil {
return err return err
} }
if jsonPath != "" && len(payload) > 0 {
// extract the payload from the specified JSON path.
// do this before the zero-length check in case there
// is no payload.
jsonBody := map[string]json.RawMessage{}
if err = json.Unmarshal(payload, &jsonBody); err != nil {
return err
}
payload = jsonBody[jsonPath]
}
if len(payload) == 0 { if len(payload) == 0 {
return nil return nil
} }

View File

@ -40,5 +40,5 @@ const (
Module = "azcore" Module = "azcore"
// Version is the semantic version (see http://semver.org) of this module. // Version is the semantic version (see http://semver.org) of this module.
Version = "v1.11.1" Version = "v1.14.0"
) )

View File

@ -94,6 +94,10 @@ type FetcherForNextLinkOptions struct {
// NextReq is the func to be called when requesting subsequent pages. // NextReq is the func to be called when requesting subsequent pages.
// Used for paged operations that have a custom next link operation. // Used for paged operations that have a custom next link operation.
NextReq func(context.Context, string) (*policy.Request, error) NextReq func(context.Context, string) (*policy.Request, error)
// StatusCodes contains additional HTTP status codes indicating success.
// The default value is http.StatusOK.
StatusCodes []int
} }
// FetcherForNextLink is a helper containing boilerplate code to simplify creating a PagingHandler[T].Fetcher from a next link URL. // FetcherForNextLink is a helper containing boilerplate code to simplify creating a PagingHandler[T].Fetcher from a next link URL.
@ -105,10 +109,13 @@ type FetcherForNextLinkOptions struct {
func FetcherForNextLink(ctx context.Context, pl Pipeline, nextLink string, firstReq func(context.Context) (*policy.Request, error), options *FetcherForNextLinkOptions) (*http.Response, error) { func FetcherForNextLink(ctx context.Context, pl Pipeline, nextLink string, firstReq func(context.Context) (*policy.Request, error), options *FetcherForNextLinkOptions) (*http.Response, error) {
var req *policy.Request var req *policy.Request
var err error var err error
if options == nil {
options = &FetcherForNextLinkOptions{}
}
if nextLink == "" { if nextLink == "" {
req, err = firstReq(ctx) req, err = firstReq(ctx)
} else if nextLink, err = EncodeQueryParams(nextLink); err == nil { } else if nextLink, err = EncodeQueryParams(nextLink); err == nil {
if options != nil && options.NextReq != nil { if options.NextReq != nil {
req, err = options.NextReq(ctx, nextLink) req, err = options.NextReq(ctx, nextLink)
} else { } else {
req, err = NewRequest(ctx, http.MethodGet, nextLink) req, err = NewRequest(ctx, http.MethodGet, nextLink)
@ -121,7 +128,9 @@ func FetcherForNextLink(ctx context.Context, pl Pipeline, nextLink string, first
if err != nil { if err != nil {
return nil, err return nil, err
} }
if !HasStatusCode(resp, http.StatusOK) { successCodes := []int{http.StatusOK}
successCodes = append(successCodes, options.StatusCodes...)
if !HasStatusCode(resp, successCodes...) {
return nil, NewResponseError(resp) return nil, NewResponseError(resp)
} }
return resp, nil return resp, nil

View File

@ -96,7 +96,8 @@ func (h *httpTracePolicy) Do(req *policy.Request) (resp *http.Response, err erro
// StartSpanOptions contains the optional values for StartSpan. // StartSpanOptions contains the optional values for StartSpan.
type StartSpanOptions struct { type StartSpanOptions struct {
// for future expansion // Attributes contains key-value pairs of attributes for the span.
Attributes []tracing.Attribute
} }
// StartSpan starts a new tracing span. // StartSpan starts a new tracing span.
@ -126,8 +127,14 @@ func StartSpan(ctx context.Context, name string, tracer tracing.Tracer, options
return ctx, func(err error) {} return ctx, func(err error) {}
} }
} }
if options == nil {
options = &StartSpanOptions{}
}
ctx, span := tracer.Start(ctx, name, &tracing.SpanOptions{ ctx, span := tracer.Start(ctx, name, &tracing.SpanOptions{
Kind: newSpanKind, Kind: newSpanKind,
Attributes: options.Attributes,
}) })
ctx = context.WithValue(ctx, ctxActiveSpan{}, newSpanKind) ctx = context.WithValue(ctx, ctxActiveSpan{}, newSpanKind)
return ctx, func(err error) { return ctx, func(err error) {

View File

@ -102,7 +102,8 @@ func (p *retryPolicy) Do(req *policy.Request) (resp *http.Response, err error) {
try := int32(1) try := int32(1)
for { for {
resp = nil // reset resp = nil // reset
log.Writef(log.EventRetryPolicy, "=====> Try=%d", try) // unfortunately we don't have access to the custom allow-list of query params, so we'll redact everything but the default allowed QPs
log.Writef(log.EventRetryPolicy, "=====> Try=%d for %s %s", try, req.Raw().Method, getSanitizedURL(*req.Raw().URL, getAllowedQueryParams(nil)))
// For each try, seek to the beginning of the Body stream. We do this even for the 1st try because // For each try, seek to the beginning of the Body stream. We do this even for the 1st try because
// the stream may not be at offset 0 when we first get it and we want the same behavior for the // the stream may not be at offset 0 when we first get it and we want the same behavior for the

View File

@ -15,6 +15,7 @@ import (
"fmt" "fmt"
"io" "io"
"mime/multipart" "mime/multipart"
"net/http"
"net/textproto" "net/textproto"
"net/url" "net/url"
"path" "path"
@ -24,6 +25,7 @@ import (
"github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
"github.com/Azure/azure-sdk-for-go/sdk/internal/uuid"
) )
// Base64Encoding is usesd to specify which base-64 encoder/decoder to use when // Base64Encoding is usesd to specify which base-64 encoder/decoder to use when
@ -44,6 +46,11 @@ func NewRequest(ctx context.Context, httpMethod string, endpoint string) (*polic
return exported.NewRequest(ctx, httpMethod, endpoint) return exported.NewRequest(ctx, httpMethod, endpoint)
} }
// NewRequestFromRequest creates a new policy.Request with an existing *http.Request
func NewRequestFromRequest(req *http.Request) (*policy.Request, error) {
return exported.NewRequestFromRequest(req)
}
// EncodeQueryParams will parse and encode any query parameters in the specified URL. // EncodeQueryParams will parse and encode any query parameters in the specified URL.
// Any semicolons will automatically be escaped. // Any semicolons will automatically be escaped.
func EncodeQueryParams(u string) (string, error) { func EncodeQueryParams(u string) (string, error) {
@ -263,3 +270,12 @@ func SkipBodyDownload(req *policy.Request) {
// CtxAPINameKey is used as a context key for adding/retrieving the API name. // CtxAPINameKey is used as a context key for adding/retrieving the API name.
type CtxAPINameKey = shared.CtxAPINameKey type CtxAPINameKey = shared.CtxAPINameKey
// NewUUID returns a new UUID using the RFC4122 algorithm.
func NewUUID() (string, error) {
u, err := uuid.New()
if err != nil {
return "", err
}
return u.String(), nil
}

View File

@ -0,0 +1,10 @@
# Breaking Changes
## v1.6.0
### Behavioral change to `DefaultAzureCredential` in IMDS managed identity scenarios
As of `azidentity` v1.6.0, `DefaultAzureCredential` makes a minor behavioral change when it uses IMDS managed
identity. It sends its first request to IMDS without the "Metadata" header, to expedite validating whether the endpoint
is available. This precedes the credential's first token request and is guaranteed to fail with a 400 error. This error
response can appear in logs but doesn't indicate authentication failed.

View File

@ -1,5 +1,52 @@
# Release History # Release History
## 1.8.0 (2024-10-08)
### Other Changes
* `AzurePipelinesCredential` sets an additional OIDC request header so that it
receives a 401 instead of a 302 after presenting an invalid system access token
* Allow logging of debugging headers for `AzurePipelinesCredential` and include
them in error messages
## 1.8.0-beta.3 (2024-09-17)
### Features Added
* Added `ObjectID` type for `ManagedIdentityCredentialOptions.ID`
### Other Changes
* Removed redundant content from error messages
## 1.8.0-beta.2 (2024-08-06)
### Breaking Changes
* `NewManagedIdentityCredential` now returns an error when a user-assigned identity
is specified on a platform whose managed identity API doesn't support that.
`ManagedIdentityCredential.GetToken()` formerly logged a warning in these cases.
Returning an error instead prevents the credential authenticating an unexpected
identity, causing a client to act with unexpected privileges. The affected
platforms are:
* Azure Arc
* Azure ML (when a resource ID is specified; client IDs are supported)
* Cloud Shell
* Service Fabric
### Other Changes
* If `DefaultAzureCredential` receives a non-JSON response when probing IMDS before
attempting to authenticate a managed identity, it continues to the next credential
in the chain instead of immediately returning an error.
## 1.8.0-beta.1 (2024-07-17)
### Features Added
* Restored persistent token caching feature
### Breaking Changes
> These changes affect only code written against a beta version such as v1.7.0-beta.1
* Redesigned the persistent caching API. Encryption is now required in all cases
and persistent cache construction is separate from credential construction.
The `PersistentUserAuthentication` example in the package docs has been updated
to demonstrate the new API.
## 1.7.0 (2024-06-20) ## 1.7.0 (2024-06-20)
### Features Added ### Features Added

View File

@ -54,7 +54,7 @@ The `azidentity` module focuses on OAuth authentication with Microsoft Entra ID.
### DefaultAzureCredential ### DefaultAzureCredential
`DefaultAzureCredential` is appropriate for most apps that will be deployed to Azure. It combines common production credentials with development credentials. It attempts to authenticate via the following mechanisms in this order, stopping when one succeeds: `DefaultAzureCredential` simplifies authentication while developing applications that deploy to Azure by combining credentials used in Azure hosting environments and credentials used in local development. In production, it's better to use a specific credential type so authentication is more predictable and easier to debug. `DefaultAzureCredential` attempts to authenticate via the following mechanisms in this order, stopping when one succeeds:
![DefaultAzureCredential authentication flow](img/mermaidjs/DefaultAzureCredentialAuthFlow.svg) ![DefaultAzureCredential authentication flow](img/mermaidjs/DefaultAzureCredentialAuthFlow.svg)
@ -126,12 +126,17 @@ client := armresources.NewResourceGroupsClient("subscription ID", chain, nil)
## Credential Types ## Credential Types
### Authenticating Azure Hosted Applications ### Credential chains
|Credential|Usage |Credential|Usage
|-|- |-|-
|[DefaultAzureCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#DefaultAzureCredential)|Simplified authentication experience for getting started developing Azure apps |[DefaultAzureCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#DefaultAzureCredential)|Simplified authentication experience for getting started developing Azure apps
|[ChainedTokenCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ChainedTokenCredential)|Define custom authentication flows, composing multiple credentials |[ChainedTokenCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ChainedTokenCredential)|Define custom authentication flows, composing multiple credentials
### Authenticating Azure-Hosted Applications
|Credential|Usage
|-|-
|[EnvironmentCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#EnvironmentCredential)|Authenticate a service principal or user configured by environment variables |[EnvironmentCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#EnvironmentCredential)|Authenticate a service principal or user configured by environment variables
|[ManagedIdentityCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ManagedIdentityCredential)|Authenticate the managed identity of an Azure resource |[ManagedIdentityCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ManagedIdentityCredential)|Authenticate the managed identity of an Azure resource
|[WorkloadIdentityCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#WorkloadIdentityCredential)|Authenticate a workload identity on Kubernetes |[WorkloadIdentityCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#WorkloadIdentityCredential)|Authenticate a workload identity on Kubernetes
@ -158,7 +163,7 @@ client := armresources.NewResourceGroupsClient("subscription ID", chain, nil)
|Credential|Usage |Credential|Usage
|-|- |-|-
|[AzureCLICredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#AzureCLICredential)|Authenticate as the user signed in to the Azure CLI |[AzureCLICredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#AzureCLICredential)|Authenticate as the user signed in to the Azure CLI
|[`AzureDeveloperCLICredential`](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#AzureDeveloperCLICredential)|Authenticates as the user signed in to the Azure Developer CLI |[AzureDeveloperCLICredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#AzureDeveloperCLICredential)|Authenticates as the user signed in to the Azure Developer CLI
## Environment Variables ## Environment Variables

View File

@ -1,57 +1,40 @@
## Token caching in the Azure Identity client module ## Token caching in the Azure Identity client module
*Token caching* is a feature provided by the Azure Identity library that allows apps to: Token caching helps apps:
- Improve their resilience and performance. - Improve their resilience and performance.
- Reduce the number of requests made to Microsoft Entra ID to obtain access tokens. - Reduce the number of requests sent to Microsoft Entra ID to obtain access tokens.
- Reduce the number of times the user is prompted to authenticate. - Reduce the number of times users are prompted to authenticate.
When an app needs to access a protected Azure resource, it typically needs to obtain an access token from Entra ID. Obtaining that token involves sending a request to Entra ID and may also involve prompting the user. Entra ID then validates the credentials provided in the request and issues an access token. When an app needs to access a protected Azure resource, it typically needs to obtain an access token from Entra ID by sending an HTTP request and sometimes prompting a user to authenticate interactively. Credentials with caches (see [the below table](#credentials-supporting-token-caching) for a list) store access tokens either [in memory](#in-memory-token-caching) or, optionally, [on disk](#persistent-token-caching). These credentials return cached tokens whenever possible, to avoid unnecessary token requests or user interaction. Both cache implementations are safe for concurrent use.
Token caching, via the Azure Identity library, allows the app to store this access token [in memory](#in-memory-token-caching), where it's accessible to the current process, or [on disk](#persistent-token-caching) where it can be accessed across application or process invocations. The token can then be retrieved quickly and easily the next time the app needs to access the same resource. The app can avoid making another request to Entra ID, which reduces network traffic and improves resilience. Additionally, in scenarios where the app is authenticating users, token caching also avoids prompting the user each time new tokens are requested. #### Caching can't be disabled
Whether a credential caches tokens isn't configurable. If a credential has a cache of either kind, it requests a new token only when it can't provide one from its cache. Azure SDK service clients have an additional, independent layer of in-memory token caching, to prevent redundant token requests. This cache works with any credential type, even a custom implementation defined outside the Azure SDK, and can't be disabled. Disabling token caching is therefore impossible when using Azure SDK clients or most `azidentity` credential types. However, in-memory caches can be cleared by constructing new credential and client instances.
### In-memory token caching ### In-memory token caching
*In-memory token caching* is the default option provided by the Azure Identity library. This caching approach allows apps to store access tokens in memory. With in-memory token caching, the library first determines if a valid access token for the requested resource is already stored in memory. If a valid token is found, it's returned to the app without the need to make another request to Entra ID. If a valid token isn't found, the library will automatically acquire a token by sending a request to Entra ID. The in-memory token cache provided by the Azure Identity library is thread-safe. Credential types that support caching store tokens in memory by default and require no configuration to do so. Each instance of these types has its own cache, and two credential instances never share an in-memory cache.
**Note:** When Azure Identity library credentials are used with Azure service libraries (for example, Azure Blob Storage), the in-memory token caching is active in the `Pipeline` layer as well. All `TokenCredential` implementations are supported there, including custom implementations external to the Azure Identity library.
#### Caching cannot be disabled
As there are many levels of caching, it's not possible disable in-memory caching. However, the in-memory cache may be cleared by creating a new credential instance.
### Persistent token caching ### Persistent token caching
> Only azidentity v1.5.0-beta versions support persistent token caching Some credential types support opt-in persistent token caching (see [the below table](#credentials-supporting-token-caching) for a list). This feature enables credentials to store and retrieve tokens across process executions, so an application doesn't need to authenticate every time it runs.
*Persistent disk token caching* is an opt-in feature in the Azure Identity library. The feature allows apps to cache access tokens in an encrypted, persistent storage mechanism. As indicated in the following table, the storage mechanism differs across operating systems. Persistent caches are encrypted at rest using a mechanism that depends on the operating system:
| Operating system | Storage mechanism | | Operating system | Encryption facility |
|------------------|---------------------------------------| |------------------|---------------------------------------|
| Linux | kernel key retention service (keyctl) | | Linux | kernel key retention service (keyctl) |
| macOS | Keychain | | macOS | Keychain |
| Windows | DPAPI | | Windows | Data Protection API (DPAPI) |
By default the token cache will protect any data which is persisted using the user data protection APIs available on the current platform. Persistent caching requires encryption. When the required encryption facility is unuseable, or the application is running on an unsupported OS, the persistent cache constructor returns an error. This doesn't mean that authentication is impossible, only that credentials can't persist authentication data and the application will need to reauthenticate the next time it runs. See the [package documentation][example] for example code showing how to configure persistent caching and access cached data.
However, there are cases where no data protection is available, and applications may choose to allow storing the token cache in an unencrypted state by setting `TokenCachePersistenceOptions.AllowUnencryptedStorage` to `true`. This allows a credential to fall back to unencrypted storage if it can't encrypt the cache. However, we do not recommend using this storage method due to its significantly lower security measures. In addition, tokens are not encrypted solely to the current user, which could potentially allow unauthorized access to the cache by individuals with machine access.
With persistent disk token caching enabled, the library first determines if a valid access token for the requested resource is already stored in the persistent cache. If a valid token is found, it's returned to the app without the need to make another request to Entra ID. Additionally, the tokens are preserved across app runs, which:
- Makes the app more resilient to failures.
- Ensures the app can continue to function during an Entra ID outage or disruption.
- Avoids having to prompt users to authenticate each time the process is restarted.
>IMPORTANT! The token cache contains sensitive data and **MUST** be protected to prevent compromising accounts. All application decisions regarding the persistence of the token cache must consider that a breach of its content will fully compromise all the accounts it contains.
#### Example code
See the [package documentation](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity@v1.6.0-beta.2#pkg-overview) for example code demonstrating how to configure persistent caching and access cached data.
### Credentials supporting token caching ### Credentials supporting token caching
The following table indicates the state of in-memory and persistent caching in each credential type. The following table indicates the state of in-memory and persistent caching in each credential type.
**Note:** In-memory caching is activated by default. Persistent token caching needs to be enabled as shown in [this example](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity@v1.5.0-beta.1#example-package-PersistentCache). **Note:** in-memory caching is enabled by default for every type supporting it. Persistent token caching must be enabled explicitly. See the [package documentation][user_example] for an example showing how to do this for credential types authenticating users. For types that authenticate service principals, set the `Cache` field on the constructor's options as shown in [this example][sp_example].
| Credential | In-memory token caching | Persistent token caching | | Credential | In-memory token caching | Persistent token caching |
|--------------------------------|---------------------------------------------------------------------|--------------------------| |--------------------------------|---------------------------------------------------------------------|--------------------------|
@ -66,6 +49,9 @@ The following table indicates the state of in-memory and persistent caching in e
| `EnvironmentCredential` | Supported | Not Supported | | `EnvironmentCredential` | Supported | Not Supported |
| `InteractiveBrowserCredential` | Supported | Supported | | `InteractiveBrowserCredential` | Supported | Supported |
| `ManagedIdentityCredential` | Supported | Not Supported | | `ManagedIdentityCredential` | Supported | Not Supported |
| `OnBehalfOfCredential` | Supported | Supported | | `OnBehalfOfCredential` | Supported | Not Supported |
| `UsernamePasswordCredential` | Supported | Supported | | `UsernamePasswordCredential` | Supported | Supported |
| `WorkloadIdentityCredential` | Supported | Supported | | `WorkloadIdentityCredential` | Supported | Supported |
[sp_example]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#example-package-PersistentServicePrincipalAuthentication
[user_example]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#example-package-PersistentUserAuthentication

View File

@ -234,7 +234,7 @@ azd auth token --output json --scope https://management.core.windows.net/.defaul
|---|---|---| |---|---|---|
| AADSTS900023: Specified tenant identifier 'some tenant ID' is neither a valid DNS name, nor a valid external domain.|The `tenantID` argument to `NewAzurePipelinesCredential` is incorrect| Verify the tenant ID. It must identify the tenant of the user-assigned managed identity or service principal configured for the service connection.| | AADSTS900023: Specified tenant identifier 'some tenant ID' is neither a valid DNS name, nor a valid external domain.|The `tenantID` argument to `NewAzurePipelinesCredential` is incorrect| Verify the tenant ID. It must identify the tenant of the user-assigned managed identity or service principal configured for the service connection.|
| No service connection found with identifier |The `serviceConnectionID` argument to `NewAzurePipelinesCredential` is incorrect| Verify the service connection ID. This parameter refers to the `resourceId` of the Azure Service Connection. It can also be found in the query string of the service connection's configuration in Azure DevOps. [Azure Pipelines documentation](https://learn.microsoft.com/azure/devops/pipelines/library/service-endpoints?view=azure-devops&tabs=yaml) has more information about service connections.| | No service connection found with identifier |The `serviceConnectionID` argument to `NewAzurePipelinesCredential` is incorrect| Verify the service connection ID. This parameter refers to the `resourceId` of the Azure Service Connection. It can also be found in the query string of the service connection's configuration in Azure DevOps. [Azure Pipelines documentation](https://learn.microsoft.com/azure/devops/pipelines/library/service-endpoints?view=azure-devops&tabs=yaml) has more information about service connections.|
|302 (Found) response from OIDC endpoint|The `systemAccessToken` argument to `NewAzurePipelinesCredential` is incorrect|Check pipeline configuration. This value comes from the predefined variable `System.AccessToken` [as described in Azure Pipelines documentation](https://learn.microsoft.com/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml#systemaccesstoken).| |401 (Unauthorized) response from OIDC endpoint|The `systemAccessToken` argument to `NewAzurePipelinesCredential` is incorrect|Check pipeline configuration. This value comes from the predefined variable `System.AccessToken` [as described in Azure Pipelines documentation](https://learn.microsoft.com/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml#systemaccesstoken).|
## Get additional help ## Get additional help

View File

@ -2,5 +2,5 @@
"AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepo": "Azure/azure-sdk-assets",
"AssetsRepoPrefixPath": "go", "AssetsRepoPrefixPath": "go",
"TagPrefix": "go/azidentity", "TagPrefix": "go/azidentity",
"Tag": "go/azidentity_087379b475" "Tag": "go/azidentity_c55452bbf6"
} }

View File

@ -18,10 +18,10 @@ import (
var supportedAuthRecordVersions = []string{"1.0"} var supportedAuthRecordVersions = []string{"1.0"}
// authenticationRecord is non-secret account information about an authenticated user that user credentials such as // AuthenticationRecord is non-secret account information about an authenticated user that user credentials such as
// [DeviceCodeCredential] and [InteractiveBrowserCredential] can use to access previously cached authentication // [DeviceCodeCredential] and [InteractiveBrowserCredential] can use to access previously cached authentication
// data. Call these credentials' Authenticate method to get an authenticationRecord for a user. // data. Call these credentials' Authenticate method to get an AuthenticationRecord for a user.
type authenticationRecord struct { type AuthenticationRecord struct {
// Authority is the URL of the authority that issued the token. // Authority is the URL of the authority that issued the token.
Authority string `json:"authority"` Authority string `json:"authority"`
@ -42,11 +42,11 @@ type authenticationRecord struct {
} }
// UnmarshalJSON implements json.Unmarshaler for AuthenticationRecord // UnmarshalJSON implements json.Unmarshaler for AuthenticationRecord
func (a *authenticationRecord) UnmarshalJSON(b []byte) error { func (a *AuthenticationRecord) UnmarshalJSON(b []byte) error {
// Default unmarshaling is fine but we want to return an error if the record's version isn't supported i.e., we // Default unmarshaling is fine but we want to return an error if the record's version isn't supported i.e., we
// want to inspect the unmarshalled values before deciding whether to return an error. Unmarshaling a formally // want to inspect the unmarshalled values before deciding whether to return an error. Unmarshaling a formally
// different type enables this by assigning all the fields without recursing into this method. // different type enables this by assigning all the fields without recursing into this method.
type r authenticationRecord type r AuthenticationRecord
err := json.Unmarshal(b, (*r)(a)) err := json.Unmarshal(b, (*r)(a))
if err != nil { if err != nil {
return err return err
@ -63,7 +63,7 @@ func (a *authenticationRecord) UnmarshalJSON(b []byte) error {
} }
// account returns the AuthenticationRecord as an MSAL Account. The account is zero-valued when the AuthenticationRecord is zero-valued. // account returns the AuthenticationRecord as an MSAL Account. The account is zero-valued when the AuthenticationRecord is zero-valued.
func (a *authenticationRecord) account() public.Account { func (a *AuthenticationRecord) account() public.Account {
return public.Account{ return public.Account{
Environment: a.Authority, Environment: a.Authority,
HomeAccountID: a.HomeAccountID, HomeAccountID: a.HomeAccountID,
@ -71,10 +71,10 @@ func (a *authenticationRecord) account() public.Account {
} }
} }
func newAuthenticationRecord(ar public.AuthResult) (authenticationRecord, error) { func newAuthenticationRecord(ar public.AuthResult) (AuthenticationRecord, error) {
u, err := url.Parse(ar.IDToken.Issuer) u, err := url.Parse(ar.IDToken.Issuer)
if err != nil { if err != nil {
return authenticationRecord{}, fmt.Errorf("Authenticate expected a URL issuer but got %q", ar.IDToken.Issuer) return AuthenticationRecord{}, fmt.Errorf("Authenticate expected a URL issuer but got %q", ar.IDToken.Issuer)
} }
tenant := ar.IDToken.TenantID tenant := ar.IDToken.TenantID
if tenant == "" { if tenant == "" {
@ -84,7 +84,7 @@ func newAuthenticationRecord(ar public.AuthResult) (authenticationRecord, error)
if username == "" { if username == "" {
username = ar.IDToken.UPN username = ar.IDToken.UPN
} }
return authenticationRecord{ return AuthenticationRecord{
Authority: fmt.Sprintf("%s://%s", u.Scheme, u.Host), Authority: fmt.Sprintf("%s://%s", u.Scheme, u.Host),
ClientID: ar.IDToken.Audience, ClientID: ar.IDToken.Audience,
HomeAccountID: ar.Account.HomeAccountID, HomeAccountID: ar.Account.HomeAccountID,

View File

@ -53,8 +53,14 @@ var (
errInvalidTenantID = errors.New("invalid tenantID. You can locate your tenantID by following the instructions listed here: https://learn.microsoft.com/partner-center/find-ids-and-domain-names") errInvalidTenantID = errors.New("invalid tenantID. You can locate your tenantID by following the instructions listed here: https://learn.microsoft.com/partner-center/find-ids-and-domain-names")
) )
// tokenCachePersistenceOptions contains options for persistent token caching // Cache represents a persistent cache that makes authentication data available across processes.
type tokenCachePersistenceOptions = internal.TokenCachePersistenceOptions // Construct one with [github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache.New]. This package's
// [persistent user authentication example] shows how to use a persistent cache to reuse user
// logins across application runs. For service principal credential types such as
// [ClientCertificateCredential], simply set the Cache field on the credential options.
//
// [persistent user authentication example]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#example-package-PersistentUserAuthentication
type Cache = internal.Cache
// setAuthorityHost initializes the authority host for credentials. Precedence is: // setAuthorityHost initializes the authority host for credentials. Precedence is:
// 1. cloud.Configuration.ActiveDirectoryAuthorityHost value set by user // 1. cloud.Configuration.ActiveDirectoryAuthorityHost value set by user

View File

@ -20,6 +20,8 @@ const (
credNameAzurePipelines = "AzurePipelinesCredential" credNameAzurePipelines = "AzurePipelinesCredential"
oidcAPIVersion = "7.1" oidcAPIVersion = "7.1"
systemOIDCRequestURI = "SYSTEM_OIDCREQUESTURI" systemOIDCRequestURI = "SYSTEM_OIDCREQUESTURI"
xMsEdgeRef = "x-msedge-ref"
xVssE2eId = "x-vss-e2eid"
) )
// AzurePipelinesCredential authenticates with workload identity federation in an Azure Pipeline. See // AzurePipelinesCredential authenticates with workload identity federation in an Azure Pipeline. See
@ -40,6 +42,11 @@ type AzurePipelinesCredentialOptions struct {
// application is registered. // application is registered.
AdditionallyAllowedTenants []string AdditionallyAllowedTenants []string
// Cache is a persistent cache the credential will use to store the tokens it acquires, making
// them available to other processes and credential instances. The default, zero value means the
// credential will store tokens in memory and not share them with any other credential instance.
Cache Cache
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata
// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
@ -81,8 +88,11 @@ func NewAzurePipelinesCredential(tenantID, clientID, serviceConnectionID, system
if options == nil { if options == nil {
options = &AzurePipelinesCredentialOptions{} options = &AzurePipelinesCredentialOptions{}
} }
// these headers are useful to the DevOps team when debugging OIDC error responses
options.ClientOptions.Logging.AllowedHeaders = append(options.ClientOptions.Logging.AllowedHeaders, xMsEdgeRef, xVssE2eId)
caco := ClientAssertionCredentialOptions{ caco := ClientAssertionCredentialOptions{
AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, AdditionallyAllowedTenants: options.AdditionallyAllowedTenants,
Cache: options.Cache,
ClientOptions: options.ClientOptions, ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery, DisableInstanceDiscovery: options.DisableInstanceDiscovery,
} }
@ -108,33 +118,40 @@ func (a *AzurePipelinesCredential) getAssertion(ctx context.Context) (string, er
url := a.oidcURI + "?api-version=" + oidcAPIVersion + "&serviceConnectionId=" + a.connectionID url := a.oidcURI + "?api-version=" + oidcAPIVersion + "&serviceConnectionId=" + a.connectionID
url, err := runtime.EncodeQueryParams(url) url, err := runtime.EncodeQueryParams(url)
if err != nil { if err != nil {
return "", newAuthenticationFailedError(credNameAzurePipelines, "couldn't encode OIDC URL: "+err.Error(), nil, nil) return "", newAuthenticationFailedError(credNameAzurePipelines, "couldn't encode OIDC URL: "+err.Error(), nil)
} }
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, nil) req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, nil)
if err != nil { if err != nil {
return "", newAuthenticationFailedError(credNameAzurePipelines, "couldn't create OIDC token request: "+err.Error(), nil, nil) return "", newAuthenticationFailedError(credNameAzurePipelines, "couldn't create OIDC token request: "+err.Error(), nil)
} }
req.Header.Set("Authorization", "Bearer "+a.systemAccessToken) req.Header.Set("Authorization", "Bearer "+a.systemAccessToken)
// instruct endpoint to return 401 instead of 302, if the system access token is invalid
req.Header.Set("X-TFS-FedAuthRedirect", "Suppress")
res, err := doForClient(a.cred.client.azClient, req) res, err := doForClient(a.cred.client.azClient, req)
if err != nil { if err != nil {
return "", newAuthenticationFailedError(credNameAzurePipelines, "couldn't send OIDC token request: "+err.Error(), nil, nil) return "", newAuthenticationFailedError(credNameAzurePipelines, "couldn't send OIDC token request: "+err.Error(), nil)
} }
if res.StatusCode != http.StatusOK { if res.StatusCode != http.StatusOK {
msg := res.Status + " response from the OIDC endpoint. Check service connection ID and Pipeline configuration" msg := res.Status + " response from the OIDC endpoint. Check service connection ID and Pipeline configuration."
for _, h := range []string{xMsEdgeRef, xVssE2eId} {
if v := res.Header.Get(h); v != "" {
msg += fmt.Sprintf("\n%s: %s", h, v)
}
}
// include the response because its body, if any, probably contains an error message. // include the response because its body, if any, probably contains an error message.
// OK responses aren't included with errors because they probably contain secrets // OK responses aren't included with errors because they probably contain secrets
return "", newAuthenticationFailedError(credNameAzurePipelines, msg, res, nil) return "", newAuthenticationFailedError(credNameAzurePipelines, msg, res)
} }
b, err := runtime.Payload(res) b, err := runtime.Payload(res)
if err != nil { if err != nil {
return "", newAuthenticationFailedError(credNameAzurePipelines, "couldn't read OIDC response content: "+err.Error(), nil, nil) return "", newAuthenticationFailedError(credNameAzurePipelines, "couldn't read OIDC response content: "+err.Error(), nil)
} }
var r struct { var r struct {
OIDCToken string `json:"oidcToken"` OIDCToken string `json:"oidcToken"`
} }
err = json.Unmarshal(b, &r) err = json.Unmarshal(b, &r)
if err != nil { if err != nil {
return "", newAuthenticationFailedError(credNameAzurePipelines, "unexpected response from OIDC endpoint", nil, nil) return "", newAuthenticationFailedError(credNameAzurePipelines, "unexpected response from OIDC endpoint", nil)
} }
return r.OIDCToken, nil return r.OIDCToken, nil
} }

View File

@ -113,11 +113,19 @@ func (c *ChainedTokenCredential) GetToken(ctx context.Context, opts policy.Token
if err != nil { if err != nil {
// return credentialUnavailableError iff all sources did so; return AuthenticationFailedError otherwise // return credentialUnavailableError iff all sources did so; return AuthenticationFailedError otherwise
msg := createChainedErrorMessage(errs) msg := createChainedErrorMessage(errs)
if errors.As(err, &unavailableErr) { var authFailedErr *AuthenticationFailedError
switch {
case errors.As(err, &authFailedErr):
err = newAuthenticationFailedError(c.name, msg, authFailedErr.RawResponse)
if af, ok := err.(*AuthenticationFailedError); ok {
// stop Error() printing the response again; it's already in msg
af.omitResponse = true
}
case errors.As(err, &unavailableErr):
err = newCredentialUnavailableError(c.name, msg) err = newCredentialUnavailableError(c.name, msg)
} else { default:
res := getResponseFromError(err) res := getResponseFromError(err)
err = newAuthenticationFailedError(c.name, msg, res, err) err = newAuthenticationFailedError(c.name, msg, res)
} }
} }
return token, err return token, err
@ -126,7 +134,7 @@ func (c *ChainedTokenCredential) GetToken(ctx context.Context, opts policy.Token
func createChainedErrorMessage(errs []error) string { func createChainedErrorMessage(errs []error) string {
msg := "failed to acquire a token.\nAttempted credentials:" msg := "failed to acquire a token.\nAttempted credentials:"
for _, err := range errs { for _, err := range errs {
msg += fmt.Sprintf("\n\t%s", err.Error()) msg += fmt.Sprintf("\n\t%s", strings.ReplaceAll(err.Error(), "\n", "\n\t\t"))
} }
return msg return msg
} }

View File

@ -26,16 +26,27 @@ extends:
parameters: parameters:
CloudConfig: CloudConfig:
Public: Public:
ServiceConnection: azure-sdk-tests
SubscriptionConfigurationFilePaths:
- eng/common/TestResources/sub-config/AzurePublicMsft.json
SubscriptionConfigurations: SubscriptionConfigurations:
- $(sub-config-azure-cloud-test-resources) - $(sub-config-azure-cloud-test-resources)
- $(sub-config-identity-test-resources) - $(sub-config-identity-test-resources)
EnvVars: EnableRaceDetector: true
SYSTEM_ACCESSTOKEN: $(System.AccessToken)
RunLiveTests: true RunLiveTests: true
ServiceDirectory: azidentity ServiceDirectory: azidentity
UsePipelineProxy: false UsePipelineProxy: false
${{ if endsWith(variables['Build.DefinitionName'], 'weekly') }}: ${{ if endsWith(variables['Build.DefinitionName'], 'weekly') }}:
PreSteps:
- task: AzureCLI@2
displayName: Set OIDC token
inputs:
addSpnToEnvironment: true
azureSubscription: azure-sdk-tests
inlineScript: Write-Host "##vso[task.setvariable variable=OIDC_TOKEN;]$($env:idToken)"
scriptLocation: inlineScript
scriptType: pscore
MatrixConfigs: MatrixConfigs:
- Name: managed_identity_matrix - Name: managed_identity_matrix
GenerateVMJobs: true GenerateVMJobs: true

View File

@ -37,14 +37,16 @@ type ClientAssertionCredentialOptions struct {
// application is registered. // application is registered.
AdditionallyAllowedTenants []string AdditionallyAllowedTenants []string
// Cache is a persistent cache the credential will use to store the tokens it acquires, making
// them available to other processes and credential instances. The default, zero value means the
// credential will store tokens in memory and not share them with any other credential instance.
Cache Cache
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata
// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
// the application responsible for ensuring the configured authority is valid and trustworthy. // the application responsible for ensuring the configured authority is valid and trustworthy.
DisableInstanceDiscovery bool DisableInstanceDiscovery bool
// tokenCachePersistenceOptions enables persistent token caching when not nil.
tokenCachePersistenceOptions *tokenCachePersistenceOptions
} }
// NewClientAssertionCredential constructs a ClientAssertionCredential. The getAssertion function must be thread safe. Pass nil for options to accept defaults. // NewClientAssertionCredential constructs a ClientAssertionCredential. The getAssertion function must be thread safe. Pass nil for options to accept defaults.
@ -62,9 +64,9 @@ func NewClientAssertionCredential(tenantID, clientID string, getAssertion func(c
) )
msalOpts := confidentialClientOptions{ msalOpts := confidentialClientOptions{
AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, AdditionallyAllowedTenants: options.AdditionallyAllowedTenants,
Cache: options.Cache,
ClientOptions: options.ClientOptions, ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery, DisableInstanceDiscovery: options.DisableInstanceDiscovery,
tokenCachePersistenceOptions: options.tokenCachePersistenceOptions,
} }
c, err := newConfidentialClient(tenantID, clientID, credNameAssertion, cred, msalOpts) c, err := newConfidentialClient(tenantID, clientID, credNameAssertion, cred, msalOpts)
if err != nil { if err != nil {

View File

@ -31,6 +31,11 @@ type ClientCertificateCredentialOptions struct {
// application is registered. // application is registered.
AdditionallyAllowedTenants []string AdditionallyAllowedTenants []string
// Cache is a persistent cache the credential will use to store the tokens it acquires, making
// them available to other processes and credential instances. The default, zero value means the
// credential will store tokens in memory and not share them with any other credential instance.
Cache Cache
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata
// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
@ -41,9 +46,6 @@ type ClientCertificateCredentialOptions struct {
// header of each token request's JWT. This is required for Subject Name/Issuer (SNI) authentication. // header of each token request's JWT. This is required for Subject Name/Issuer (SNI) authentication.
// Defaults to False. // Defaults to False.
SendCertificateChain bool SendCertificateChain bool
// tokenCachePersistenceOptions enables persistent token caching when not nil.
tokenCachePersistenceOptions *tokenCachePersistenceOptions
} }
// ClientCertificateCredential authenticates a service principal with a certificate. // ClientCertificateCredential authenticates a service principal with a certificate.
@ -66,10 +68,10 @@ func NewClientCertificateCredential(tenantID string, clientID string, certs []*x
} }
msalOpts := confidentialClientOptions{ msalOpts := confidentialClientOptions{
AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, AdditionallyAllowedTenants: options.AdditionallyAllowedTenants,
Cache: options.Cache,
ClientOptions: options.ClientOptions, ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery, DisableInstanceDiscovery: options.DisableInstanceDiscovery,
SendX5C: options.SendCertificateChain, SendX5C: options.SendCertificateChain,
tokenCachePersistenceOptions: options.tokenCachePersistenceOptions,
} }
c, err := newConfidentialClient(tenantID, clientID, credNameCert, cred, msalOpts) c, err := newConfidentialClient(tenantID, clientID, credNameCert, cred, msalOpts)
if err != nil { if err != nil {

View File

@ -32,8 +32,10 @@ type ClientSecretCredentialOptions struct {
// the application responsible for ensuring the configured authority is valid and trustworthy. // the application responsible for ensuring the configured authority is valid and trustworthy.
DisableInstanceDiscovery bool DisableInstanceDiscovery bool
// tokenCachePersistenceOptions enables persistent token caching when not nil. // Cache is a persistent cache the credential will use to store the tokens it acquires, making
tokenCachePersistenceOptions *tokenCachePersistenceOptions // them available to other processes and credential instances. The default, zero value means the
// credential will store tokens in memory and not share them with any other credential instance.
Cache Cache
} }
// ClientSecretCredential authenticates an application with a client secret. // ClientSecretCredential authenticates an application with a client secret.
@ -52,9 +54,9 @@ func NewClientSecretCredential(tenantID string, clientID string, clientSecret st
} }
msalOpts := confidentialClientOptions{ msalOpts := confidentialClientOptions{
AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, AdditionallyAllowedTenants: options.AdditionallyAllowedTenants,
Cache: options.Cache,
ClientOptions: options.ClientOptions, ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery, DisableInstanceDiscovery: options.DisableInstanceDiscovery,
tokenCachePersistenceOptions: options.tokenCachePersistenceOptions,
} }
c, err := newConfidentialClient(tenantID, clientID, credNameSecret, cred, msalOpts) c, err := newConfidentialClient(tenantID, clientID, credNameSecret, cred, msalOpts)
if err != nil { if err != nil {

View File

@ -29,8 +29,8 @@ type confidentialClientOptions struct {
AdditionallyAllowedTenants []string AdditionallyAllowedTenants []string
// Assertion for on-behalf-of authentication // Assertion for on-behalf-of authentication
Assertion string Assertion string
Cache Cache
DisableInstanceDiscovery, SendX5C bool DisableInstanceDiscovery, SendX5C bool
tokenCachePersistenceOptions *tokenCachePersistenceOptions
} }
// confidentialClient wraps the MSAL confidential client // confidentialClient wraps the MSAL confidential client
@ -107,12 +107,12 @@ func (c *confidentialClient) GetToken(ctx context.Context, tro policy.TokenReque
} }
} }
if err != nil { if err != nil {
// We could get a credentialUnavailableError from managed identity authentication because in that case the error comes from our code. var (
// We return it directly because it affects the behavior of credential chains. Otherwise, we return AuthenticationFailedError. authFailedErr *AuthenticationFailedError
var unavailableErr credentialUnavailable unavailableErr credentialUnavailable
if !errors.As(err, &unavailableErr) { )
res := getResponseFromError(err) if !(errors.As(err, &unavailableErr) || errors.As(err, &authFailedErr)) {
err = newAuthenticationFailedError(c.name, err.Error(), res, err) err = newAuthenticationFailedErrorFromMSAL(c.name, err)
} }
} else { } else {
msg := fmt.Sprintf("%s.GetToken() acquired a token for scope %q", c.name, strings.Join(ar.GrantedScopes, ", ")) msg := fmt.Sprintf("%s.GetToken() acquired a token for scope %q", c.name, strings.Join(ar.GrantedScopes, ", "))
@ -145,7 +145,7 @@ func (c *confidentialClient) client(tro policy.TokenRequestOptions) (msalConfide
} }
func (c *confidentialClient) newMSALClient(enableCAE bool) (msalConfidentialClient, error) { func (c *confidentialClient) newMSALClient(enableCAE bool) (msalConfidentialClient, error) {
cache, err := internal.NewCache(c.opts.tokenCachePersistenceOptions, enableCAE) cache, err := internal.ExportReplace(c.opts.Cache, enableCAE)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -36,10 +36,13 @@ type DefaultAzureCredentialOptions struct {
TenantID string TenantID string
} }
// DefaultAzureCredential is a default credential chain for applications that will deploy to Azure. // DefaultAzureCredential simplifies authentication while developing applications that deploy to Azure by
// It combines credentials suitable for deployment with credentials suitable for local development. // combining credentials used in Azure hosting environments and credentials used in local development. In
// It attempts to authenticate with each of these credential types, in the following order, stopping // production, it's better to use a specific credential type so authentication is more predictable and easier
// when one provides a token: // to debug.
//
// DefaultAzureCredential attempts to authenticate with each of these credential types, in the following order,
// stopping when one provides a token:
// //
// - [EnvironmentCredential] // - [EnvironmentCredential]
// - [WorkloadIdentityCredential], if environment variable configuration is set by the Azure workload // - [WorkloadIdentityCredential], if environment variable configuration is set by the Azure workload

View File

@ -25,18 +25,26 @@ type DeviceCodeCredentialOptions struct {
// tokens. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant. // tokens. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant.
AdditionallyAllowedTenants []string AdditionallyAllowedTenants []string
// authenticationRecord returned by a call to a credential's Authenticate method. Set this option // AuthenticationRecord returned by a call to a credential's Authenticate method. Set this option
// to enable the credential to use data from a previous authentication. // to enable the credential to use data from a previous authentication.
authenticationRecord authenticationRecord AuthenticationRecord AuthenticationRecord
// ClientID is the ID of the application users will authenticate to. // Cache is a persistent cache the credential will use to store the tokens it acquires, making
// Defaults to the ID of an Azure development application. // them available to other processes and credential instances. The default, zero value means the
// credential will store tokens in memory and not share them with any other credential instance.
Cache Cache
// ClientID is the ID of the application to which users will authenticate. When not set, users
// will authenticate to an Azure development application, which isn't recommended for production
// scenarios. In production, developers should instead register their applications and assign
// appropriate roles. See https://aka.ms/azsdk/identity/AppRegistrationAndRoleAssignment for more
// information.
ClientID string ClientID string
// disableAutomaticAuthentication prevents the credential from automatically prompting the user to authenticate. // DisableAutomaticAuthentication prevents the credential from automatically prompting the user to authenticate.
// When this option is true, GetToken will return authenticationRequiredError when user interaction is necessary // When this option is true, GetToken will return AuthenticationRequiredError when user interaction is necessary
// to acquire a token. // to acquire a token.
disableAutomaticAuthentication bool DisableAutomaticAuthentication bool
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata
@ -49,9 +57,6 @@ type DeviceCodeCredentialOptions struct {
// applications. // applications.
TenantID string TenantID string
// tokenCachePersistenceOptions enables persistent token caching when not nil.
tokenCachePersistenceOptions *tokenCachePersistenceOptions
// UserPrompt controls how the credential presents authentication instructions. The credential calls // UserPrompt controls how the credential presents authentication instructions. The credential calls
// this function with authentication details when it receives a device code. By default, the credential // this function with authentication details when it receives a device code. By default, the credential
// prints these details to stdout. // prints these details to stdout.
@ -101,12 +106,12 @@ func NewDeviceCodeCredential(options *DeviceCodeCredentialOptions) (*DeviceCodeC
cp.init() cp.init()
msalOpts := publicClientOptions{ msalOpts := publicClientOptions{
AdditionallyAllowedTenants: cp.AdditionallyAllowedTenants, AdditionallyAllowedTenants: cp.AdditionallyAllowedTenants,
Cache: cp.Cache,
ClientOptions: cp.ClientOptions, ClientOptions: cp.ClientOptions,
DeviceCodePrompt: cp.UserPrompt, DeviceCodePrompt: cp.UserPrompt,
DisableAutomaticAuthentication: cp.disableAutomaticAuthentication, DisableAutomaticAuthentication: cp.DisableAutomaticAuthentication,
DisableInstanceDiscovery: cp.DisableInstanceDiscovery, DisableInstanceDiscovery: cp.DisableInstanceDiscovery,
Record: cp.authenticationRecord, Record: cp.AuthenticationRecord,
TokenCachePersistenceOptions: cp.tokenCachePersistenceOptions,
} }
c, err := newPublicClient(cp.TenantID, cp.ClientID, credNameDeviceCode, msalOpts) c, err := newPublicClient(cp.TenantID, cp.ClientID, credNameDeviceCode, msalOpts)
if err != nil { if err != nil {
@ -116,8 +121,9 @@ func NewDeviceCodeCredential(options *DeviceCodeCredentialOptions) (*DeviceCodeC
return &DeviceCodeCredential{client: c}, nil return &DeviceCodeCredential{client: c}, nil
} }
// Authenticate a user via the device code flow. Subsequent calls to GetToken will automatically use the returned AuthenticationRecord. // Authenticate prompts a user to log in via the device code flow. Subsequent
func (c *DeviceCodeCredential) authenticate(ctx context.Context, opts *policy.TokenRequestOptions) (authenticationRecord, error) { // GetToken calls will automatically use the returned AuthenticationRecord.
func (c *DeviceCodeCredential) Authenticate(ctx context.Context, opts *policy.TokenRequestOptions) (AuthenticationRecord, error) {
var err error var err error
ctx, endSpan := runtime.StartSpan(ctx, credNameDeviceCode+"."+traceOpAuthenticate, c.client.azClient.Tracer(), nil) ctx, endSpan := runtime.StartSpan(ctx, credNameDeviceCode+"."+traceOpAuthenticate, c.client.azClient.Tracer(), nil)
defer func() { endSpan(err) }() defer func() { endSpan(err) }()

View File

@ -38,18 +38,30 @@ type AuthenticationFailedError struct {
// RawResponse is the HTTP response motivating the error, if available. // RawResponse is the HTTP response motivating the error, if available.
RawResponse *http.Response RawResponse *http.Response
credType string credType, message string
message string omitResponse bool
err error
} }
func newAuthenticationFailedError(credType string, message string, resp *http.Response, err error) error { func newAuthenticationFailedError(credType, message string, resp *http.Response) error {
return &AuthenticationFailedError{credType: credType, message: message, RawResponse: resp, err: err} return &AuthenticationFailedError{credType: credType, message: message, RawResponse: resp}
}
// newAuthenticationFailedErrorFromMSAL creates an AuthenticationFailedError from an MSAL error.
// If the error is an MSAL CallErr, the new error includes an HTTP response and not the MSAL error
// message, because that message is redundant given the response. If the original error isn't a
// CallErr, the returned error incorporates its message.
func newAuthenticationFailedErrorFromMSAL(credType string, err error) error {
msg := ""
res := getResponseFromError(err)
if res == nil {
msg = err.Error()
}
return newAuthenticationFailedError(credType, msg, res)
} }
// Error implements the error interface. Note that the message contents are not contractual and can change over time. // Error implements the error interface. Note that the message contents are not contractual and can change over time.
func (e *AuthenticationFailedError) Error() string { func (e *AuthenticationFailedError) Error() string {
if e.RawResponse == nil { if e.RawResponse == nil || e.omitResponse {
return e.credType + ": " + e.message return e.credType + ": " + e.message
} }
msg := &bytes.Buffer{} msg := &bytes.Buffer{}
@ -62,7 +74,7 @@ func (e *AuthenticationFailedError) Error() string {
fmt.Fprintln(msg, "Request information not available") fmt.Fprintln(msg, "Request information not available")
} }
fmt.Fprintln(msg, "--------------------------------------------------------------------------------") fmt.Fprintln(msg, "--------------------------------------------------------------------------------")
fmt.Fprintf(msg, "RESPONSE %s\n", e.RawResponse.Status) fmt.Fprintf(msg, "RESPONSE %d: %s\n", e.RawResponse.StatusCode, e.RawResponse.Status)
fmt.Fprintln(msg, "--------------------------------------------------------------------------------") fmt.Fprintln(msg, "--------------------------------------------------------------------------------")
body, err := runtime.Payload(e.RawResponse) body, err := runtime.Payload(e.RawResponse)
switch { switch {
@ -109,17 +121,17 @@ func (*AuthenticationFailedError) NonRetriable() {
var _ errorinfo.NonRetriable = (*AuthenticationFailedError)(nil) var _ errorinfo.NonRetriable = (*AuthenticationFailedError)(nil)
// authenticationRequiredError indicates a credential's Authenticate method must be called to acquire a token // AuthenticationRequiredError indicates a credential's Authenticate method must be called to acquire a token
// because the credential requires user interaction and is configured not to request it automatically. // because the credential requires user interaction and is configured not to request it automatically.
type authenticationRequiredError struct { type AuthenticationRequiredError struct {
credentialUnavailableError credentialUnavailableError
// TokenRequestOptions for the required token. Pass this to the credential's Authenticate method. // TokenRequestOptions for the required token. Pass this to the credential's Authenticate method.
TokenRequestOptions policy.TokenRequestOptions TokenRequestOptions policy.TokenRequestOptions
} }
func newauthenticationRequiredError(credType string, tro policy.TokenRequestOptions) error { func newAuthenticationRequiredError(credType string, tro policy.TokenRequestOptions) error {
return &authenticationRequiredError{ return &AuthenticationRequiredError{
credentialUnavailableError: credentialUnavailableError{ credentialUnavailableError: credentialUnavailableError{
credType + " can't acquire a token without user interaction. Call Authenticate to authenticate a user interactively", credType + " can't acquire a token without user interaction. Call Authenticate to authenticate a user interactively",
}, },
@ -128,8 +140,8 @@ func newauthenticationRequiredError(credType string, tro policy.TokenRequestOpti
} }
var ( var (
_ credentialUnavailable = (*authenticationRequiredError)(nil) _ credentialUnavailable = (*AuthenticationRequiredError)(nil)
_ errorinfo.NonRetriable = (*authenticationRequiredError)(nil) _ errorinfo.NonRetriable = (*AuthenticationRequiredError)(nil)
) )
type credentialUnavailable interface { type credentialUnavailable interface {

View File

@ -1,60 +0,0 @@
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.0-beta.1 h1:ODs3brnqQM99Tq1PffODpAViYv3Bf8zOg464MU7p5ew=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.0-beta.1/go.mod h1:3Ug6Qzto9anB6mGlEdgYMDF5zHQ+wwhEaYR4s17PHMw=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.0 h1:fb8kj/Dh4CSwgsOzHeZY4Xh68cFVbzXx+ONXGMY//4w=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.0/go.mod h1:uReU2sSxZExRPBAg3qKzmAucSi51+SP1OhohieR821Q=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0/go.mod h1:okt5dMMTOFjX/aovMlrjvvXoPMBVSPzk9185BT0+eZM=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2/go.mod h1:yInRyqWXAuaPrgI7p70+lDDgh3mlBohis29jGMISnmc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/keybase/dbus v0.0.0-20220506165403-5aa21ea2c23a/go.mod h1:YPNKjjE7Ubp9dTbnWvsP3HT+hYnY6TfXzubYTBeUxc8=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/montanaflynn/stats v0.7.0/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o=
golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU=
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U=
golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -24,18 +24,26 @@ type InteractiveBrowserCredentialOptions struct {
// tokens. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant. // tokens. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant.
AdditionallyAllowedTenants []string AdditionallyAllowedTenants []string
// authenticationRecord returned by a call to a credential's Authenticate method. Set this option // AuthenticationRecord returned by a call to a credential's Authenticate method. Set this option
// to enable the credential to use data from a previous authentication. // to enable the credential to use data from a previous authentication.
authenticationRecord authenticationRecord AuthenticationRecord AuthenticationRecord
// ClientID is the ID of the application users will authenticate to. // Cache is a persistent cache the credential will use to store the tokens it acquires, making
// Defaults to the ID of an Azure development application. // them available to other processes and credential instances. The default, zero value means the
// credential will store tokens in memory and not share them with any other credential instance.
Cache Cache
// ClientID is the ID of the application to which users will authenticate. When not set, users
// will authenticate to an Azure development application, which isn't recommended for production
// scenarios. In production, developers should instead register their applications and assign
// appropriate roles. See https://aka.ms/azsdk/identity/AppRegistrationAndRoleAssignment for more
// information.
ClientID string ClientID string
// disableAutomaticAuthentication prevents the credential from automatically prompting the user to authenticate. // DisableAutomaticAuthentication prevents the credential from automatically prompting the user to authenticate.
// When this option is true, GetToken will return authenticationRequiredError when user interaction is necessary // When this option is true, GetToken will return AuthenticationRequiredError when user interaction is necessary
// to acquire a token. // to acquire a token.
disableAutomaticAuthentication bool DisableAutomaticAuthentication bool
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata
@ -54,9 +62,6 @@ type InteractiveBrowserCredentialOptions struct {
// TenantID is the Microsoft Entra tenant the credential authenticates in. Defaults to the // TenantID is the Microsoft Entra tenant the credential authenticates in. Defaults to the
// "organizations" tenant, which can authenticate work and school accounts. // "organizations" tenant, which can authenticate work and school accounts.
TenantID string TenantID string
// tokenCachePersistenceOptions enables persistent token caching when not nil.
tokenCachePersistenceOptions *tokenCachePersistenceOptions
} }
func (o *InteractiveBrowserCredentialOptions) init() { func (o *InteractiveBrowserCredentialOptions) init() {
@ -82,13 +87,13 @@ func NewInteractiveBrowserCredential(options *InteractiveBrowserCredentialOption
cp.init() cp.init()
msalOpts := publicClientOptions{ msalOpts := publicClientOptions{
AdditionallyAllowedTenants: cp.AdditionallyAllowedTenants, AdditionallyAllowedTenants: cp.AdditionallyAllowedTenants,
Cache: cp.Cache,
ClientOptions: cp.ClientOptions, ClientOptions: cp.ClientOptions,
DisableAutomaticAuthentication: cp.disableAutomaticAuthentication, DisableAutomaticAuthentication: cp.DisableAutomaticAuthentication,
DisableInstanceDiscovery: cp.DisableInstanceDiscovery, DisableInstanceDiscovery: cp.DisableInstanceDiscovery,
LoginHint: cp.LoginHint, LoginHint: cp.LoginHint,
Record: cp.authenticationRecord, Record: cp.AuthenticationRecord,
RedirectURL: cp.RedirectURL, RedirectURL: cp.RedirectURL,
TokenCachePersistenceOptions: cp.tokenCachePersistenceOptions,
} }
c, err := newPublicClient(cp.TenantID, cp.ClientID, credNameBrowser, msalOpts) c, err := newPublicClient(cp.TenantID, cp.ClientID, credNameBrowser, msalOpts)
if err != nil { if err != nil {
@ -97,8 +102,9 @@ func NewInteractiveBrowserCredential(options *InteractiveBrowserCredentialOption
return &InteractiveBrowserCredential{client: c}, nil return &InteractiveBrowserCredential{client: c}, nil
} }
// Authenticate a user via the default browser. Subsequent calls to GetToken will automatically use the returned AuthenticationRecord. // Authenticate opens the default browser so a user can log in. Subsequent
func (c *InteractiveBrowserCredential) authenticate(ctx context.Context, opts *policy.TokenRequestOptions) (authenticationRecord, error) { // GetToken calls will automatically use the returned AuthenticationRecord.
func (c *InteractiveBrowserCredential) Authenticate(ctx context.Context, opts *policy.TokenRequestOptions) (AuthenticationRecord, error) {
var err error var err error
ctx, endSpan := runtime.StartSpan(ctx, credNameBrowser+"."+traceOpAuthenticate, c.client.azClient.Tracer(), nil) ctx, endSpan := runtime.StartSpan(ctx, credNameBrowser+"."+traceOpAuthenticate, c.client.azClient.Tracer(), nil)
defer func() { endSpan(err) }() defer func() { endSpan(err) }()

View File

@ -0,0 +1,86 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package internal
import (
"sync"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache"
)
// Cache represents a persistent cache that makes authentication data available across processes.
// Construct one with [github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache.New]. This package's
// [persistent user authentication example] shows how to use a persistent cache to reuse user
// logins across application runs. For service principal credential types such as
// [ClientCertificateCredential], simply set the Cache field on the credential options.
//
// [persistent user authentication example]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#example-package-PersistentUserAuthentication
type Cache struct {
// impl is a pointer so a Cache can carry persistent state across copies
impl *impl
}
// impl is a Cache's private implementation
type impl struct {
// factory constructs storage implementations
factory func(bool) (cache.ExportReplace, error)
// cae and noCAE are previously constructed storage implementations. CAE
// and non-CAE tokens must be stored separately because MSAL's cache doesn't
// observe token claims. If a single storage implementation held both kinds
// of tokens, it could create a reauthentication or error loop by returning
// a non-CAE token lacking a required claim.
cae, noCAE cache.ExportReplace
// mu synchronizes around cae and noCAE
mu *sync.RWMutex
}
func (i *impl) exportReplace(cae bool) (cache.ExportReplace, error) {
if i == nil {
// zero-value Cache: return a nil ExportReplace and MSAL will cache in memory
return nil, nil
}
var (
err error
xr cache.ExportReplace
)
i.mu.RLock()
xr = i.cae
if !cae {
xr = i.noCAE
}
i.mu.RUnlock()
if xr != nil {
return xr, nil
}
i.mu.Lock()
defer i.mu.Unlock()
if cae {
if i.cae == nil {
if xr, err = i.factory(cae); err == nil {
i.cae = xr
}
}
return i.cae, err
}
if i.noCAE == nil {
if xr, err = i.factory(cae); err == nil {
i.noCAE = xr
}
}
return i.noCAE, err
}
// NewCache is the constructor for Cache. It takes a factory instead of an instance
// because it doesn't know whether the Cache will store both CAE and non-CAE tokens.
func NewCache(factory func(cae bool) (cache.ExportReplace, error)) Cache {
return Cache{&impl{factory: factory, mu: &sync.RWMutex{}}}
}
// ExportReplace returns an implementation satisfying MSAL's ExportReplace interface.
// It's a function instead of a method on Cache so packages in azidentity and
// azidentity/cache can call it while applications can't. "cae" declares whether the
// caller intends this implementation to store CAE tokens.
func ExportReplace(c Cache, cae bool) (cache.ExportReplace, error) {
return c.impl.exportReplace(cae)
}

View File

@ -1,18 +0,0 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package internal
// TokenCachePersistenceOptions contains options for persistent token caching
type TokenCachePersistenceOptions struct {
// AllowUnencryptedStorage controls whether the cache should fall back to storing its data in plain text
// when encryption isn't possible. Setting this true doesn't disable encryption. The cache always attempts
// encryption before falling back to plaintext storage.
AllowUnencryptedStorage bool
// Name identifies the cache. Set this to isolate data from other applications.
Name string
}

View File

@ -1,31 +0,0 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package internal
import (
"errors"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache"
)
var errMissingImport = errors.New("import github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache to enable persistent caching")
// NewCache constructs a persistent token cache when "o" isn't nil. Applications that intend to
// use a persistent cache must first import the cache module, which will replace this function
// with a platform-specific implementation.
var NewCache = func(o *TokenCachePersistenceOptions, enableCAE bool) (cache.ExportReplace, error) {
if o == nil {
return nil, nil
}
return nil, errMissingImport
}
// CacheFilePath returns the path to the cache file for the given name.
// Defining it in this package makes it available to azidentity tests.
var CacheFilePath = func(name string) (string, error) {
return "", errMissingImport
}

View File

@ -143,6 +143,9 @@ func newManagedIdentityClient(options *ManagedIdentityCredentialOptions) (*manag
if endpoint, ok := os.LookupEnv(identityEndpoint); ok { if endpoint, ok := os.LookupEnv(identityEndpoint); ok {
if _, ok := os.LookupEnv(identityHeader); ok { if _, ok := os.LookupEnv(identityHeader); ok {
if _, ok := os.LookupEnv(identityServerThumbprint); ok { if _, ok := os.LookupEnv(identityServerThumbprint); ok {
if options.ID != nil {
return nil, errors.New("the Service Fabric API doesn't support specifying a user-assigned managed identity at runtime")
}
env = "Service Fabric" env = "Service Fabric"
c.endpoint = endpoint c.endpoint = endpoint
c.msiType = msiTypeServiceFabric c.msiType = msiTypeServiceFabric
@ -152,6 +155,9 @@ func newManagedIdentityClient(options *ManagedIdentityCredentialOptions) (*manag
c.msiType = msiTypeAppService c.msiType = msiTypeAppService
} }
} else if _, ok := os.LookupEnv(arcIMDSEndpoint); ok { } else if _, ok := os.LookupEnv(arcIMDSEndpoint); ok {
if options.ID != nil {
return nil, errors.New("the Azure Arc API doesn't support specifying a user-assigned managed identity at runtime")
}
env = "Azure Arc" env = "Azure Arc"
c.endpoint = endpoint c.endpoint = endpoint
c.msiType = msiTypeAzureArc c.msiType = msiTypeAzureArc
@ -159,9 +165,15 @@ func newManagedIdentityClient(options *ManagedIdentityCredentialOptions) (*manag
} else if endpoint, ok := os.LookupEnv(msiEndpoint); ok { } else if endpoint, ok := os.LookupEnv(msiEndpoint); ok {
c.endpoint = endpoint c.endpoint = endpoint
if _, ok := os.LookupEnv(msiSecret); ok { if _, ok := os.LookupEnv(msiSecret); ok {
if options.ID != nil && options.ID.idKind() != miClientID {
return nil, errors.New("the Azure ML API supports specifying a user-assigned managed identity by client ID only")
}
env = "Azure ML" env = "Azure ML"
c.msiType = msiTypeAzureML c.msiType = msiTypeAzureML
} else { } else {
if options.ID != nil {
return nil, errors.New("the Cloud Shell API doesn't support user-assigned managed identities")
}
env = "Cloud Shell" env = "Cloud Shell"
c.msiType = msiTypeCloudShell c.msiType = msiTypeCloudShell
} }
@ -207,9 +219,10 @@ func (c *managedIdentityClient) authenticate(ctx context.Context, id ManagedIDKi
defer cancel() defer cancel()
cx = policy.WithRetryOptions(cx, policy.RetryOptions{MaxRetries: -1}) cx = policy.WithRetryOptions(cx, policy.RetryOptions{MaxRetries: -1})
req, err := azruntime.NewRequest(cx, http.MethodGet, c.endpoint) req, err := azruntime.NewRequest(cx, http.MethodGet, c.endpoint)
if err == nil { if err != nil {
_, err = c.azClient.Pipeline().Do(req) return azcore.AccessToken{}, fmt.Errorf("failed to create IMDS probe request: %s", err)
} }
res, err := c.azClient.Pipeline().Do(req)
if err != nil { if err != nil {
msg := err.Error() msg := err.Error()
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
@ -217,7 +230,16 @@ func (c *managedIdentityClient) authenticate(ctx context.Context, id ManagedIDKi
} }
return azcore.AccessToken{}, newCredentialUnavailableError(credNameManagedIdentity, msg) return azcore.AccessToken{}, newCredentialUnavailableError(credNameManagedIdentity, msg)
} }
// send normal token requests from now on because something responded // because IMDS always responds with JSON, assume a non-JSON response is from something else, such
// as a proxy, and return credentialUnavailableError so DefaultAzureCredential continues iterating
b, err := azruntime.Payload(res)
if err != nil {
return azcore.AccessToken{}, newCredentialUnavailableError(credNameManagedIdentity, fmt.Sprintf("failed to read IMDS probe response: %s", err))
}
if !json.Valid(b) {
return azcore.AccessToken{}, newCredentialUnavailableError(credNameManagedIdentity, "unexpected response to IMDS probe")
}
// send normal token requests from now on because IMDS responded
c.probeIMDS = false c.probeIMDS = false
} }
@ -228,7 +250,7 @@ func (c *managedIdentityClient) authenticate(ctx context.Context, id ManagedIDKi
resp, err := c.azClient.Pipeline().Do(msg) resp, err := c.azClient.Pipeline().Do(msg)
if err != nil { if err != nil {
return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, err.Error(), nil, err) return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, err.Error(), nil)
} }
if azruntime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { if azruntime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) {
@ -239,7 +261,7 @@ func (c *managedIdentityClient) authenticate(ctx context.Context, id ManagedIDKi
switch resp.StatusCode { switch resp.StatusCode {
case http.StatusBadRequest: case http.StatusBadRequest:
if id != nil { if id != nil {
return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "the requested identity isn't assigned to this resource", resp, nil) return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "the requested identity isn't assigned to this resource", resp)
} }
msg := "failed to authenticate a system assigned identity" msg := "failed to authenticate a system assigned identity"
if body, err := azruntime.Payload(resp); err == nil && len(body) > 0 { if body, err := azruntime.Payload(resp); err == nil && len(body) > 0 {
@ -256,7 +278,7 @@ func (c *managedIdentityClient) authenticate(ctx context.Context, id ManagedIDKi
} }
} }
return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "authentication failed", resp, nil) return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "", resp)
} }
func (c *managedIdentityClient) createAccessToken(res *http.Response) (azcore.AccessToken, error) { func (c *managedIdentityClient) createAccessToken(res *http.Response) (azcore.AccessToken, error) {
@ -284,10 +306,10 @@ func (c *managedIdentityClient) createAccessToken(res *http.Response) (azcore.Ac
if expiresOn, err := strconv.Atoi(v); err == nil { if expiresOn, err := strconv.Atoi(v); err == nil {
return azcore.AccessToken{Token: value.Token, ExpiresOn: time.Unix(int64(expiresOn), 0).UTC()}, nil return azcore.AccessToken{Token: value.Token, ExpiresOn: time.Unix(int64(expiresOn), 0).UTC()}, nil
} }
return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "unexpected expires_on value: "+v, res, nil) return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "unexpected expires_on value: "+v, res)
default: default:
msg := fmt.Sprintf("unsupported type received in expires_on: %T, %v", v, v) msg := fmt.Sprintf("unsupported type received in expires_on: %T, %v", v, v)
return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, msg, res, nil) return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, msg, res)
} }
} }
@ -302,15 +324,15 @@ func (c *managedIdentityClient) createAuthRequest(ctx context.Context, id Manage
key, err := c.getAzureArcSecretKey(ctx, scopes) key, err := c.getAzureArcSecretKey(ctx, scopes)
if err != nil { if err != nil {
msg := fmt.Sprintf("failed to retreive secret key from the identity endpoint: %v", err) msg := fmt.Sprintf("failed to retreive secret key from the identity endpoint: %v", err)
return nil, newAuthenticationFailedError(credNameManagedIdentity, msg, nil, err) return nil, newAuthenticationFailedError(credNameManagedIdentity, msg, nil)
} }
return c.createAzureArcAuthRequest(ctx, id, scopes, key) return c.createAzureArcAuthRequest(ctx, scopes, key)
case msiTypeAzureML: case msiTypeAzureML:
return c.createAzureMLAuthRequest(ctx, id, scopes) return c.createAzureMLAuthRequest(ctx, id, scopes)
case msiTypeServiceFabric: case msiTypeServiceFabric:
return c.createServiceFabricAuthRequest(ctx, id, scopes) return c.createServiceFabricAuthRequest(ctx, scopes)
case msiTypeCloudShell: case msiTypeCloudShell:
return c.createCloudShellAuthRequest(ctx, id, scopes) return c.createCloudShellAuthRequest(ctx, scopes)
default: default:
return nil, newCredentialUnavailableError(credNameManagedIdentity, "managed identity isn't supported in this environment") return nil, newCredentialUnavailableError(credNameManagedIdentity, "managed identity isn't supported in this environment")
} }
@ -323,13 +345,16 @@ func (c *managedIdentityClient) createIMDSAuthRequest(ctx context.Context, id Ma
} }
request.Raw().Header.Set(headerMetadata, "true") request.Raw().Header.Set(headerMetadata, "true")
q := request.Raw().URL.Query() q := request.Raw().URL.Query()
q.Add("api-version", imdsAPIVersion) q.Set("api-version", imdsAPIVersion)
q.Add("resource", strings.Join(scopes, " ")) q.Set("resource", strings.Join(scopes, " "))
if id != nil { if id != nil {
if id.idKind() == miResourceID { switch id.idKind() {
q.Add(msiResID, id.String()) case miClientID:
} else { q.Set(qpClientID, id.String())
q.Add(qpClientID, id.String()) case miObjectID:
q.Set("object_id", id.String())
case miResourceID:
q.Set(msiResID, id.String())
} }
} }
request.Raw().URL.RawQuery = q.Encode() request.Raw().URL.RawQuery = q.Encode()
@ -343,13 +368,16 @@ func (c *managedIdentityClient) createAppServiceAuthRequest(ctx context.Context,
} }
request.Raw().Header.Set("X-IDENTITY-HEADER", os.Getenv(identityHeader)) request.Raw().Header.Set("X-IDENTITY-HEADER", os.Getenv(identityHeader))
q := request.Raw().URL.Query() q := request.Raw().URL.Query()
q.Add("api-version", "2019-08-01") q.Set("api-version", "2019-08-01")
q.Add("resource", scopes[0]) q.Set("resource", scopes[0])
if id != nil { if id != nil {
if id.idKind() == miResourceID { switch id.idKind() {
q.Add(miResID, id.String()) case miClientID:
} else { q.Set(qpClientID, id.String())
q.Add(qpClientID, id.String()) case miObjectID:
q.Set("principal_id", id.String())
case miResourceID:
q.Set(miResID, id.String())
} }
} }
request.Raw().URL.RawQuery = q.Encode() request.Raw().URL.RawQuery = q.Encode()
@ -363,23 +391,24 @@ func (c *managedIdentityClient) createAzureMLAuthRequest(ctx context.Context, id
} }
request.Raw().Header.Set("secret", os.Getenv(msiSecret)) request.Raw().Header.Set("secret", os.Getenv(msiSecret))
q := request.Raw().URL.Query() q := request.Raw().URL.Query()
q.Add("api-version", "2017-09-01") q.Set("api-version", "2017-09-01")
q.Add("resource", strings.Join(scopes, " ")) q.Set("resource", strings.Join(scopes, " "))
q.Add("clientid", os.Getenv(defaultIdentityClientID)) q.Set("clientid", os.Getenv(defaultIdentityClientID))
if id != nil { if id != nil {
if id.idKind() == miResourceID { switch id.idKind() {
log.Write(EventAuthentication, "WARNING: Azure ML doesn't support specifying a managed identity by resource ID") case miClientID:
q.Set("clientid", "")
q.Set(miResID, id.String())
} else {
q.Set("clientid", id.String()) q.Set("clientid", id.String())
case miObjectID:
return nil, newAuthenticationFailedError(credNameManagedIdentity, "Azure ML doesn't support specifying a managed identity by object ID", nil)
case miResourceID:
return nil, newAuthenticationFailedError(credNameManagedIdentity, "Azure ML doesn't support specifying a managed identity by resource ID", nil)
} }
} }
request.Raw().URL.RawQuery = q.Encode() request.Raw().URL.RawQuery = q.Encode()
return request, nil return request, nil
} }
func (c *managedIdentityClient) createServiceFabricAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { func (c *managedIdentityClient) createServiceFabricAuthRequest(ctx context.Context, scopes []string) (*policy.Request, error) {
request, err := azruntime.NewRequest(ctx, http.MethodGet, c.endpoint) request, err := azruntime.NewRequest(ctx, http.MethodGet, c.endpoint)
if err != nil { if err != nil {
return nil, err return nil, err
@ -387,16 +416,8 @@ func (c *managedIdentityClient) createServiceFabricAuthRequest(ctx context.Conte
q := request.Raw().URL.Query() q := request.Raw().URL.Query()
request.Raw().Header.Set("Accept", "application/json") request.Raw().Header.Set("Accept", "application/json")
request.Raw().Header.Set("Secret", os.Getenv(identityHeader)) request.Raw().Header.Set("Secret", os.Getenv(identityHeader))
q.Add("api-version", serviceFabricAPIVersion) q.Set("api-version", serviceFabricAPIVersion)
q.Add("resource", strings.Join(scopes, " ")) q.Set("resource", strings.Join(scopes, " "))
if id != nil {
log.Write(EventAuthentication, "WARNING: Service Fabric doesn't support selecting a user-assigned identity at runtime")
if id.idKind() == miResourceID {
q.Add(miResID, id.String())
} else {
q.Add(qpClientID, id.String())
}
}
request.Raw().URL.RawQuery = q.Encode() request.Raw().URL.RawQuery = q.Encode()
return request, nil return request, nil
} }
@ -409,8 +430,8 @@ func (c *managedIdentityClient) getAzureArcSecretKey(ctx context.Context, resour
} }
request.Raw().Header.Set(headerMetadata, "true") request.Raw().Header.Set(headerMetadata, "true")
q := request.Raw().URL.Query() q := request.Raw().URL.Query()
q.Add("api-version", azureArcAPIVersion) q.Set("api-version", azureArcAPIVersion)
q.Add("resource", strings.Join(resources, " ")) q.Set("resource", strings.Join(resources, " "))
request.Raw().URL.RawQuery = q.Encode() request.Raw().URL.RawQuery = q.Encode()
// send the initial request to get the short-lived secret key // send the initial request to get the short-lived secret key
response, err := c.azClient.Pipeline().Do(request) response, err := c.azClient.Pipeline().Do(request)
@ -421,39 +442,39 @@ func (c *managedIdentityClient) getAzureArcSecretKey(ctx context.Context, resour
// of the secret key file. Any other status code indicates an error in the request. // of the secret key file. Any other status code indicates an error in the request.
if response.StatusCode != 401 { if response.StatusCode != 401 {
msg := fmt.Sprintf("expected a 401 response, received %d", response.StatusCode) msg := fmt.Sprintf("expected a 401 response, received %d", response.StatusCode)
return "", newAuthenticationFailedError(credNameManagedIdentity, msg, response, nil) return "", newAuthenticationFailedError(credNameManagedIdentity, msg, response)
} }
header := response.Header.Get("WWW-Authenticate") header := response.Header.Get("WWW-Authenticate")
if len(header) == 0 { if len(header) == 0 {
return "", newAuthenticationFailedError(credNameManagedIdentity, "HIMDS response has no WWW-Authenticate header", nil, nil) return "", newAuthenticationFailedError(credNameManagedIdentity, "HIMDS response has no WWW-Authenticate header", nil)
} }
// the WWW-Authenticate header is expected in the following format: Basic realm=/some/file/path.key // the WWW-Authenticate header is expected in the following format: Basic realm=/some/file/path.key
_, p, found := strings.Cut(header, "=") _, p, found := strings.Cut(header, "=")
if !found { if !found {
return "", newAuthenticationFailedError(credNameManagedIdentity, "unexpected WWW-Authenticate header from HIMDS: "+header, nil, nil) return "", newAuthenticationFailedError(credNameManagedIdentity, "unexpected WWW-Authenticate header from HIMDS: "+header, nil)
} }
expected, err := arcKeyDirectory() expected, err := arcKeyDirectory()
if err != nil { if err != nil {
return "", err return "", err
} }
if filepath.Dir(p) != expected || !strings.HasSuffix(p, ".key") { if filepath.Dir(p) != expected || !strings.HasSuffix(p, ".key") {
return "", newAuthenticationFailedError(credNameManagedIdentity, "unexpected file path from HIMDS service: "+p, nil, nil) return "", newAuthenticationFailedError(credNameManagedIdentity, "unexpected file path from HIMDS service: "+p, nil)
} }
f, err := os.Stat(p) f, err := os.Stat(p)
if err != nil { if err != nil {
return "", newAuthenticationFailedError(credNameManagedIdentity, fmt.Sprintf("could not stat %q: %v", p, err), nil, nil) return "", newAuthenticationFailedError(credNameManagedIdentity, fmt.Sprintf("could not stat %q: %v", p, err), nil)
} }
if s := f.Size(); s > 4096 { if s := f.Size(); s > 4096 {
return "", newAuthenticationFailedError(credNameManagedIdentity, fmt.Sprintf("key is too large (%d bytes)", s), nil, nil) return "", newAuthenticationFailedError(credNameManagedIdentity, fmt.Sprintf("key is too large (%d bytes)", s), nil)
} }
key, err := os.ReadFile(p) key, err := os.ReadFile(p)
if err != nil { if err != nil {
return "", newAuthenticationFailedError(credNameManagedIdentity, fmt.Sprintf("could not read %q: %v", p, err), nil, nil) return "", newAuthenticationFailedError(credNameManagedIdentity, fmt.Sprintf("could not read %q: %v", p, err), nil)
} }
return string(key), nil return string(key), nil
} }
func (c *managedIdentityClient) createAzureArcAuthRequest(ctx context.Context, id ManagedIDKind, resources []string, key string) (*policy.Request, error) { func (c *managedIdentityClient) createAzureArcAuthRequest(ctx context.Context, resources []string, key string) (*policy.Request, error) {
request, err := azruntime.NewRequest(ctx, http.MethodGet, c.endpoint) request, err := azruntime.NewRequest(ctx, http.MethodGet, c.endpoint)
if err != nil { if err != nil {
return nil, err return nil, err
@ -461,21 +482,13 @@ func (c *managedIdentityClient) createAzureArcAuthRequest(ctx context.Context, i
request.Raw().Header.Set(headerMetadata, "true") request.Raw().Header.Set(headerMetadata, "true")
request.Raw().Header.Set("Authorization", fmt.Sprintf("Basic %s", key)) request.Raw().Header.Set("Authorization", fmt.Sprintf("Basic %s", key))
q := request.Raw().URL.Query() q := request.Raw().URL.Query()
q.Add("api-version", azureArcAPIVersion) q.Set("api-version", azureArcAPIVersion)
q.Add("resource", strings.Join(resources, " ")) q.Set("resource", strings.Join(resources, " "))
if id != nil {
log.Write(EventAuthentication, "WARNING: Azure Arc doesn't support user-assigned managed identities")
if id.idKind() == miResourceID {
q.Add(miResID, id.String())
} else {
q.Add(qpClientID, id.String())
}
}
request.Raw().URL.RawQuery = q.Encode() request.Raw().URL.RawQuery = q.Encode()
return request, nil return request, nil
} }
func (c *managedIdentityClient) createCloudShellAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { func (c *managedIdentityClient) createCloudShellAuthRequest(ctx context.Context, scopes []string) (*policy.Request, error) {
request, err := azruntime.NewRequest(ctx, http.MethodPost, c.endpoint) request, err := azruntime.NewRequest(ctx, http.MethodPost, c.endpoint)
if err != nil { if err != nil {
return nil, err return nil, err
@ -488,14 +501,5 @@ func (c *managedIdentityClient) createCloudShellAuthRequest(ctx context.Context,
if err := request.SetBody(body, "application/x-www-form-urlencoded"); err != nil { if err := request.SetBody(body, "application/x-www-form-urlencoded"); err != nil {
return nil, err return nil, err
} }
if id != nil {
log.Write(EventAuthentication, "WARNING: Cloud Shell doesn't support user-assigned managed identities")
q := request.Raw().URL.Query()
if id.idKind() == miResourceID {
q.Add(miResID, id.String())
} else {
q.Add(qpClientID, id.String())
}
}
return request, nil return request, nil
} }

View File

@ -22,8 +22,9 @@ const credNameManagedIdentity = "ManagedIdentityCredential"
type managedIdentityIDKind int type managedIdentityIDKind int
const ( const (
miClientID managedIdentityIDKind = 0 miClientID managedIdentityIDKind = iota
miResourceID managedIdentityIDKind = 1 miObjectID
miResourceID
) )
// ManagedIDKind identifies the ID of a managed identity as either a client or resource ID // ManagedIDKind identifies the ID of a managed identity as either a client or resource ID
@ -32,7 +33,12 @@ type ManagedIDKind interface {
idKind() managedIdentityIDKind idKind() managedIdentityIDKind
} }
// ClientID is the client ID of a user-assigned managed identity. // ClientID is the client ID of a user-assigned managed identity. [NewManagedIdentityCredential]
// returns an error when a ClientID is specified on the following platforms:
//
// - Azure Arc
// - Cloud Shell
// - Service Fabric
type ClientID string type ClientID string
func (ClientID) idKind() managedIdentityIDKind { func (ClientID) idKind() managedIdentityIDKind {
@ -44,7 +50,31 @@ func (c ClientID) String() string {
return string(c) return string(c)
} }
// ResourceID is the resource ID of a user-assigned managed identity. // ObjectID is the object ID of a user-assigned managed identity. [NewManagedIdentityCredential]
// returns an error when an ObjectID is specified on the following platforms:
//
// - Azure Arc
// - Azure ML
// - Cloud Shell
// - Service Fabric
type ObjectID string
func (ObjectID) idKind() managedIdentityIDKind {
return miObjectID
}
// String returns the string value of the ID.
func (o ObjectID) String() string {
return string(o)
}
// ResourceID is the resource ID of a user-assigned managed identity. [NewManagedIdentityCredential]
// returns an error when a ResourceID is specified on the following platforms:
//
// - Azure Arc
// - Azure ML
// - Cloud Shell
// - Service Fabric
type ResourceID string type ResourceID string
func (ResourceID) idKind() managedIdentityIDKind { func (ResourceID) idKind() managedIdentityIDKind {
@ -60,9 +90,10 @@ func (r ResourceID) String() string {
type ManagedIdentityCredentialOptions struct { type ManagedIdentityCredentialOptions struct {
azcore.ClientOptions azcore.ClientOptions
// ID is the ID of a managed identity the credential should authenticate. Set this field to use a specific identity // ID of a managed identity the credential should authenticate. Set this field to use a specific identity instead of
// instead of the hosting environment's default. The value may be the identity's client ID or resource ID, but note that // the hosting environment's default. The value may be the identity's client, object, or resource ID.
// some platforms don't accept resource IDs. // NewManagedIdentityCredential returns an error when the hosting environment doesn't support user-assigned managed
// identities, or the specified kind of ID.
ID ManagedIDKind ID ManagedIDKind
// dac indicates whether the credential is part of DefaultAzureCredential. When true, and the environment doesn't have // dac indicates whether the credential is part of DefaultAzureCredential. When true, and the environment doesn't have
@ -73,10 +104,11 @@ type ManagedIdentityCredentialOptions struct {
dac bool dac bool
} }
// ManagedIdentityCredential authenticates an Azure managed identity in any hosting environment supporting managed identities. // ManagedIdentityCredential authenticates an [Azure managed identity] in any hosting environment supporting managed identities.
// This credential authenticates a system-assigned identity by default. Use ManagedIdentityCredentialOptions.ID to specify a // This credential authenticates a system-assigned identity by default. Use ManagedIdentityCredentialOptions.ID to specify a
// user-assigned identity. See Microsoft Entra ID documentation for more information about managed identities: // user-assigned identity.
// https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/overview //
// [Azure managed identity]: https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/overview
type ManagedIdentityCredential struct { type ManagedIdentityCredential struct {
client *confidentialClient client *confidentialClient
mic *managedIdentityClient mic *managedIdentityClient

View File

@ -30,12 +30,12 @@ type publicClientOptions struct {
azcore.ClientOptions azcore.ClientOptions
AdditionallyAllowedTenants []string AdditionallyAllowedTenants []string
Cache Cache
DeviceCodePrompt func(context.Context, DeviceCodeMessage) error DeviceCodePrompt func(context.Context, DeviceCodeMessage) error
DisableAutomaticAuthentication bool DisableAutomaticAuthentication bool
DisableInstanceDiscovery bool DisableInstanceDiscovery bool
LoginHint, RedirectURL string LoginHint, RedirectURL string
Record authenticationRecord Record AuthenticationRecord
TokenCachePersistenceOptions *tokenCachePersistenceOptions
Username, Password string Username, Password string
} }
@ -48,7 +48,7 @@ type publicClient struct {
host string host string
name string name string
opts publicClientOptions opts publicClientOptions
record authenticationRecord record AuthenticationRecord
azClient *azcore.Client azClient *azcore.Client
} }
@ -107,19 +107,19 @@ func newPublicClient(tenantID, clientID, name string, o publicClientOptions) (*p
}, nil }, nil
} }
func (p *publicClient) Authenticate(ctx context.Context, tro *policy.TokenRequestOptions) (authenticationRecord, error) { func (p *publicClient) Authenticate(ctx context.Context, tro *policy.TokenRequestOptions) (AuthenticationRecord, error) {
if tro == nil { if tro == nil {
tro = &policy.TokenRequestOptions{} tro = &policy.TokenRequestOptions{}
} }
if len(tro.Scopes) == 0 { if len(tro.Scopes) == 0 {
if p.defaultScope == nil { if p.defaultScope == nil {
return authenticationRecord{}, errScopeRequired return AuthenticationRecord{}, errScopeRequired
} }
tro.Scopes = p.defaultScope tro.Scopes = p.defaultScope
} }
client, mu, err := p.client(*tro) client, mu, err := p.client(*tro)
if err != nil { if err != nil {
return authenticationRecord{}, err return AuthenticationRecord{}, err
} }
mu.Lock() mu.Lock()
defer mu.Unlock() defer mu.Unlock()
@ -152,7 +152,7 @@ func (p *publicClient) GetToken(ctx context.Context, tro policy.TokenRequestOpti
return p.token(ar, err) return p.token(ar, err)
} }
if p.opts.DisableAutomaticAuthentication { if p.opts.DisableAutomaticAuthentication {
return azcore.AccessToken{}, newauthenticationRequiredError(p.name, tro) return azcore.AccessToken{}, newAuthenticationRequiredError(p.name, tro)
} }
at, err := p.reqToken(ctx, client, tro) at, err := p.reqToken(ctx, client, tro)
if err == nil { if err == nil {
@ -222,13 +222,13 @@ func (p *publicClient) client(tro policy.TokenRequestOptions) (msalPublicClient,
} }
func (p *publicClient) newMSALClient(enableCAE bool) (msalPublicClient, error) { func (p *publicClient) newMSALClient(enableCAE bool) (msalPublicClient, error) {
cache, err := internal.NewCache(p.opts.TokenCachePersistenceOptions, enableCAE) c, err := internal.ExportReplace(p.opts.Cache, enableCAE)
if err != nil { if err != nil {
return nil, err return nil, err
} }
o := []public.Option{ o := []public.Option{
public.WithAuthority(runtime.JoinPaths(p.host, p.tenantID)), public.WithAuthority(runtime.JoinPaths(p.host, p.tenantID)),
public.WithCache(cache), public.WithCache(c),
public.WithHTTPClient(p), public.WithHTTPClient(p),
} }
if enableCAE { if enableCAE {
@ -244,8 +244,7 @@ func (p *publicClient) token(ar public.AuthResult, err error) (azcore.AccessToke
if err == nil { if err == nil {
p.record, err = newAuthenticationRecord(ar) p.record, err = newAuthenticationRecord(ar)
} else { } else {
res := getResponseFromError(err) err = newAuthenticationFailedErrorFromMSAL(p.name, err)
err = newAuthenticationFailedError(p.name, err.Error(), res, err)
} }
return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err
} }

View File

@ -5,7 +5,19 @@
param ( param (
[hashtable] $AdditionalParameters = @{}, [hashtable] $AdditionalParameters = @{},
[hashtable] $DeploymentOutputs [hashtable] $DeploymentOutputs,
[Parameter(ParameterSetName = 'Provisioner', Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string] $TenantId,
[Parameter()]
[ValidatePattern('^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$')]
[string] $TestApplicationId,
# Captures any arguments from eng/New-TestResources.ps1 not declared here (no parameter errors).
[Parameter(ValueFromRemainingArguments = $true)]
$RemainingArguments
) )
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
@ -16,14 +28,14 @@ if ($CI) {
Write-Host "Skipping post-provisioning script because resources weren't deployed" Write-Host "Skipping post-provisioning script because resources weren't deployed"
return return
} }
az login --service-principal -u $DeploymentOutputs['AZIDENTITY_CLIENT_ID'] -p $DeploymentOutputs['AZIDENTITY_CLIENT_SECRET'] --tenant $DeploymentOutputs['AZIDENTITY_TENANT_ID'] az login --federated-token $env:OIDC_TOKEN --service-principal -t $TenantId -u $TestApplicationId
az account set --subscription $DeploymentOutputs['AZIDENTITY_SUBSCRIPTION_ID'] az account set --subscription $DeploymentOutputs['AZIDENTITY_SUBSCRIPTION_ID']
} }
Write-Host "Building container" Write-Host "Building container"
$image = "$($DeploymentOutputs['AZIDENTITY_ACR_LOGIN_SERVER'])/azidentity-managed-id-test" $image = "$($DeploymentOutputs['AZIDENTITY_ACR_LOGIN_SERVER'])/azidentity-managed-id-test"
Set-Content -Path "$PSScriptRoot/Dockerfile" -Value @" Set-Content -Path "$PSScriptRoot/Dockerfile" -Value @"
FROM mcr.microsoft.com/oss/go/microsoft/golang:latest as builder FROM mcr.microsoft.com/oss/go/microsoft/golang:latest AS builder
ENV GOARCH=amd64 GOWORK=off ENV GOARCH=amd64 GOWORK=off
COPY . /azidentity COPY . /azidentity
WORKDIR /azidentity/testdata/managed-id-test WORKDIR /azidentity/testdata/managed-id-test
@ -55,6 +67,8 @@ az container create -g $rg -n $aciName --image $image `
-e AZIDENTITY_STORAGE_NAME=$($DeploymentOutputs['AZIDENTITY_STORAGE_NAME']) ` -e AZIDENTITY_STORAGE_NAME=$($DeploymentOutputs['AZIDENTITY_STORAGE_NAME']) `
AZIDENTITY_STORAGE_NAME_USER_ASSIGNED=$($DeploymentOutputs['AZIDENTITY_STORAGE_NAME_USER_ASSIGNED']) ` AZIDENTITY_STORAGE_NAME_USER_ASSIGNED=$($DeploymentOutputs['AZIDENTITY_STORAGE_NAME_USER_ASSIGNED']) `
AZIDENTITY_USER_ASSIGNED_IDENTITY=$($DeploymentOutputs['AZIDENTITY_USER_ASSIGNED_IDENTITY']) ` AZIDENTITY_USER_ASSIGNED_IDENTITY=$($DeploymentOutputs['AZIDENTITY_USER_ASSIGNED_IDENTITY']) `
AZIDENTITY_USER_ASSIGNED_IDENTITY_CLIENT_ID=$($DeploymentOutputs['AZIDENTITY_USER_ASSIGNED_IDENTITY_CLIENT_ID']) `
AZIDENTITY_USER_ASSIGNED_IDENTITY_OBJECT_ID=$($DeploymentOutputs['AZIDENTITY_USER_ASSIGNED_IDENTITY_OBJECT_ID']) `
FUNCTIONS_CUSTOMHANDLER_PORT=80 FUNCTIONS_CUSTOMHANDLER_PORT=80
Write-Host "##vso[task.setvariable variable=AZIDENTITY_ACI_NAME;]$aciName" Write-Host "##vso[task.setvariable variable=AZIDENTITY_ACI_NAME;]$aciName"

View File

@ -135,6 +135,14 @@ resource azfunc 'Microsoft.Web/sites@2021-03-01' = if (deployResources) {
name: 'AZIDENTITY_USER_ASSIGNED_IDENTITY' name: 'AZIDENTITY_USER_ASSIGNED_IDENTITY'
value: deployResources ? usermgdid.id : null value: deployResources ? usermgdid.id : null
} }
{
name: 'AZIDENTITY_USER_ASSIGNED_IDENTITY_CLIENT_ID'
value: deployResources ? usermgdid.properties.clientId : null
}
{
name: 'AZIDENTITY_USER_ASSIGNED_IDENTITY_OBJECT_ID'
value: deployResources ? usermgdid.properties.principalId : null
}
{ {
name: 'AzureWebJobsStorage' name: 'AzureWebJobsStorage'
value: 'DefaultEndpointsProtocol=https;AccountName=${deployResources ? sa.name : ''};EndpointSuffix=${deployResources ? environment().suffixes.storage : ''};AccountKey=${deployResources ? sa.listKeys().keys[0].value : ''}' value: 'DefaultEndpointsProtocol=https;AccountName=${deployResources ? sa.name : ''};EndpointSuffix=${deployResources ? environment().suffixes.storage : ''};AccountKey=${deployResources ? sa.listKeys().keys[0].value : ''}'
@ -217,3 +225,4 @@ output AZIDENTITY_STORAGE_NAME_USER_ASSIGNED string = deployResources ? saUserAs
output AZIDENTITY_USER_ASSIGNED_IDENTITY string = deployResources ? usermgdid.id : '' output AZIDENTITY_USER_ASSIGNED_IDENTITY string = deployResources ? usermgdid.id : ''
output AZIDENTITY_USER_ASSIGNED_IDENTITY_CLIENT_ID string = deployResources ? usermgdid.properties.clientId : '' output AZIDENTITY_USER_ASSIGNED_IDENTITY_CLIENT_ID string = deployResources ? usermgdid.properties.clientId : ''
output AZIDENTITY_USER_ASSIGNED_IDENTITY_NAME string = deployResources ? usermgdid.name : '' output AZIDENTITY_USER_ASSIGNED_IDENTITY_NAME string = deployResources ? usermgdid.name : ''
output AZIDENTITY_USER_ASSIGNED_IDENTITY_OBJECT_ID string = deployResources ? usermgdid.properties.principalId : ''

View File

@ -25,18 +25,20 @@ type UsernamePasswordCredentialOptions struct {
// application is registered. // application is registered.
AdditionallyAllowedTenants []string AdditionallyAllowedTenants []string
// authenticationRecord returned by a call to a credential's Authenticate method. Set this option // AuthenticationRecord returned by a call to a credential's Authenticate method. Set this option
// to enable the credential to use data from a previous authentication. // to enable the credential to use data from a previous authentication.
authenticationRecord authenticationRecord AuthenticationRecord AuthenticationRecord
// Cache is a persistent cache the credential will use to store the tokens it acquires, making
// them available to other processes and credential instances. The default, zero value means the
// credential will store tokens in memory and not share them with any other credential instance.
Cache Cache
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata
// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
// the application responsible for ensuring the configured authority is valid and trustworthy. // the application responsible for ensuring the configured authority is valid and trustworthy.
DisableInstanceDiscovery bool DisableInstanceDiscovery bool
// tokenCachePersistenceOptions enables persistent token caching when not nil.
tokenCachePersistenceOptions *tokenCachePersistenceOptions
} }
// UsernamePasswordCredential authenticates a user with a password. Microsoft doesn't recommend this kind of authentication, // UsernamePasswordCredential authenticates a user with a password. Microsoft doesn't recommend this kind of authentication,
@ -55,11 +57,11 @@ func NewUsernamePasswordCredential(tenantID string, clientID string, username st
} }
opts := publicClientOptions{ opts := publicClientOptions{
AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, AdditionallyAllowedTenants: options.AdditionallyAllowedTenants,
Cache: options.Cache,
ClientOptions: options.ClientOptions, ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery, DisableInstanceDiscovery: options.DisableInstanceDiscovery,
Password: password, Password: password,
Record: options.authenticationRecord, Record: options.AuthenticationRecord,
TokenCachePersistenceOptions: options.tokenCachePersistenceOptions,
Username: username, Username: username,
} }
c, err := newPublicClient(tenantID, clientID, credNameUserPassword, opts) c, err := newPublicClient(tenantID, clientID, credNameUserPassword, opts)
@ -70,7 +72,7 @@ func NewUsernamePasswordCredential(tenantID string, clientID string, username st
} }
// Authenticate the user. Subsequent calls to GetToken will automatically use the returned AuthenticationRecord. // Authenticate the user. Subsequent calls to GetToken will automatically use the returned AuthenticationRecord.
func (c *UsernamePasswordCredential) authenticate(ctx context.Context, opts *policy.TokenRequestOptions) (authenticationRecord, error) { func (c *UsernamePasswordCredential) Authenticate(ctx context.Context, opts *policy.TokenRequestOptions) (AuthenticationRecord, error) {
var err error var err error
ctx, endSpan := runtime.StartSpan(ctx, credNameUserPassword+"."+traceOpAuthenticate, c.client.azClient.Tracer(), nil) ctx, endSpan := runtime.StartSpan(ctx, credNameUserPassword+"."+traceOpAuthenticate, c.client.azClient.Tracer(), nil)
defer func() { endSpan(err) }() defer func() { endSpan(err) }()

View File

@ -14,5 +14,5 @@ const (
module = "github.com/Azure/azure-sdk-for-go/sdk/" + component module = "github.com/Azure/azure-sdk-for-go/sdk/" + component
// Version is the semantic version (see http://semver.org) of this module. // Version is the semantic version (see http://semver.org) of this module.
version = "v1.7.0" version = "v1.8.0"
) )

View File

@ -39,15 +39,24 @@ type WorkloadIdentityCredentialOptions struct {
// Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the // Add the wildcard value "*" to allow the credential to acquire tokens for any tenant in which the
// application is registered. // application is registered.
AdditionallyAllowedTenants []string AdditionallyAllowedTenants []string
// Cache is a persistent cache the credential will use to store the tokens it acquires, making
// them available to other processes and credential instances. The default, zero value means the
// credential will store tokens in memory and not share them with any other credential instance.
Cache Cache
// ClientID of the service principal. Defaults to the value of the environment variable AZURE_CLIENT_ID. // ClientID of the service principal. Defaults to the value of the environment variable AZURE_CLIENT_ID.
ClientID string ClientID string
// DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or
// private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata
// from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making
// the application responsible for ensuring the configured authority is valid and trustworthy. // the application responsible for ensuring the configured authority is valid and trustworthy.
DisableInstanceDiscovery bool DisableInstanceDiscovery bool
// TenantID of the service principal. Defaults to the value of the environment variable AZURE_TENANT_ID. // TenantID of the service principal. Defaults to the value of the environment variable AZURE_TENANT_ID.
TenantID string TenantID string
// TokenFilePath is the path of a file containing a Kubernetes service account token. Defaults to the value of the // TokenFilePath is the path of a file containing a Kubernetes service account token. Defaults to the value of the
// environment variable AZURE_FEDERATED_TOKEN_FILE. // environment variable AZURE_FEDERATED_TOKEN_FILE.
TokenFilePath string TokenFilePath string
@ -81,6 +90,7 @@ func NewWorkloadIdentityCredential(options *WorkloadIdentityCredentialOptions) (
w := WorkloadIdentityCredential{file: file, mtx: &sync.RWMutex{}} w := WorkloadIdentityCredential{file: file, mtx: &sync.RWMutex{}}
caco := ClientAssertionCredentialOptions{ caco := ClientAssertionCredentialOptions{
AdditionallyAllowedTenants: options.AdditionallyAllowedTenants, AdditionallyAllowedTenants: options.AdditionallyAllowedTenants,
Cache: options.Cache,
ClientOptions: options.ClientOptions, ClientOptions: options.ClientOptions,
DisableInstanceDiscovery: options.DisableInstanceDiscovery, DisableInstanceDiscovery: options.DisableInstanceDiscovery,
} }

View File

@ -3,4 +3,4 @@
package aws package aws
// goModuleVersion is the tagged release for this module // goModuleVersion is the tagged release for this module
const goModuleVersion = "1.32.1" const goModuleVersion = "1.32.2"

View File

@ -85,6 +85,7 @@ const (
UserAgentFeatureS3ExpressBucket = "J" UserAgentFeatureS3ExpressBucket = "J"
UserAgentFeatureS3AccessGrants = "K" // not yet implemented UserAgentFeatureS3AccessGrants = "K" // not yet implemented
UserAgentFeatureGZIPRequestCompression = "L" UserAgentFeatureGZIPRequestCompression = "L"
UserAgentFeatureProtocolRPCV2CBOR = "M"
) )
// RequestUserAgent is a build middleware that set the User-Agent for the request. // RequestUserAgent is a build middleware that set the User-Agent for the request.

View File

@ -1,3 +1,7 @@
# v1.3.21 (2024-10-08)
* **Dependency Update**: Updated to the latest SDK module versions
# v1.3.20 (2024-10-07) # v1.3.20 (2024-10-07)
* **Dependency Update**: Updated to the latest SDK module versions * **Dependency Update**: Updated to the latest SDK module versions

View File

@ -3,4 +3,4 @@
package configsources package configsources
// goModuleVersion is the tagged release for this module // goModuleVersion is the tagged release for this module
const goModuleVersion = "1.3.20" const goModuleVersion = "1.3.21"

View File

@ -1,3 +1,7 @@
# v2.6.21 (2024-10-08)
* **Dependency Update**: Updated to the latest SDK module versions
# v2.6.20 (2024-10-07) # v2.6.20 (2024-10-07)
* **Dependency Update**: Updated to the latest SDK module versions * **Dependency Update**: Updated to the latest SDK module versions

View File

@ -3,4 +3,4 @@
package endpoints package endpoints
// goModuleVersion is the tagged release for this module // goModuleVersion is the tagged release for this module
const goModuleVersion = "2.6.20" const goModuleVersion = "2.6.21"

View File

@ -1,3 +1,7 @@
# v1.12.2 (2024-10-08)
* **Dependency Update**: Updated to the latest SDK module versions
# v1.12.1 (2024-10-07) # v1.12.1 (2024-10-07)
* **Dependency Update**: Updated to the latest SDK module versions * **Dependency Update**: Updated to the latest SDK module versions

View File

@ -3,4 +3,4 @@
package presignedurl package presignedurl
// goModuleVersion is the tagged release for this module // goModuleVersion is the tagged release for this module
const goModuleVersion = "1.12.1" const goModuleVersion = "1.12.2"

View File

@ -1,3 +1,7 @@
# v1.32.2 (2024-10-08)
* **Dependency Update**: Updated to the latest SDK module versions
# v1.32.1 (2024-10-07) # v1.32.1 (2024-10-07)
* **Dependency Update**: Updated to the latest SDK module versions * **Dependency Update**: Updated to the latest SDK module versions

View File

@ -3,4 +3,4 @@
package sts package sts
// goModuleVersion is the tagged release for this module // goModuleVersion is the tagged release for this module
const goModuleVersion = "1.32.1" const goModuleVersion = "1.32.2"

16
vendor/modules.txt vendored
View File

@ -1,4 +1,4 @@
# github.com/Azure/azure-sdk-for-go/sdk/azcore v1.11.1 # github.com/Azure/azure-sdk-for-go/sdk/azcore v1.14.0
## explicit; go 1.18 ## explicit; go 1.18
github.com/Azure/azure-sdk-for-go/sdk/azcore github.com/Azure/azure-sdk-for-go/sdk/azcore
github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/internal/resource github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/internal/resource
@ -20,11 +20,11 @@ github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime
github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming
github.com/Azure/azure-sdk-for-go/sdk/azcore/to github.com/Azure/azure-sdk-for-go/sdk/azcore/to
github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing
# github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 # github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0
## explicit; go 1.18 ## explicit; go 1.18
github.com/Azure/azure-sdk-for-go/sdk/azidentity github.com/Azure/azure-sdk-for-go/sdk/azidentity
github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal
# github.com/Azure/azure-sdk-for-go/sdk/internal v1.8.0 # github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0
## explicit; go 1.18 ## explicit; go 1.18
github.com/Azure/azure-sdk-for-go/sdk/internal/diag github.com/Azure/azure-sdk-for-go/sdk/internal/diag
github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo
@ -126,7 +126,7 @@ github.com/aws/aws-sdk-go/service/sso/ssoiface
github.com/aws/aws-sdk-go/service/ssooidc github.com/aws/aws-sdk-go/service/ssooidc
github.com/aws/aws-sdk-go/service/sts github.com/aws/aws-sdk-go/service/sts
github.com/aws/aws-sdk-go/service/sts/stsiface github.com/aws/aws-sdk-go/service/sts/stsiface
# github.com/aws/aws-sdk-go-v2 v1.32.1 # github.com/aws/aws-sdk-go-v2 v1.32.2
## explicit; go 1.21 ## explicit; go 1.21
github.com/aws/aws-sdk-go-v2/aws github.com/aws/aws-sdk-go-v2/aws
github.com/aws/aws-sdk-go-v2/aws/defaults github.com/aws/aws-sdk-go-v2/aws/defaults
@ -149,19 +149,19 @@ github.com/aws/aws-sdk-go-v2/internal/sdk
github.com/aws/aws-sdk-go-v2/internal/strings github.com/aws/aws-sdk-go-v2/internal/strings
github.com/aws/aws-sdk-go-v2/internal/sync/singleflight github.com/aws/aws-sdk-go-v2/internal/sync/singleflight
github.com/aws/aws-sdk-go-v2/internal/timeconv github.com/aws/aws-sdk-go-v2/internal/timeconv
# github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.20 # github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.21
## explicit; go 1.21 ## explicit; go 1.21
github.com/aws/aws-sdk-go-v2/internal/configsources github.com/aws/aws-sdk-go-v2/internal/configsources
# github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.20 # github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.21
## explicit; go 1.21 ## explicit; go 1.21
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 github.com/aws/aws-sdk-go-v2/internal/endpoints/v2
# github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.0 # github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.0
## explicit; go 1.21 ## explicit; go 1.21
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding
# github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.1 # github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.2
## explicit; go 1.21 ## explicit; go 1.21
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url github.com/aws/aws-sdk-go-v2/service/internal/presigned-url
# github.com/aws/aws-sdk-go-v2/service/sts v1.32.1 # github.com/aws/aws-sdk-go-v2/service/sts v1.32.2
## explicit; go 1.21 ## explicit; go 1.21
github.com/aws/aws-sdk-go-v2/service/sts github.com/aws/aws-sdk-go-v2/service/sts
github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints