-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathconfig.go
296 lines (267 loc) · 8.37 KB
/
config.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
286
287
288
289
290
291
292
293
294
295
296
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package config
import (
"bytes"
"crypto/tls"
"fmt"
"net/http"
"net/url"
"os"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/retry"
awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
"github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
"github.com/hashicorp/aws-sdk-go-base/v2/diag"
"github.com/hashicorp/aws-sdk-go-base/v2/internal/expand"
"github.com/hashicorp/aws-sdk-go-base/v2/logging"
"golang.org/x/net/http/httpproxy"
)
type ProxyMode int
const (
HTTPProxyModeLegacy ProxyMode = iota
HTTPProxyModeSeparate
)
type Config struct {
AccessKey string
AllowedAccountIds []string
APNInfo *APNInfo
AssumeRole []AssumeRole
AssumeRoleWithWebIdentity *AssumeRoleWithWebIdentity
Backoff retry.BackoffDelayer
CallerDocumentationURL string
CallerName string
CustomCABundle string
EC2MetadataServiceEnableState imds.ClientEnableState
EC2MetadataServiceEndpoint string
EC2MetadataServiceEndpointMode string
ForbiddenAccountIds []string
HTTPClient *http.Client
HTTPProxy *string
HTTPSProxy *string
IamEndpoint string
Insecure bool
Logger logging.Logger
MaxBackoff time.Duration
MaxRetries int
NoProxy string
Profile string
HTTPProxyMode ProxyMode
Region string
RetryMode aws.RetryMode
SecretKey string
SharedCredentialsFiles []string
SharedConfigFiles []string
SkipCredsValidation bool
SkipRequestingAccountId bool
SsoEndpoint string
StsEndpoint string
StsRegion string
SuppressDebugLog bool
Token string
TokenBucketRateLimiterCapacity int
UseDualStackEndpoint bool
UseFIPSEndpoint bool
UserAgent UserAgentProducts
}
type AssumeRole struct {
RoleARN string
Duration time.Duration
ExternalID string
Policy string
PolicyARNs []string
SessionName string
SourceIdentity string
Tags map[string]string
TransitiveTagKeys []string
}
func (c Config) CustomCABundleReader() (*bytes.Reader, error) {
if c.CustomCABundle == "" {
return nil, nil
}
bundleFile, err := expand.FilePath(c.CustomCABundle)
if err != nil {
return nil, fmt.Errorf("expanding custom CA bundle: %w", err)
}
bundle, err := os.ReadFile(bundleFile)
if err != nil {
return nil, fmt.Errorf("reading custom CA bundle: %w", err)
}
return bytes.NewReader(bundle), nil
}
// HTTPTransportOptions returns functional options that configures an http.Transport.
// The returned options function is called on both AWS SDKv1 and v2 default HTTP clients.
func (c Config) HTTPTransportOptions() (func(*http.Transport), error) {
var err error
var httpProxyUrl *url.URL
if c.HTTPProxy != nil {
httpProxyUrl, err = url.Parse(aws.ToString(c.HTTPProxy))
if err != nil {
return nil, fmt.Errorf("parsing HTTP proxy URL: %w", err)
}
}
var httpsProxyUrl *url.URL
if c.HTTPSProxy != nil {
httpsProxyUrl, err = url.Parse(aws.ToString(c.HTTPSProxy))
if err != nil {
return nil, fmt.Errorf("parsing HTTPS proxy URL: %w", err)
}
}
opts := func(tr *http.Transport) {
tr.MaxIdleConnsPerHost = awshttp.DefaultHTTPTransportMaxIdleConnsPerHost
tlsConfig := tr.TLSClientConfig
if tlsConfig == nil {
tlsConfig = &tls.Config{
MinVersion: tls.VersionTLS12,
}
tr.TLSClientConfig = tlsConfig
}
if c.Insecure {
tr.TLSClientConfig.InsecureSkipVerify = true
}
proxyConfig := httpproxy.FromEnvironment()
if httpProxyUrl != nil {
proxyConfig.HTTPProxy = httpProxyUrl.String()
if c.HTTPProxyMode == HTTPProxyModeLegacy && proxyConfig.HTTPSProxy == "" {
proxyConfig.HTTPSProxy = httpProxyUrl.String()
}
}
if httpsProxyUrl != nil {
proxyConfig.HTTPSProxy = httpsProxyUrl.String()
}
if c.NoProxy != "" {
proxyConfig.NoProxy = c.NoProxy
}
tr.Proxy = func(req *http.Request) (*url.URL, error) {
return proxyConfig.ProxyFunc()(req.URL)
}
}
return opts, nil
}
func (c Config) ValidateProxySettings(diags *diag.Diagnostics) {
if c.HTTPProxy != nil {
if _, err := url.Parse(aws.ToString(c.HTTPProxy)); err != nil {
*diags = diags.AddError(
"Invalid HTTP Proxy",
fmt.Sprintf("Unable to parse URL: %s", err),
)
}
}
if c.HTTPSProxy != nil {
if _, err := url.Parse(aws.ToString(c.HTTPSProxy)); err != nil {
*diags = diags.AddError(
"Invalid HTTPS Proxy",
fmt.Sprintf("Unable to parse URL: %s", err),
)
}
}
if c.HTTPProxy != nil && *c.HTTPProxy != "" && c.HTTPSProxy == nil && os.Getenv("HTTPS_PROXY") == "" && os.Getenv("https_proxy") == "" {
if c.HTTPProxyMode == HTTPProxyModeLegacy {
*diags = diags.Append(
missingHttpsProxyLegacyWarningDiag(aws.ToString(c.HTTPProxy)),
)
} else {
*diags = diags.Append(
missingHttpsProxyWarningDiag(),
)
}
}
}
const (
missingHttpsProxyWarningSummary = "Missing HTTPS Proxy"
missingHttpsProxyDetailProblem = "An HTTP proxy was set but no HTTPS proxy was."
missingHttpsProxyDetailResolution = "To specify no proxy for HTTPS, set the HTTPS to an empty string."
)
func missingHttpsProxyLegacyWarningDiag(s string) diag.Diagnostic {
return diag.NewWarningDiagnostic(
missingHttpsProxyWarningSummary,
fmt.Sprintf(
missingHttpsProxyDetailProblem+" Using HTTP proxy %q for HTTPS requests. This behavior may change in future versions.\n\n"+
missingHttpsProxyDetailResolution,
s,
),
)
}
func missingHttpsProxyWarningDiag() diag.Diagnostic {
return diag.NewWarningDiagnostic(
missingHttpsProxyWarningSummary,
missingHttpsProxyDetailProblem+"\n\n"+
missingHttpsProxyDetailResolution,
)
}
func (c Config) ResolveSharedConfigFiles() ([]string, error) {
v, err := expand.FilePaths(c.SharedConfigFiles)
if err != nil {
return []string{}, fmt.Errorf("expanding shared config files: %w", err)
}
return v, nil
}
func (c Config) ResolveSharedCredentialsFiles() ([]string, error) {
v, err := expand.FilePaths(c.SharedCredentialsFiles)
if err != nil {
return []string{}, fmt.Errorf("expanding shared credentials files: %w", err)
}
return v, nil
}
// VerifyAccountIDAllowed verifies an account ID is not explicitly forbidden
// or omitted from an allow list, if configured.
//
// If the AllowedAccountIds and ForbiddenAccountIds fields are both empty, this
// function will return nil.
func (c Config) VerifyAccountIDAllowed(accountID string) error {
if len(c.ForbiddenAccountIds) > 0 {
for _, forbiddenAccountID := range c.ForbiddenAccountIds {
if accountID == forbiddenAccountID {
return fmt.Errorf("AWS account ID not allowed: %s", accountID)
}
}
}
if len(c.AllowedAccountIds) > 0 {
found := false
for _, allowedAccountID := range c.AllowedAccountIds {
if accountID == allowedAccountID {
found = true
break
}
}
if !found {
return fmt.Errorf("AWS account ID not allowed: %s", accountID)
}
}
return nil
}
type AssumeRoleWithWebIdentity struct {
RoleARN string
Duration time.Duration
Policy string
PolicyARNs []string
SessionName string
WebIdentityToken string
WebIdentityTokenFile string
}
func (c AssumeRoleWithWebIdentity) resolveWebIdentityTokenFile() (string, error) {
v, err := expand.FilePath(c.WebIdentityTokenFile)
if err != nil {
return "", fmt.Errorf("expanding web identity token file: %w", err)
}
return v, nil
}
func (c AssumeRoleWithWebIdentity) HasValidTokenSource() bool {
return c.WebIdentityToken != "" || c.WebIdentityTokenFile != ""
}
// Implements `stscreds.IdentityTokenRetriever`
func (c AssumeRoleWithWebIdentity) GetIdentityToken() ([]byte, error) {
if c.WebIdentityToken != "" {
return []byte(c.WebIdentityToken), nil
}
webIdentityTokenFile, err := c.resolveWebIdentityTokenFile()
if err != nil {
return nil, err
}
b, err := os.ReadFile(webIdentityTokenFile)
if err != nil {
return nil, fmt.Errorf("unable to read file at %s: %w", webIdentityTokenFile, err)
}
return b, nil
}