/
azure.go
100 lines (89 loc) · 2.29 KB
/
azure.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
96
97
98
99
100
package main
import (
"context"
"crypto"
"crypto/x509"
"encoding/pem"
"fmt"
"github.com/BurntSushi/toml"
"github.com/confluentinc/confluent-kafka-go/kafka"
"os"
)
import "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential"
type AzureFetcher struct {
Authority string `toml:"authority"`
ClientId string `toml:"client-id"`
CertPath string `toml:"cert-path"`
KeyPath string `toml:"key-path"`
Scope string `toml:"scope"`
Principal string `toml:"principal"`
}
func (f *AzureFetcher) Fetch() (*kafka.OAuthBearerToken, error) {
result, err := fetchToken(
f.Authority,
f.ClientId,
f.CertPath,
f.KeyPath,
f.Scope,
)
if err != nil {
return nil, err
}
return &kafka.OAuthBearerToken{
TokenValue: result.AccessToken,
Expiration: result.ExpiresOn,
Principal: f.Principal,
}, nil
}
func NewAzureTokenFetcherFromConfig(azureConfigPath string) (*AzureFetcher, error) {
var fetcher AzureFetcher
_, err := toml.DecodeFile(azureConfigPath, &fetcher)
if err != nil {
return nil, err
}
return &fetcher, nil
}
func fetchToken(authority, clientId, certPath, keyPath, scope string) (*confidential.AuthResult, error) {
certs, err := getCerts(certPath)
if err != nil {
return nil, fmt.Errorf("failed to read cert from '%s': %w", certPath, err)
}
privateKey, err := getPrivateKey(keyPath)
if err != nil {
return nil, fmt.Errorf("failed to read private key from '%s': %w", keyPath, err)
}
cred, err := confidential.NewCredFromCert(certs, privateKey)
if err != nil {
return nil, err
}
client, err := confidential.New(authority, clientId, cred)
if err != nil {
return nil, err
}
result, err := client.AcquireTokenByCredential(context.Background(), []string{scope})
return &result, nil
}
func getCerts(path string) ([]*x509.Certificate, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
block, _ := pem.Decode(data)
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
return []*x509.Certificate{cert}, nil
}
func getPrivateKey(path string) (crypto.PrivateKey, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
block, _ := pem.Decode(data)
privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return privateKey, nil
}