-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
285 lines (246 loc) · 8.27 KB
/
parser.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package azcfg
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"errors"
"fmt"
"net/http"
"os"
"time"
"github.com/KarlGW/azcfg/auth"
"github.com/KarlGW/azcfg/azure/cloud"
"github.com/KarlGW/azcfg/internal/httpr"
"github.com/KarlGW/azcfg/internal/identity"
"github.com/KarlGW/azcfg/internal/secret"
"github.com/KarlGW/azcfg/internal/setting"
)
// Parser provides a method to parse secrets and settings into a struct.
type Parser interface {
Parse(ctx context.Context, v any) error
}
// HTTPClient is an HTTP client with a Do method.
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
// Secret represents a secret as returned from the Key Vault REST API.
type Secret = secret.Secret
// SecretOptions contains options for SecretClient operations.
type SecretOptions = secret.Options
// SecretOption is a function that sets an option on a SecretClient.
type SecretOption = secret.Option
// SecretClient is the interface that wraps around method GetSecrets.
type SecretClient interface {
GetSecrets(ctx context.Context, names []string, options ...SecretOption) (map[string]Secret, error)
}
// Setting represents a setting as returned from the App Config REST API.
type Setting = setting.Setting
// SettingOptions contains options for SettingClient operations.
type SettingOptions = setting.Options
// SettingOption is a function that sets an option on a SettingClient.
type SettingOption = setting.Option
// SettingClient is the interface that wraps around method GetSettings.
type SettingClient interface {
GetSettings(ctx context.Context, keys []string, options ...SettingOption) (map[string]Setting, error)
}
// RetryPolicy contains rules for retries.
type RetryPolicy = httpr.RetryPolicy
// parser contains all the necessary values and settings for calls to
// Parse.
type parser struct {
secretClient SecretClient
settingClient SettingClient
timeout time.Duration
}
// NewParser creates and returns a Parser. This suits situations
// where multiple calls to Parse are needed with the same settings.
func NewParser(options ...Option) (Parser, error) {
opts := defaultOptions()
for _, option := range options {
option(&opts)
}
var httpClient HTTPClient
if opts.httpClient == nil {
httpClient = httpr.NewClient(
httpr.WithTimeout(opts.Timeout),
httpr.WithRetryPolicy(opts.RetryPolicy),
)
} else {
httpClient = opts.httpClient
}
var cred auth.Credential
if opts.Credential != nil {
cred = opts.Credential
}
var secretClient SecretClient
if opts.SecretClient == nil && len(opts.KeyVault) > 0 {
var err error
if cred == nil {
cred, err = setupCredential(opts.Cloud, opts.Authentication.Entra)
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrCredential, err.Error())
}
}
concurrency := opts.Concurrency
if len(opts.AppConfiguration) > 0 || len(opts.Authentication.AppConfigurationConnectionString) > 0 {
concurrency /= 2
}
secretClient, err = secret.NewClient(
opts.KeyVault,
cred,
secret.WithHTTPClient(httpClient),
secret.WithConcurrency(concurrency),
secret.WithCloud(opts.Cloud),
secret.WithClientVersions(opts.SecretsVersions),
)
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrSecretClient, err.Error())
}
} else {
secretClient = opts.SecretClient
}
var settingClient SettingClient
if opts.SettingClient == nil && len(opts.AppConfiguration) > 0 || len(opts.Authentication.AppConfigurationConnectionString) > 0 {
var err error
if opts.Authentication.AppConfigurationAccessKey == (AppConfigurationAccessKey{}) && len(opts.Authentication.AppConfigurationConnectionString) == 0 {
if cred == nil {
cred, err = setupCredential(opts.Cloud, opts.Authentication.Entra)
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrCredential, err.Error())
}
}
}
concurrency := opts.Concurrency
if len(opts.KeyVault) > 0 {
concurrency /= 2
}
options := []setting.ClientOption{
setting.WithHTTPClient(httpClient),
setting.WithConcurrency(concurrency),
setting.WithCloud(opts.Cloud),
setting.WithClientLabel(opts.SettingsLabel),
setting.WithClientLabels(opts.SettingsLabels),
}
settingClient, err = newSettingClient(
settings{
credential: cred,
appConfiguration: opts.AppConfiguration,
accessKey: opts.Authentication.AppConfigurationAccessKey,
connectionString: opts.Authentication.AppConfigurationConnectionString,
},
options...,
)
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrSettingClient, err.Error())
}
} else {
settingClient = opts.SettingClient
}
return &parser{
secretClient: secretClient,
settingClient: settingClient,
timeout: opts.Timeout,
}, nil
}
// Parse secrets from an Azure Key Vault and settings from an
// Azure App Configuration into the provided struct.
func (p *parser) Parse(ctx context.Context, v any) error {
if err := parse(ctx, v, p.secretClient, p.settingClient); err != nil {
return fmt.Errorf("azcfg: %w", err)
}
return nil
}
// setupCredential configures credential based on the provided
// options.
func setupCredential(cloud cloud.Cloud, entra Entra) (auth.Credential, error) {
if entra.AzureCLICredential {
return identity.NewAzureCLICredential(identity.WithCloud(cloud))
}
if len(entra.TenantID) == 0 || entra.ManagedIdentity {
cred, err := identity.NewManagedIdentityCredential(
identity.WithClientID(entra.ClientID),
identity.WithCloud(cloud),
identity.WithIMDSDialTimeout(entra.ManagedIdentityIMDSDialTimeout),
)
if err != nil && !errors.Is(err, identity.ErrIMDSEndpointUnavailable) {
return nil, err
}
if cred != nil {
return cred, nil
}
}
if len(entra.ClientSecret) > 0 {
return identity.NewClientSecretCredential(entra.TenantID, entra.ClientID, entra.ClientSecret, identity.WithCloud(cloud))
}
var certs []*x509.Certificate
var key *rsa.PrivateKey
if len(entra.Certificates) > 0 && entra.PrivateKey != nil {
certs, key = entra.Certificates, entra.PrivateKey
} else if len(entra.certificate) > 0 || len(entra.certificatePath) > 0 {
var err error
certs, key, err = certificateAndKey(entra.certificate, entra.certificatePath)
if err != nil {
return nil, err
}
}
if len(certs) > 0 && key != nil {
return identity.NewClientCertificateCredential(entra.TenantID, entra.ClientID, certs, key, identity.WithCloud(cloud))
}
if entra.Assertion != nil {
return identity.NewClientAssertionCredential(entra.TenantID, entra.ClientID, entra.Assertion, identity.WithCloud(cloud))
}
return nil, errors.New("could not determine and create entra credential")
}
// settings contains the necessary values for setting client creation.
type settings struct {
credential auth.Credential
accessKey AppConfigurationAccessKey
appConfiguration string
connectionString string
}
// newSettingClient creates a new setting client based on the provided settings.
func newSettingClient(settings settings, options ...setting.ClientOption) (SettingClient, error) {
if len(settings.appConfiguration) > 0 && settings.credential != nil {
return setting.NewClient(
settings.appConfiguration,
settings.credential,
options...,
)
}
if len(settings.connectionString) > 0 {
return setting.NewClientWithConnectionString(
settings.connectionString,
options...,
)
}
if len(settings.appConfiguration) > 0 && len(settings.accessKey.ID) > 0 && len(settings.accessKey.Secret) > 0 {
return setting.NewClientWithAccessKey(
settings.appConfiguration,
setting.AccessKey{
ID: settings.accessKey.ID,
Secret: settings.accessKey.Secret,
},
options...,
)
}
return nil, errors.New("could not determine and create app configuration credential")
}
// certificatesAndKeyFromPEM extracts the x509 certificates and private key from the given PEM.
var certificatesAndKeyFromPEM = identity.CertificatesAndKeyFromPEM
// certificateAndKey gets the certificates and keys from the provided certificate or certificate path.
func certificateAndKey(certificate, certificatePath string) ([]*x509.Certificate, *rsa.PrivateKey, error) {
var pem []byte
var err error
if len(certificate) > 0 {
pem, err = base64.StdEncoding.DecodeString(certificate)
} else if len(certificatePath) > 0 {
pem, err = os.ReadFile(certificatePath)
} else {
return nil, nil, nil
}
if err != nil {
return nil, nil, err
}
return certificatesAndKeyFromPEM(pem)
}