This repository has been archived by the owner on Aug 1, 2021. It is now read-only.
/
credentials.go
150 lines (121 loc) · 4.1 KB
/
credentials.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
package proxy
import (
"context"
"fmt"
"regexp"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/aws/aws-sdk-go/service/sts/stsiface"
"github.com/pkg/errors"
)
const (
maxSessionNameLen int = 32
)
var (
// matches char that is not valid in a STS role session name
invalidSessionNameRegexp = regexp.MustCompile(`[^\w+=,.@-]`)
sessionExpiration = 5 * time.Minute
)
type credentials struct {
AccessKey string
Expiration time.Time
GeneratedAt time.Time
RoleArn RoleARN
SecretKey string
Token string
}
func (c credentials) ExpiredNow() bool {
return c.ExpiredAt(time.Now())
}
func (c credentials) ExpiredAt(at time.Time) bool {
return at.After(c.Expiration)
}
func (c credentials) ExpiresIn(d time.Duration) bool {
return c.ExpiredAt(time.Now().Add(d))
}
type containerCredentials struct {
ContainerInfo
credentials
}
func (c containerCredentials) IsValid(container ContainerInfo) bool {
return c.ContainerInfo.IamRole.Equals(container.IamRole) &&
c.ContainerInfo.ID == container.ID &&
!c.credentials.ExpiresIn(sessionExpiration)
}
type credentialsProvider struct {
container ContainerService
awsSts stsiface.STSAPI
defaultIamRoleArn RoleARN
defaultIamPolicy string
containerCredentials map[string]containerCredentials
lock sync.Mutex
}
func newCredentialsProvider(stsSvc stsiface.STSAPI, container ContainerService, defaultIamRoleArn RoleARN, defaultIamPolicy string) *credentialsProvider {
return &credentialsProvider{
container: container,
awsSts: stsSvc,
defaultIamRoleArn: defaultIamRoleArn,
defaultIamPolicy: defaultIamPolicy,
containerCredentials: make(map[string]containerCredentials),
}
}
// CredentialsForIP resolves the IP to a specific container, then attempts to assume the role
// specified in the container's metadata. Role specific credentials are returned.
//
// If the cache contains no fresh and valid role credentials, a fresh set is requested from
// AWS and cached.
func (c *credentialsProvider) CredentialsForIP(ctx context.Context, containerIP string) (credentials, error) {
c.lock.Lock()
defer c.lock.Unlock()
container, err := c.container.ContainerForIP(ctx, containerIP)
if err != nil {
return credentials{}, errors.Wrapf(err, "Error finding container with IP [%s]", containerIP)
}
oldCredentials, found := c.containerCredentials[containerIP]
if !found || !oldCredentials.IsValid(container) {
arn := container.IamRole
iamPolicy := container.IamPolicy
if arn.Empty() {
arn = c.defaultIamRoleArn
}
if len(iamPolicy) == 0 {
iamPolicy = c.defaultIamPolicy
}
role, err := c.AssumeRole(arn, iamPolicy, generateSessionName(c.container.TypeName(), container.ID))
if err != nil {
return credentials{}, errors.Wrapf(err, "Error assuming role [%s] for container [%s] at IP {%s]", arn, container.Name, containerIP)
}
oldCredentials = containerCredentials{container, role}
c.containerCredentials[containerIP] = oldCredentials
}
return oldCredentials.credentials, nil
}
func (c *credentialsProvider) AssumeRole(role RoleARN, iamPolicy, sessionName string) (credentials, error) {
var policy *string
if len(iamPolicy) > 0 {
policy = aws.String(iamPolicy)
}
resp, err := c.awsSts.AssumeRole(&sts.AssumeRoleInput{
DurationSeconds: aws.Int64(3600), // Max is 1 hour
Policy: policy,
RoleArn: aws.String(role.String()),
RoleSessionName: aws.String(sessionName),
})
if err != nil {
return credentials{}, errors.Wrapf(err, "Error assuming role [%s] with policy [%s] and session name [%s]]", role, iamPolicy, sessionName)
}
return credentials{
AccessKey: *resp.Credentials.AccessKeyId,
SecretKey: *resp.Credentials.SecretAccessKey,
Token: *resp.Credentials.SessionToken,
Expiration: *resp.Credentials.Expiration,
GeneratedAt: time.Now(),
RoleArn: role,
}, nil
}
func generateSessionName(platform, containerID string) string {
sessionName := fmt.Sprintf("%s-%s", platform, containerID)
return invalidSessionNameRegexp.ReplaceAllString(sessionName, "_")[0:maxSessionNameLen]
}