Repository navigation
Expand file tree
/
Copy pathaws.go
More file actions
348 lines (299 loc) · 11.9 KB
/
Copy pathaws.go
File metadata and controls
348 lines (299 loc) · 11.9 KB
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package pluginsdk
import (
"context"
"fmt"
"os"
"path/filepath"
"regexp"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/credentials/stscreds"
"github.com/aws/aws-sdk-go-v2/service/sts"
"sigs.k8s.io/yaml"
)
type AWSCredentials struct {
UseDefault bool `json:"use_default,omitempty" description:"Use AWS credentials from environment or default profile (recommended)" default:"true"`
ID string `json:"id,omitempty" description:"AWS access key ID"`
Secret string `json:"secret,omitempty" description:"AWS secret access key" sensitive:"true"`
Token string `json:"token,omitempty" description:"AWS session token" sensitive:"true"`
Profile string `json:"profile,omitempty" description:"AWS profile to use from shared credentials file"`
RoleARN string `json:"role_arn,omitempty" label:"Role ARN" description:"The IAM role Marmot signs in as with the pipeline's identity token. Its trust policy must name the Marmot issuer as an OIDC provider. Setting it means no keys are needed; region is then required"`
Region string `json:"region,omitempty" description:"AWS region for services"`
Endpoint string `json:"endpoint,omitempty" description:"Custom endpoint URL for AWS services" validate:"omitempty,url"`
ThenAssume *AWSAssumeRole `json:"then_assume,omitempty" label:"Then assume role" description:"Optional. A second role to switch to after signing in, for example in another account that does not trust Marmot directly"`
// Deprecated: use ThenAssume. Still read, as then_assume.role_arn
// and then_assume.external_id, so saved configs keep working.
Role string `json:"role,omitempty" hidden:"true" description:"Deprecated: use then_assume.role_arn"`
RoleExternalID string `json:"role_external_id,omitempty" hidden:"true" description:"Deprecated: use then_assume.external_id"`
}
// AWSAssumeRole is a role assumed with AssumeRole on top of whatever the
// credentials signed in with: role_arn, static keys, a profile or the
// default chain. Only this step takes an external ID; AWS's web identity
// exchange has none.
type AWSAssumeRole struct {
RoleARN string `json:"role_arn,omitempty" label:"Role ARN" description:"IAM role to assume after signing in"`
ExternalID string `json:"external_id,omitempty" label:"External ID" description:"Only if this role's trust policy requires one"`
}
// assumeRole is the role to assume on top of the sign-in, from
// then_assume or, in a config saved before it, from role and
// role_external_id.
func (c *AWSCredentials) assumeRole() (roleARN, externalID string) {
if c.ThenAssume != nil && c.ThenAssume.RoleARN != "" {
return c.ThenAssume.RoleARN, c.ThenAssume.ExternalID
}
return c.Role, c.RoleExternalID
}
// checkAssumeRole refuses a config that names a second role both ways,
// and a then_assume that is not a role.
func (c *AWSCredentials) checkAssumeRole() error {
if c.ThenAssume == nil {
return nil
}
if c.ThenAssume.RoleARN == "" {
if c.ThenAssume.ExternalID != "" {
return validationError("then_assume.role_arn", "then_assume.external_id needs then_assume.role_arn")
}
return nil
}
if c.Role != "" || c.RoleExternalID != "" {
return validationError("then_assume", "set then_assume or the deprecated role and role_external_id, not both")
}
if !awsRoleARNPattern.MatchString(c.ThenAssume.RoleARN) {
return validationError("then_assume.role_arn", "then_assume.role_arn must be an IAM role ARN: arn:aws:iam::<account>:role/<name>")
}
return nil
}
type AWSConfig struct {
Credentials AWSCredentials `json:"credentials" description:"AWS credentials configuration"`
TagsToMetadata bool `json:"tags_to_metadata,omitempty" group:"Discovery" description:"Convert AWS tags to Marmot metadata"`
IncludeTags []string `json:"include_tags,omitempty" group:"Discovery" description:"List of AWS tags to include as metadata. By default, all tags are included."`
}
func (a *AWSConfig) Validate() error {
return nil
}
// awsDefaultAudience is what an IAM OIDC identity provider expects as
// client id unless registered with another.
const awsDefaultAudience = "sts.amazonaws.com"
// awsSessionName names the assumed-role session. CloudTrail records the
// token's subject alongside it as SubjectFromWebIdentityToken.
const awsSessionName = "marmot"
var awsRoleARNPattern = regexp.MustCompile(`^arn:aws[a-zA-Z-]*:iam::[0-9]{12}:role/.+$`)
// Federate applies AWSCredentials.Federate to the embedded credentials.
func (a *AWSConfig) Federate(raw RawConfig) error {
return a.Credentials.Federate(raw)
}
// Federated reports whether the credentials exchange a Marmot identity
// token rather than use keys, a profile or the default chain.
func (c *AWSCredentials) Federated() bool {
return c.RoleARN != ""
}
// Federate checks the federation fields and derives the token audience
// into raw, the config Validate returns to the host. Call it from
// Validate after UnmarshalConfig. An audience alone is refused: it is
// the host's signal to mint, which only a role can exchange. A role
// excludes static keys and a profile: the point is to have none.
func (c *AWSCredentials) Federate(raw RawConfig) error {
if err := c.checkAssumeRole(); err != nil {
return err
}
audience := Audience(raw)
if c.RoleARN == "" {
if audience != "" {
return validationError("audience", "audience needs role_arn; without a role the plugin uses the keys, profile or default chain it names")
}
return nil
}
if !awsRoleARNPattern.MatchString(c.RoleARN) {
return validationError("role_arn", "role_arn must be an IAM role ARN: arn:aws:iam::<account>:role/<name>")
}
if c.ID != "" || c.Secret != "" || c.Token != "" || c.Profile != "" {
return validationError("role_arn", "role_arn excludes static keys and a profile; a federated pipeline needs no key")
}
if c.Region == "" {
return validationError("region", "region is required with role_arn; the STS exchange and the service calls are regional")
}
if audience == "" {
audience = awsDefaultAudience
}
SetAudience(raw, audience)
return nil
}
var ErrEndpointNotFound = fmt.Errorf("endpoint not found")
func ExtractAWSConfig(rawConfig map[string]interface{}) (*AWSConfig, error) {
var awsCfg AWSConfig
configBytes, err := yaml.Marshal(rawConfig)
if err != nil {
return nil, fmt.Errorf("marshaling raw config: %w", err)
}
if err := yaml.Unmarshal(configBytes, &awsCfg); err != nil {
return nil, fmt.Errorf("unmarshaling into AWSConfig: %w", err)
}
return &awsCfg, nil
}
// DetectAWSCredentials checks if AWS credentials are available from environment or config files
func DetectAWSCredentials(ctx context.Context) *AWSCredentialStatus {
status := &AWSCredentialStatus{
Available: false,
Sources: []string{},
}
if os.Getenv("AWS_ACCESS_KEY_ID") != "" && os.Getenv("AWS_SECRET_ACCESS_KEY") != "" {
status.Available = true
status.Sources = append(status.Sources, "environment variables")
}
homeDir, err := os.UserHomeDir()
if err == nil {
credsPath := filepath.Join(homeDir, ".aws", "credentials")
if _, err := os.Stat(credsPath); err == nil {
status.Available = true
status.Sources = append(status.Sources, "credentials file (~/.aws/credentials)")
}
}
if err == nil {
configPath := filepath.Join(homeDir, ".aws", "config")
if _, err := os.Stat(configPath); err == nil {
if !contains(status.Sources, "credentials file (~/.aws/credentials)") {
status.Available = true
status.Sources = append(status.Sources, "config file (~/.aws/config)")
}
}
}
if os.Getenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI") != "" || os.Getenv("AWS_CONTAINER_CREDENTIALS_FULL_URI") != "" {
status.Available = true
status.Sources = append(status.Sources, "container credentials")
}
if status.Available {
_, err := config.LoadDefaultConfig(ctx)
if err != nil {
status.Available = false
status.Error = err.Error()
}
}
return status
}
type AWSCredentialStatus struct {
Available bool `json:"available"`
Sources []string `json:"sources"`
Error string `json:"error,omitempty"`
} // @name AWSCredentialStatus
func contains(slice []string, item string) bool {
for _, s := range slice {
if s == item {
return true
}
}
return false
}
func (a *AWSConfig) NewAWSConfig(ctx context.Context) (aws.Config, error) {
var opts []func(*config.LoadOptions) error
if a.Credentials.Region != "" {
opts = append(opts, config.WithRegion(a.Credentials.Region))
}
if a.Credentials.RoleARN != "" {
// Federated: the default chain is not consulted, even if it
// would resolve. The web identity provider goes in below, once
// the config exists to build an STS client from.
opts = append(opts, config.WithCredentialsProvider(aws.AnonymousCredentials{}))
} else if a.Credentials.UseDefault || (a.Credentials.ID == "" && a.Credentials.Profile == "") {
if a.Credentials.Profile != "" {
opts = append(opts, config.WithSharedConfigProfile(a.Credentials.Profile))
}
} else {
if a.Credentials.ID != "" && a.Credentials.Secret != "" {
provider := credentials.NewStaticCredentialsProvider(
a.Credentials.ID,
a.Credentials.Secret,
a.Credentials.Token,
)
opts = append(opts, config.WithCredentialsProvider(provider))
}
if a.Credentials.Profile != "" {
opts = append(opts, config.WithSharedConfigProfile(a.Credentials.Profile))
}
}
cfg, err := config.LoadDefaultConfig(ctx, opts...)
if err != nil {
return aws.Config{}, fmt.Errorf("loading AWS config: %w", err)
}
if a.Credentials.RoleARN != "" {
provider, err := a.federatedCredentials(ctx, cfg)
if err != nil {
return aws.Config{}, err
}
cfg.Credentials = provider
}
if roleARN, externalID := a.Credentials.assumeRole(); roleARN != "" {
stsClient := sts.NewFromConfig(cfg)
assumeRoleOpts := func(o *stscreds.AssumeRoleOptions) {
if externalID != "" {
o.ExternalID = aws.String(externalID)
}
}
provider := stscreds.NewAssumeRoleProvider(stsClient, roleARN, assumeRoleOpts)
cfg.Credentials = aws.NewCredentialsCache(provider)
}
if a.Credentials.Endpoint != "" {
cfg.BaseEndpoint = aws.String(a.Credentials.Endpoint)
}
return cfg, nil
}
func ProcessAWSTags(tagsToMetadata bool, includeTags []string, tags map[string]string) map[string]interface{} {
metadata := make(map[string]interface{})
if !tagsToMetadata || len(tags) == 0 {
return metadata
}
for key, value := range tags {
if len(includeTags) > 0 {
included := false
for _, includeTag := range includeTags {
if key == includeTag {
included = true
break
}
}
if !included {
continue
}
}
metadata[fmt.Sprintf("tag_%s", key)] = value
}
return metadata
}
func ShouldIncludeResource(name string, filter Filter) bool {
if len(filter.Include) == 0 && len(filter.Exclude) == 0 {
return true
}
for _, pattern := range filter.Exclude {
matched, err := regexp.MatchString(pattern, name)
if err == nil && matched {
return false
}
}
if len(filter.Include) == 0 {
return true
}
for _, pattern := range filter.Include {
matched, err := regexp.MatchString(pattern, name)
if err == nil && matched {
return true
}
}
return false
}
// federatedCredentials returns a cached provider that exchanges the
// Marmot identity token the host left in IdentityTokenFile for the
// role's credentials, and reads the file again at every refresh.
// AssumeRoleWithWebIdentity is unsigned, so the STS client runs
// anonymously.
func (a *AWSConfig) federatedCredentials(ctx context.Context, cfg aws.Config) (aws.CredentialsProvider, error) {
file, ok := IdentityTokenFile(ctx)
if !ok {
return nil, ErrNoIdentityToken
}
stsCfg := cfg
stsCfg.Credentials = aws.AnonymousCredentials{}
provider := stscreds.NewWebIdentityRoleProvider(sts.NewFromConfig(stsCfg), a.Credentials.RoleARN, stscreds.IdentityTokenFile(file), func(o *stscreds.WebIdentityRoleOptions) {
o.RoleSessionName = awsSessionName
})
return aws.NewCredentialsCache(provider), nil
}