This repository has been archived by the owner on Feb 21, 2023. It is now read-only.
/
assume_role.go
88 lines (63 loc) · 1.95 KB
/
assume_role.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
package cli
import (
"errors"
"fmt"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/spf13/viper"
"github.com/redbubble/yak/aws"
"github.com/redbubble/yak/cache"
"github.com/redbubble/yak/saml"
log "github.com/sirupsen/logrus"
)
var notARoleErrorMessage = `'%s' is neither an IAM role ARN nor a configured alias.
Run 'yak --list-roles' to see which roles and aliases you can use.`
func AssumeRole(role string) (*sts.AssumeRoleWithSAMLOutput, error) {
creds := getAssumedRoleFromCache(role)
if creds == nil {
log.Infof("Role %s not in cache", role)
if viper.GetBool("cache.cache_only") {
return nil, errors.New("Could not find credentials in cache and --cache-only specified. Run `yak <role>` to remedy.")
}
loginData, err := GetLoginDataWithTimeout()
if err != nil {
return nil, err
}
CacheLoginRoles(loginData.Roles)
creds, err = assumeRoleFromAws(loginData, role)
if err != nil {
return nil, err
}
log.WithField("role", creds).Debug("assume_role.go: Role assumption credentials from AWS")
cache.WriteDefault(role, creds)
cache.Export()
}
return creds, nil
}
func getAssumedRoleFromCache(role string) *sts.AssumeRoleWithSAMLOutput {
data, ok := cache.Check(role).(sts.AssumeRoleWithSAMLOutput)
if !ok {
return nil
}
return &data
}
func ResolveRole(roleName string) (string, error) {
if viper.IsSet("alias." + roleName) {
return viper.GetString("alias." + roleName), nil
}
if isIamRoleArn(roleName) {
return roleName, nil
}
return "", fmt.Errorf(notARoleErrorMessage, roleName)
}
func assumeRoleFromAws(login saml.LoginData, desiredRole string) (*sts.AssumeRoleWithSAMLOutput, error) {
log.Infof("Assuming role %s from AWS", desiredRole)
role, err := login.GetLoginRole(desiredRole)
if err != nil {
return nil, err
}
return aws.AssumeRole(login, role, viper.GetInt64("aws.session_duration"))
}
func isIamRoleArn(roleName string) bool {
return arn.IsARN(roleName)
}