forked from scriptsrc/ec2metaproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
role.go
88 lines (70 loc) · 1.71 KB
/
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 ec2metaproxy
import (
"errors"
"regexp"
"time"
"github.com/goamz/goamz/aws"
"github.com/goamz/goamz/sts"
)
var (
roleArnRegex = regexp.MustCompile(`^arn:aws:iam::(\d+):role/([^:]+/)?([^:]+?)$`)
)
type RoleArn struct {
value string
path string
name string
accountId string
}
func NewRoleArn(value string) (RoleArn, error) {
result := roleArnRegex.FindStringSubmatch(value)
if result == nil {
return RoleArn{}, errors.New("invalid role ARN")
}
return RoleArn{value, "/" + result[2], result[3], result[1]}, nil
}
func (t RoleArn) RoleName() string {
return t.name
}
func (t RoleArn) Path() string {
return t.path
}
func (t RoleArn) AccountId() string {
return t.accountId
}
func (t RoleArn) String() string {
return t.value
}
func (t RoleArn) Empty() bool {
return len(t.value) == 0
}
type RoleCredentials struct {
AccessKey string
SecretKey string
Token string
Expiration time.Time
}
func (t *RoleCredentials) ExpiredNow() bool {
return t.ExpiredAt(time.Now())
}
func (t *RoleCredentials) ExpiredAt(at time.Time) bool {
return at.After(t.Expiration)
}
func AssumeRole(auth aws.Auth, roleArn, sessionName string) (*RoleCredentials, error) {
stsClient := sts.New(auth, aws.USWest2)
resp, err := stsClient.AssumeRole(&sts.AssumeRoleParams{
DurationSeconds: 3600, // Max is 1 hour
ExternalId: "", // Empty string means not applicable
Policy: "", // Empty string means not applicable
RoleArn: roleArn,
RoleSessionName: sessionName,
})
if err != nil {
return nil, err
}
return &RoleCredentials{
resp.Credentials.AccessKeyId,
resp.Credentials.SecretAccessKey,
resp.Credentials.SessionToken,
resp.Credentials.Expiration,
}, nil
}