-
Notifications
You must be signed in to change notification settings - Fork 25
/
azure_msi.go
71 lines (61 loc) · 1.74 KB
/
azure_msi.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
*/
package azure
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"k8s.io/client-go/util/retry"
"k8s.io/klog/v2"
"go.goms.io/fleet/pkg/interfaces"
)
const (
aksScope = "6dae42f8-4368-4678-94ff-3960e28e3630"
)
type AuthTokenProvider struct {
ClientID string
Scope string
}
func New(clientID, scope string) interfaces.AuthTokenProvider {
if scope == "" {
scope = aksScope
}
return &AuthTokenProvider{
ClientID: clientID,
Scope: scope,
}
}
// FetchToken gets a new token to make request to the associated fleet' hub cluster.
func (a *AuthTokenProvider) FetchToken(ctx context.Context) (interfaces.AuthToken, error) {
token := interfaces.AuthToken{}
opts := &azidentity.ManagedIdentityCredentialOptions{ID: azidentity.ClientID(a.ClientID)}
klog.V(2).InfoS("FetchToken", "client ID", a.ClientID)
credential, err := azidentity.NewManagedIdentityCredential(opts)
if err != nil {
return token, fmt.Errorf("failed to create managed identity cred: %w", err)
}
var azToken azcore.AccessToken
err = retry.OnError(retry.DefaultBackoff,
func(err error) bool {
return ctx.Err() == nil
}, func() error {
klog.V(2).InfoS("GetToken start", "credential", credential)
azToken, err = credential.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string{a.Scope},
})
if err != nil {
klog.ErrorS(err, "Failed to GetToken", "scope", a.Scope)
}
return err
})
if err != nil {
return token, fmt.Errorf("failed to get a token: %w", err)
}
token.Token = azToken.Token
token.ExpiresOn = azToken.ExpiresOn
return token, nil
}