-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.go
More file actions
213 lines (180 loc) · 7.28 KB
/
client.go
File metadata and controls
213 lines (180 loc) · 7.28 KB
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
package cognito
import (
b64 "encoding/base64"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
"github.com/hashicorp/errwrap"
uuid "github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/sdk/helper/jsonutil"
"io/ioutil"
"math/rand"
"net/http"
"time"
)
type client interface {
deleteUser(region string, userPoolId string, username string) error
getClientCredentialsGrant(cognitoPoolDomain string, appClientId string, appClientSecret string) (map[string]interface{}, error)
getNewUser(region string, appClientId string, userPoolId string, group string, dummyEmailDomain string) (map[string]interface{}, error)
}
type clientImpl struct {
AwsAccessKeyId string
AwsAssumeRoleArn string
AwsSecretAccessKey string
AwsSessionToken string
}
func (c *clientImpl) deleteUser(region string, userPoolId string, username string) error {
config := aws.NewConfig()
if c.AwsAccessKeyId != "" {
creds := credentials.NewStaticCredentials(c.AwsAccessKeyId, c.AwsSecretAccessKey, c.AwsSessionToken)
config = config.WithCredentials(creds)
}
// Initial credentials loaded from SDK's default credential chain. Such as
// the environment, shared credentials (~/.aws/credentials), or EC2 Instance
// Role. These credentials will be used to to make the STS Assume Role API.
sess := session.Must(session.NewSession(config))
cognitoProviderConfig := aws.NewConfig().WithRegion(region)
if c.AwsAssumeRoleArn != "" {
assumedRoleCreds := stscreds.NewCredentials(sess, c.AwsAssumeRoleArn)
cognitoProviderConfig = cognitoProviderConfig.WithCredentials(assumedRoleCreds)
}
cognitoClient := cognitoidentityprovider.New(sess, cognitoProviderConfig)
deleteUserData := &cognitoidentityprovider.AdminDeleteUserInput{
UserPoolId: aws.String(userPoolId),
Username: aws.String(username),
}
_, err := cognitoClient.AdminDeleteUser(deleteUserData)
return err
}
func (c *clientImpl) getClientCredentialsGrant(cognitoPoolDomain string, appClientId string, appClientSecret string) (map[string]interface{}, error) {
var rawData map[string]interface{}
encodedAppClientSecret := b64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", appClientId, appClientSecret)))
myClient := &http.Client{}
postReq, _ := http.NewRequest("POST", fmt.Sprintf("https://%s/oauth2/token?grant_type=client_credentials&client_id=%s", cognitoPoolDomain, appClientId), nil)
postReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
postReq.Header.Set("Authorization", fmt.Sprintf("Basic %s", encodedAppClientSecret))
postResp, err := myClient.Do(postReq)
fetchedData, _ := ioutil.ReadAll(postResp.Body)
if err != nil {
return nil, errwrap.Wrapf("Token request failed: {{err}}", err)
}
if fetchedData == nil {
return nil, fmt.Errorf("Token was empty")
}
if err := jsonutil.DecodeJSON(fetchedData, &rawData); err != nil {
return nil, errwrap.Wrapf("json decoding failed: {{err}}", err)
}
return rawData, nil
}
func (c *clientImpl) getNewUser(region string, appClientId string, userPoolId string, group string, dummyEmailDomain string) (map[string]interface{}, error) {
config := aws.NewConfig()
if c.AwsAccessKeyId != "" {
creds := credentials.NewStaticCredentials(c.AwsAccessKeyId, c.AwsSecretAccessKey, c.AwsSessionToken)
config = config.WithCredentials(creds)
}
// Initial credentials loaded from SDK's default credential chain. Such as
// the environment, shared credentials (~/.aws/credentials), or EC2 Instance
// Role. These credentials will be used to to make the STS Assume Role API.
sess := session.Must(session.NewSession(config))
cognitoProviderConfig := aws.NewConfig().WithRegion(region)
if c.AwsAssumeRoleArn != "" {
assumedRoleCreds := stscreds.NewCredentials(sess, c.AwsAssumeRoleArn)
cognitoProviderConfig = cognitoProviderConfig.WithCredentials(assumedRoleCreds)
}
cognitoClient := cognitoidentityprovider.New(sess, cognitoProviderConfig)
keyID, err := uuid.GenerateUUID()
if err != nil {
return nil, errwrap.Wrapf("Could not generate UUID: {{err}}", err)
}
emailID := "vault" + keyID[5:] + "@" + dummyEmailDomain
password := generatePassword()
newUserData := &cognitoidentityprovider.AdminCreateUserInput{
MessageAction: aws.String("SUPPRESS"),
TemporaryPassword: aws.String(password),
UserAttributes: []*cognitoidentityprovider.AttributeType{
{
Name: aws.String("email"),
Value: aws.String(emailID),
},
{
Name: aws.String("email_verified"),
Value: aws.String("true"),
},
},
UserPoolId: aws.String(userPoolId),
Username: aws.String(emailID),
}
_, err = cognitoClient.AdminCreateUser(newUserData)
if err != nil {
return nil, errwrap.Wrapf("Could not create user: {{err}}", err)
}
addUserToGroupData := &cognitoidentityprovider.AdminAddUserToGroupInput{
GroupName: aws.String(group),
UserPoolId: aws.String(userPoolId),
Username: aws.String(emailID),
}
_, err = cognitoClient.AdminAddUserToGroup(addUserToGroupData)
if err != nil {
return nil, errwrap.Wrapf("Could not add user to group: {{err}}", err)
}
adminInitiateAuthData := &cognitoidentityprovider.AdminInitiateAuthInput{
AuthFlow: aws.String("ADMIN_NO_SRP_AUTH"),
AuthParameters: map[string]*string{
"USERNAME": aws.String(emailID),
"PASSWORD": aws.String(password),
},
ClientId: aws.String(appClientId),
UserPoolId: aws.String(userPoolId),
}
sessionResponse, err := cognitoClient.AdminInitiateAuth(adminInitiateAuthData)
if err != nil {
return nil, errwrap.Wrapf("Could not init auth: {{err}}", err)
}
adminRespondToAuthChallengeData := &cognitoidentityprovider.AdminRespondToAuthChallengeInput{
ChallengeName: aws.String("NEW_PASSWORD_REQUIRED"),
ChallengeResponses: map[string]*string{
"USERNAME": aws.String(emailID),
"NEW_PASSWORD": aws.String(password),
},
ClientId: aws.String(appClientId),
Session: aws.String(*sessionResponse.Session),
UserPoolId: aws.String(userPoolId),
}
authenticationResult, err := cognitoClient.AdminRespondToAuthChallenge(adminRespondToAuthChallengeData)
if err != nil {
return nil, errwrap.Wrapf("Could not respond to auth challenge: {{err}}", err)
}
rawData := map[string]interface{}{
"username": emailID,
"password": password,
"access_token": aws.String(*authenticationResult.AuthenticationResult.AccessToken),
"expires_in": aws.Int64(*authenticationResult.AuthenticationResult.ExpiresIn),
"id_token": aws.String(*authenticationResult.AuthenticationResult.IdToken),
"refresh_token": aws.String(*authenticationResult.AuthenticationResult.RefreshToken),
"token_type": aws.String(*authenticationResult.AuthenticationResult.TokenType),
}
return rawData, nil
}
func generatePassword() string {
rand.Seed(time.Now().UnixNano())
digits := "0123456789"
specials := "~=+%^*/()[]{}/!@#$?|"
all := "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
digits + specials
length := 32
buf := make([]byte, length)
buf[0] = digits[rand.Intn(len(digits))]
buf[1] = specials[rand.Intn(len(specials))]
for i := 2; i < length; i++ {
buf[i] = all[rand.Intn(len(all))]
}
rand.Shuffle(len(buf), func(i, j int) {
buf[i], buf[j] = buf[j], buf[i]
})
str := string(buf) // E.g. "3i[g0|)z"
return str
}