-
Notifications
You must be signed in to change notification settings - Fork 15
/
retriever_workloadidentity.go
95 lines (81 loc) · 2.31 KB
/
retriever_workloadidentity.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package aztokenprovider
import (
"context"
"fmt"
"time"
"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"
"github.com/grafana/grafana-azure-sdk-go/v2/azcredentials"
"github.com/grafana/grafana-azure-sdk-go/v2/azsettings"
)
type workloadIdentityTokenRetriever struct {
tenantId string
clientId string
tokenFile string
credential azcore.TokenCredential
}
func getWorkloadIdentityTokenRetriever(settings *azsettings.AzureSettings, credentials *azcredentials.AzureWorkloadIdentityCredentials) TokenRetriever {
tenantId := ""
clientId := ""
tokenFile := ""
if wiSettings := settings.WorkloadIdentitySettings; wiSettings != nil {
tenantId = wiSettings.TenantId
clientId = wiSettings.ClientId
tokenFile = wiSettings.TokenFile
}
if credentials != nil {
if credentials.TenantId != "" {
tenantId = credentials.TenantId
}
if credentials.ClientId != "" {
clientId = credentials.ClientId
}
}
return &workloadIdentityTokenRetriever{
tenantId: tenantId,
clientId: clientId,
tokenFile: tokenFile,
}
}
func (c *workloadIdentityTokenRetriever) GetCacheKey(grafanaMultiTenantId string) string {
tenantId := c.tenantId
if tenantId == "" {
tenantId = "default"
}
clientId := c.clientId
if clientId == "" {
clientId = "default"
}
return fmt.Sprintf("azure|wi|%s|%s|%s", tenantId, clientId, grafanaMultiTenantId)
}
func (c *workloadIdentityTokenRetriever) Init() error {
options := &azidentity.WorkloadIdentityCredentialOptions{}
if c.tenantId != "" {
options.TenantID = c.tenantId
}
if c.clientId != "" {
options.ClientID = c.clientId
}
if c.tokenFile != "" {
options.TokenFilePath = c.tokenFile
}
credential, err := azidentity.NewWorkloadIdentityCredential(options)
if err != nil {
return err
} else {
c.credential = credential
return nil
}
}
func (c *workloadIdentityTokenRetriever) GetAccessToken(ctx context.Context, scopes []string) (*AccessToken, error) {
accessToken, err := c.credential.GetToken(ctx, policy.TokenRequestOptions{Scopes: scopes})
if err != nil {
return nil, err
}
return &AccessToken{Token: accessToken.Token, ExpiresOn: accessToken.ExpiresOn}, nil
}
// Empty implementation
func (c *workloadIdentityTokenRetriever) GetExpiry() *time.Time {
return nil
}