-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaws_sso.go
369 lines (297 loc) · 9.25 KB
/
aws_sso.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
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package main
import (
"crypto/sha1"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/mitchellh/go-homedir"
logger "github.com/rs/zerolog/log"
"gopkg.in/ini.v1"
)
const (
awsSSOPath = "sso"
keyRegion = "region"
keySSOUrl = "sso_start_url"
keySSORegion = "sso_region"
keySSOAccountID = "sso_account_id"
keySSORoleName = "sso_role_name"
keyCrdAccessKeyID = "aws_access_key_id"
keyCrdSecretAccessKey = "aws_secret_access_key"
keyCrdSessionToken = "aws_session_token"
)
var awsPath string
// SSOCredential defines the structure returned by AWS Cli
type SSOCredential struct {
URL string `json:"startUrl"`
Region string `json:"region"`
AccessToken string `json:"accessToken"`
ExpiresAsStr string `json:"expiresAt"`
}
// SSO implements the flow to retrieve the AWS SSO credentials
type SSO struct {
Cmd SSOCommand `json:"-"`
AccountID string `json:"accountId"`
RoleName string `json:"roleName"`
StartURL string `json:"startUrl"`
Region string `json:"region"`
BackupFile bool `json:"-"`
ForceSSOLogin bool `json:"-"`
}
// Accounts defines the structure returned by AWS Cli
type Accounts struct {
Items []*Account `json:"accountList"`
}
// Account defines the structure returned by AWS Cli
type Account struct {
ID string `json:"accountId"`
Name string `json:"accountName"`
Email string `json:"emailAddress"`
Roles []string `json:"-"`
}
// AccountRoles defines the structure returned by AWS Cli
type AccountRoles struct {
Items []*AccountRole `json:"roleList"`
}
// AccountRole defines the structure returned by AWS Cli
type AccountRole struct {
RoleName string `json:"roleName"`
AccountID string `json:"accountId"`
}
// Credentials defines the structure returned by AWS Cli
type Credentials struct {
Item *Credential `json:"roleCredentials"`
}
// Credential defines the structure returned by AWS Cli
type Credential struct {
ProfileName string `json:"-"`
AccountName string `json:"-"`
Region string `json:"-"`
AccessKeyID string `json:"accessKeyId"`
SecretAccessKey string `json:"secretAccessKey"`
SessionToken string `json:"sessionToken"`
Expiration int64 `json:"expiration"`
}
// CredentialResultInfo defines the information about SSO credentials
type CredentialResultInfo struct {
Filename string
ExpiresAt time.Time
}
// NewSSO returns a new SSO
func NewSSO(cmd SSOCommand, c *ConfigOptions) *SSO {
return &SSO{
cmd,
c.AccountID,
c.RoleName,
c.StartURL,
c.Region,
c.BackupFile,
c.ForceSSOLogin,
}
}
// List returns a slice of account roles
func (r *AccountRoles) List() []string {
var list []string
for _, r := range r.Items {
list = append(list, r.RoleName)
}
return list
}
// ExpiresAt parses the expiration date
// There is a workaround because the aws cli stores the expiration date
// in different formats.
func (c *SSOCredential) ExpiresAt() time.Time {
// aws-cli/2.1.29 Python/3.8.8 Darwin/20.3.0 exe/x86_64 prompt/off
layout := "2006-01-02T15:04:05Z"
t, err := time.Parse(layout, c.ExpiresAsStr)
if err != nil {
//aws-cli/2.0.40 Python/3.8.5 Darwin/19.6.0 source/x86_64
layout = "2006-01-02T15:04:05UTC"
t, err = time.Parse(layout, c.ExpiresAsStr)
if err != nil {
logger.Warn().Str("value", c.ExpiresAsStr).Msg("error parsing date")
return time.Now().UTC().AddDate(0, 0, -1)
}
}
return t
}
// Expired returns if credentials are expired
func (c *SSOCredential) Expired() bool {
return time.Now().UTC().After(c.ExpiresAt())
}
// ExpiresAt returns the expiratin date
func (d *Credential) ExpiresAt() time.Time {
return time.Unix(d.Expiration/1000, 0)
}
// PersistConfig writes the sso config file
func (a *SSO) PersistConfig() error {
config := NewFile(awsPath, "config")
logger.Debug().Str("path", config.FullName).Msg("preparing to store the aws sso config file")
// create file on disk when it does not exist
if err := config.Create(); err != nil {
return err
}
if a.BackupFile {
filename, err := config.Backup()
if err != nil {
return err
}
logger.Info().Str("path", filename).Msg("backup completed successfully")
}
cfg, _ := ini.LooseLoad(config.FullName)
s := cfg.Section(fmt.Sprintf("profile %s", a.RoleName))
s.Key("output").SetValue("json")
s.Key(keyRegion).SetValue(a.Region)
s.Key(keySSOUrl).SetValue(a.StartURL)
s.Key(keySSORegion).SetValue(a.Region)
s.Key(keySSOAccountID).SetValue(a.AccountID)
s.Key(keySSORoleName).SetValue(a.RoleName)
if err := cfg.SaveTo(config.FullName); err != nil {
return err
}
logger.Info().Str("path", config.FullName).Msg("the aws sso config file has been successfully stored")
return nil
}
func (a *SSO) loginRetry(v []bool) bool {
return len(v) > 0 && v[0]
}
// Login checks if the sso cache file is valid,
// when cache credential has expired forces a login
func (a *SSO) Login(retry ...bool) (*SSOCredential, error) {
if a.ForceSSOLogin || a.loginRetry(retry) {
_, err := a.Cmd.Login(a.RoleName)
if err != nil {
return nil, err
}
logger.Info().Msg("the aws sso cache file has been updated successfully")
}
c, err := a.ReadCacheFile()
if err != nil && !os.IsNotExist(err) {
return nil, err
}
if c != nil && !c.Expired() {
logger.Debug().Bool("expired", c.Expired()).Time("expiresAt", c.ExpiresAt()).Msg("the sso cache file token is not expired")
return c, nil
}
if a.loginRetry(retry) {
return nil, errors.New("can not renew the sso token")
}
return a.Login(true)
}
// ListAccounts lists accounts assigned to the user
func (a *SSO) ListAccounts(c *SSOCredential) ([]*Account, error) {
out, err := a.Cmd.ListAccounts(c.AccessToken, c.Region)
if err != nil {
return nil, err
}
accounts := &Accounts{}
err = json.Unmarshal([]byte(out), accounts)
if err != nil {
return nil, err
}
logger.Debug().Interface("accounts", accounts).Msg("accounts obtained with credentials")
for _, account := range accounts.Items {
out, err := a.Cmd.ListAccountRoles(c.AccessToken, c.Region, account.ID)
if err != nil {
return nil, err
}
roles := &AccountRoles{}
err = json.Unmarshal([]byte(out), roles)
if err != nil {
return nil, err
}
logger.Debug().Interface("roles", roles).Str("accountID", account.ID).Msg("roles by account")
account.Roles = roles.List()
}
return accounts.Items, nil
}
// GetCredentials retrieves the credentials of the account assigned to the user
func (a *SSO) GetCredentials(c *SSOCredential, accounts []*Account) ([]*Credential, error) {
var creds []*Credential
for _, acc := range accounts {
for i, r := range acc.Roles {
out, err := a.Cmd.GetRoleCredentials(c.AccessToken, c.Region, acc.ID, r)
if err != nil {
return nil, err
}
cs := &Credentials{}
if err := json.Unmarshal([]byte(out), cs); err != nil {
return nil, err
}
logger.Debug().Interface("credentials", cs).Str("accountID", acc.ID).Str("role", r).Msg("credentials...")
profile := strings.ReplaceAll(acc.Name, " ", "-")
if i > 0 {
profile = fmt.Sprintf("%s-%s", profile, Snake(r))
}
cs.Item.AccountName = acc.Name
cs.Item.Region = c.Region
cs.Item.ProfileName = strings.ToLower(profile)
logger.Info().Str("account", acc.Name).Str("region", c.Region).Msgf("credentials profile %s", cs.Item.ProfileName)
creds = append(creds, cs.Item)
}
}
logger.Debug().Msgf("%d credentials have been generated", len(creds))
if len(creds) == 0 {
return nil, errors.New("no credentials were found")
}
return creds, nil
}
// PersistCredentials writes the credentials to the AWS file
func (a *SSO) PersistCredentials(creds []*Credential) (*CredentialResultInfo, error) {
cred := NewFile(awsPath, "credentials")
if a.BackupFile {
filename, err := cred.Backup()
if err != nil {
return nil, err
}
logger.Info().Str("path", filename).Msg("backup completed successfully")
}
cfg, _ := ini.LooseLoad(cred.FullName)
for _, c := range creds {
s := cfg.Section(c.ProfileName)
s.Key("output").SetValue("json")
s.Key(keyRegion).SetValue(c.Region)
s.Key(keyCrdAccessKeyID).SetValue(c.AccessKeyID)
s.Key(keyCrdSecretAccessKey).SetValue(c.SecretAccessKey)
s.Key(keyCrdSessionToken).SetValue(c.SessionToken)
}
if err := cfg.SaveTo(cred.FullName); err != nil {
return nil, err
}
return &CredentialResultInfo{
Filename: cred.FullName,
ExpiresAt: creds[len(creds)-1].ExpiresAt(),
}, nil
}
// ReadCacheFile reads the sso cache file for a given sso
func (a *SSO) ReadCacheFile() (*SSOCredential, error) {
hash := sha1.New()
_, err := hash.Write([]byte(a.StartURL))
if err != nil {
return nil, err
}
cacheFilename := strings.ToLower(hex.EncodeToString(hash.Sum(nil))) + ".json"
cache := NewFile(awsPath, awsSSOPath, "cache", cacheFilename)
logger.Debug().Str("path", cache.FullName).Msg("searching for the aws sso cache file...")
if !cache.Exists() {
logger.Debug().Str("path", cache.FullName).Msg("aws sso cache file not found")
return nil, os.ErrNotExist
}
data := &SSOCredential{}
if err := cache.ReadJSON(data); err != nil {
return nil, err
}
logger.Debug().Interface("data", data).Msg("cache file was read successfully")
return data, err
}
func init() {
home, err := homedir.Dir()
if err != nil {
logger.Fatal().Err(err)
}
awsPath = filepath.Join(home, ".aws")
}