Skip to content

Commit 5361cbb

Browse files
Use cloud env variable to determine token scope (#1563) (#1564)
1 parent d7d40da commit 5361cbb

File tree

2 files changed

+42
-3
lines changed

2 files changed

+42
-3
lines changed

pkg/azure/defaultazurecredential/authorizer.go

+20-3
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@ package defaultazurecredential
22

33
import (
44
"context"
5+
"fmt"
6+
"os"
57

68
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
79
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
810
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
911
"github.com/Azure/go-autorest/autorest"
12+
"github.com/Azure/go-autorest/autorest/azure"
1013
"k8s.io/klog/v2"
1114
)
1215

@@ -26,20 +29,34 @@ func NewAuthorizer() (autorest.Authorizer, error) {
2629
return nil, err
2730
}
2831

32+
scope := tokenScopeFromEnvironment()
33+
klog.V(7).Infof("Fetching token with scope %s", scope)
2934
return autorest.NewBearerAuthorizer(&tokenCredentialWrapper{
30-
cred: cred,
35+
cred: cred,
36+
scope: scope,
3137
}), nil
3238
}
3339

40+
func tokenScopeFromEnvironment() string {
41+
cloud := os.Getenv("AZURE_ENVIRONMENT")
42+
env, err := azure.EnvironmentFromName(cloud)
43+
if err != nil {
44+
env = azure.PublicCloud
45+
}
46+
47+
return fmt.Sprintf("%s.default", env.TokenAudience)
48+
}
49+
3450
type tokenCredentialWrapper struct {
35-
cred azcore.TokenCredential
51+
cred azcore.TokenCredential
52+
scope string
3653
}
3754

3855
func (w *tokenCredentialWrapper) OAuthToken() string {
3956
klog.V(7).Info("Getting Azure token using DefaultAzureCredential")
4057

4158
token, err := w.cred.GetToken(context.Background(), policy.TokenRequestOptions{
42-
Scopes: []string{"https://management.azure.com/.default"},
59+
Scopes: []string{w.scope},
4360
})
4461

4562
if err != nil {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package defaultazurecredential
2+
3+
import (
4+
"os"
5+
"testing"
6+
)
7+
8+
func TestTokenScopeFromEnvironment(t *testing.T) {
9+
scope := map[string]string{
10+
"AZUREPUBLICCLOUD": "https://management.azure.com/.default",
11+
"AZURECHINACLOUD": "https://management.chinacloudapi.cn/.default",
12+
"AZUREUSGOVERNMENTCLOUD": "https://management.usgovcloudapi.net/.default",
13+
}
14+
15+
for env, expectedScope := range scope {
16+
os.Setenv("AZURE_ENVIRONMENT", env)
17+
scope := tokenScopeFromEnvironment()
18+
if scope != expectedScope {
19+
t.Errorf("Expected scope %s, got %s", expectedScope, scope)
20+
}
21+
}
22+
}

0 commit comments

Comments
 (0)