-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreds.go
315 lines (260 loc) · 7.57 KB
/
creds.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package creds
import (
"context"
"encoding/json"
"fmt"
"github.com/RyanJarv/liquidswards/lib/graph"
"github.com/RyanJarv/liquidswards/lib/utils"
"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"
"github.com/aws/aws-sdk-go-v2/service/sts/types"
"strings"
"time"
)
type State int
const (
ActiveState State = iota
RefreshingState
FailedState
)
type IConfig interface {
MarshalJSON() ([]byte, error)
UnmarshalJSON([]byte) error
Id() string
Arn() string
Name() string
Account() string
Config() aws.Config
Assume(ctx utils.Context, arn string) (*Config, error)
Refresh(utils.Context) (*Config, error)
SetGraph(graph interface{})
}
type SourceType int
const (
SourceProfile SourceType = iota
SourceAssumeRole
)
type Identity struct {
Type SourceType
Name string
Arn string
Source *Identity
}
func (i Identity) Account() string {
p := strings.Split(i.Arn, ":")
if len(p) < 5 {
panic(fmt.Sprintf("invalid Arn: %s", i.Arn))
} else if len(p[4]) != 12 {
panic(fmt.Sprintf("invalid account id: %s", p[4]))
}
return p[4]
}
func (i Identity) ResourceType() string {
return strings.Split(strings.Split(i.Arn, ":")[5], "/")[0]
}
// Id returns underlying role or user ARN for this principal.
func (i Identity) Id() string {
result := strings.Replace(i.Arn, ":sts:", ":iam:", 1)
switch i.ResourceType() {
case "assumed-role":
result = strings.Replace(result, ":assumed-role/", ":role/", 1)
result = strings.Join(strings.Split(result, "/")[:2], "/")
default:
result = i.Arn
}
return result
}
func (i *Identity) IdentityPath() (path []string) {
identity := i
for {
if identity == nil {
break
}
path = append(path, identity.Id())
identity = identity.Source
}
utils.Reverse(path)
return path
}
func (i Identity) IsRecursive() bool {
return utils.SliceRepeats(i.IdentityPath())
}
func NewConfig(ctx utils.Context, region string, src Identity) (*Config, error) {
awsCfg := aws.Config{Region: region}
return &Config{
Identity: src,
Config: awsCfg,
ctx: ctx,
Sts: sts.NewFromConfig(awsCfg),
}, nil
}
// SetGraph needs to be called with the graph and initial creds before Config is used.
// We can't do this in NewConfig because that is used to serialize/deserialize JSON (and therefor doesn't have access
// to the graph object).
func (c *Config) SetGraph(g interface{}) {
c.graph = g.(*graph.Graph[*Config])
//c.cfg.Credentials = c.CredProvider(c.InitialCreds)
}
func (c *Config) SetProvider(p *aws.CredentialsCache) {
c.Credentials = p
}
type Config struct {
Identity
aws.Config
ctx utils.Context
Sts stscreds.AssumeRoleAPIClient
graph *graph.Graph[*Config]
}
func (c *Config) Assume(ctx utils.Context, arn string) (*Config, error) {
_, err := c.Sts.AssumeRole(ctx.Context, &sts.AssumeRoleInput{
RoleArn: aws.String(arn),
RoleSessionName: aws.String("liquidswards"),
})
if err != nil {
return nil, fmt.Errorf("Assume(): %w", err)
}
newCfg, err := NewConfig(ctx, c.Region, Identity{
Type: SourceAssumeRole,
Name: arn,
Arn: arn,
Source: &c.Identity,
})
if err != nil {
return nil, fmt.Errorf("Assume(): %w", err)
}
c.graph.AddEdge(c, newCfg)
newCfg.SetProvider(NewGraphProvider(ctx, c.graph, arn))
newCfg.SetGraph(c.graph)
return newCfg, err
}
// Name returns the role/user name without the path.
func (c *Config) Name() string {
p := strings.Split(c.Arn(), "/")
return p[len(p)-1]
}
func (c *Config) Arn() string {
return c.Identity.Arn
}
func (c *Config) Refresh(ctx utils.Context) (aws.Credentials, error) {
p := c.Credentials
switch p.(type) {
case *aws.CredentialsCache:
p.(*aws.CredentialsCache).Invalidate()
default:
ctx.Info.Printf("got provider type: %T", p)
}
return p.Retrieve(ctx.Context)
}
type JsonConfig struct {
Arn string
State State
Region string
Credentials aws.Credentials
Identity Identity
}
func (c *Config) MarshalJSON() ([]byte, error) {
var creds aws.Credentials
var err error
if c.Credentials != nil {
creds, err = c.Credentials.Retrieve(context.Background())
if err != nil {
return nil, fmt.Errorf("Save(): %w", err)
}
}
obj := JsonConfig{
Arn: c.Arn(),
Region: c.Region,
Credentials: creds,
Identity: c.Identity,
}
r, err := json.Marshal(obj)
return r, err
}
func (c *Config) UnmarshalJSON(bytes []byte) error {
// TODO: Implement limiter
var obj JsonConfig
err := json.Unmarshal(bytes, &obj)
if err != nil {
return fmt.Errorf("unmarshalling: %w", err)
}
cfg, err := NewConfig(c.ctx, obj.Region, obj.Identity)
if err != nil {
return fmt.Errorf("UnmarshalJSON(): %w", err)
}
cfg.Config.Credentials = aws.NewCredentialsCache(credentials.StaticCredentialsProvider{Value: obj.Credentials})
*c = *cfg
return nil
}
func ParseProfiles(ctx utils.Context, profiles string, region string, g *graph.Graph[*Config]) (configs []*Config, err error) {
for _, p := range utils.SplitCommas(profiles) {
awsCfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(region), config.WithSharedConfigProfile(p))
if err != nil {
return nil, fmt.Errorf("loading profile %s using region %s: %w", p, region, err)
}
arn, err := utils.GetCallerArn(ctx, awsCfg)
if err != nil {
return nil, fmt.Errorf("failed to call sts:GetCallerArn using the %s profile: %w", p, err)
}
cfg, err := NewConfig(ctx, region, Identity{Type: SourceProfile, Name: p, Arn: arn})
if err != nil {
return nil, fmt.Errorf("ParseProfiles(): %w", err)
}
cfg.SetProvider(awsCfg.Credentials.(*aws.CredentialsCache))
g.AddNode(cfg)
cfg.SetGraph(g)
configs = append(configs, cfg)
}
return configs, nil
}
// ParseScope returns the accounts included in the comma delimited scopeStr as well as any accounts passed in cfgs.
func ParseScope(scopeStr string, cfgs []*Config) []string {
scope := utils.SplitCommas(scopeStr)
for _, cfg := range cfgs {
scope = append(scope, cfg.Account())
}
return utils.FilterDuplicates(utils.RemoveDefaults(scope))
}
type MockSts struct {
Calls []sts.AssumeRoleInput
}
func (s *MockSts) AssumeRole(ctx context.Context, in *sts.AssumeRoleInput, optFns ...func(*sts.Options)) (*sts.AssumeRoleOutput, error) {
s.Calls = append(s.Calls, *in)
return &sts.AssumeRoleOutput{
AssumedRoleUser: &types.AssumedRoleUser{
Arn: aws.String(fmt.Sprintf("%s-Arn", *in.RoleArn)),
AssumedRoleId: aws.String(fmt.Sprintf("%s-id", *in.RoleArn)),
},
Credentials: &types.Credentials{
AccessKeyId: aws.String("test"),
SecretAccessKey: aws.String("test"),
SessionToken: aws.String("test"),
Expiration: aws.Time(time.Time{}),
},
}, nil
}
// NewTestAssumesAllConfig is kept here for now to allow using it from other modules.
func NewTestAssumesAllConfig(srcType SourceType, name string, g *graph.Graph[*Config]) (*Config, *MockSts, error) {
src := Identity{
Type: srcType,
Name: name,
Arn: fmt.Sprintf("arn:aws:iam::123456789012:%s", name),
}
ctx := utils.NewContext(context.Background())
cfg, err := NewConfig(ctx, "us-east-1", src)
if err != nil {
return nil, nil, fmt.Errorf("NewTestAssumesAllConfig(): %w", err)
}
if srcType == SourceProfile {
creds := aws.Credentials{AccessKeyID: "test", SecretAccessKey: "test", SessionToken: "test", Source: src.Arn}
cfg.SetProvider(aws.NewCredentialsCache(credentials.StaticCredentialsProvider{Value: creds}))
} else {
cfg.SetProvider(NewGraphProvider(ctx, g, src.Arn))
}
cfg.SetGraph(g)
client := &MockSts{Calls: []sts.AssumeRoleInput{}}
cfg.Sts = client
return cfg, client, nil
}