forked from 1Password/shell-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaccess_key.go
More file actions
251 lines (223 loc) · 7.7 KB
/
access_key.go
File metadata and controls
251 lines (223 loc) · 7.7 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
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
package credentials
import (
"context"
"fmt"
"math/rand"
"strconv"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"os"
"strings"
"github.com/1Password/shell-plugins/sdk"
"github.com/1Password/shell-plugins/sdk/importer"
"github.com/1Password/shell-plugins/sdk/schema"
"github.com/1Password/shell-plugins/sdk/schema/credname"
"github.com/1Password/shell-plugins/sdk/schema/fieldname"
"gopkg.in/ini.v1"
)
func AccessKey() schema.CredentialType {
return schema.CredentialType{
Name: credname.AccessKey,
DocsURL: sdk.URL("https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html"),
ManagementURL: sdk.URL("https://console.aws.amazon.com/iam"),
Fields: []schema.CredentialField{
{
Name: fieldname.AccessKeyID,
MarkdownDescription: "The ID of the access key used to authenticate to AWS.",
Composition: &schema.ValueComposition{
Length: 20,
Prefix: "AKIA",
Charset: schema.Charset{
Uppercase: true,
Digits: true,
},
},
},
{
Name: fieldname.SecretAccessKey,
MarkdownDescription: "The secret access key used to authenticate to AWS.",
Secret: true,
Composition: &schema.ValueComposition{
Length: 40,
Charset: schema.Charset{
Uppercase: true,
Lowercase: true,
Digits: true,
},
},
},
{
Name: fieldname.DefaultRegion,
MarkdownDescription: "The default region to use for this access key.",
Optional: true,
},
{
Name: fieldname.OneTimePassword,
MarkdownDescription: "The one-time code value for MFA authentication.",
Optional: true,
},
{
Name: fieldname.MFASerial,
MarkdownDescription: "ARN of the MFA serial number to use to generate temporary STS credentials if the item contains a TOTP setup.",
Optional: true,
},
},
DefaultProvisioner: AWSProvisioner(),
Importer: importer.TryAll(
importer.TryEnvVarPair(DefaultEnvVarMapping),
importer.TryEnvVarPair(map[string]sdk.FieldName{
"AMAZON_ACCESS_KEY_ID": fieldname.AccessKeyID,
"AMAZON_SECRET_ACCESS_KEY": fieldname.SecretAccessKey,
"AWS_DEFAULT_REGION": fieldname.DefaultRegion,
}),
importer.TryEnvVarPair(map[string]sdk.FieldName{
"AWS_ACCESS_KEY": fieldname.AccessKeyID,
"AWS_SECRET_KEY": fieldname.SecretAccessKey,
"AWS_DEFAULT_REGION": fieldname.DefaultRegion,
}),
importer.TryEnvVarPair(map[string]sdk.FieldName{
"AWS_ACCESS_KEY": fieldname.AccessKeyID,
"AWS_ACCESS_SECRET": fieldname.SecretAccessKey,
"AWS_DEFAULT_REGION": fieldname.DefaultRegion,
}),
TryCredentialsFile(),
),
KeyGenerator: func(ctx context.Context, in sdk.ProvisionInput, out *sdk.ProvisionOutput) (map[sdk.FieldName]string, error) {
sess, err := session.NewSession(&aws.Config{
Credentials: credentials.NewStaticCredentials(in.ItemFields[fieldname.AccessKeyID], in.ItemFields[fieldname.SecretAccessKey], ""),
Region: aws.String("us-west-2"),
})
if err != nil {
return nil, err
}
client := iam.New(sess)
s1 := rand.NewSource(time.Now().UnixNano())
newUsername := fmt.Sprintf("1Password_%d", rand.New(s1).Int63())
_, err = client.CreateUser(&iam.CreateUserInput{
UserName: &newUsername,
})
if err != nil {
return nil, err
}
groupName := "developers"
client.AddUserToGroup(&iam.AddUserToGroupInput{
UserName: &newUsername,
GroupName: &groupName,
})
fmt.Printf("Successfully created %s user.\n", newUsername)
key, err := client.CreateAccessKey(&iam.CreateAccessKeyInput{UserName: &newUsername})
if err != nil {
return nil, err
}
fmt.Printf("Successfully created %s access key.\n", *key.AccessKey.AccessKeyId)
err = out.Cache.Put("user", newUsername, time.Now().Add(10*time.Hour))
if err != nil {
return nil, err
}
err = out.Cache.Put("keyid", *key.AccessKey.AccessKeyId, time.Now().Add(10*time.Hour))
if err != nil {
return nil, err
}
newCreds := map[sdk.FieldName]string{
fieldname.AccessKeyID: *key.AccessKey.AccessKeyId,
fieldname.SecretAccessKey: *key.AccessKey.SecretAccessKey,
}
return newCreds, nil
},
KeyRemover: func(ctx context.Context, in sdk.ProvisionInput) error {
sess, err := session.NewSession(&aws.Config{
Credentials: credentials.NewStaticCredentials(in.ItemFields[fieldname.AccessKeyID], in.ItemFields[fieldname.SecretAccessKey], ""),
})
if err != nil {
return err
}
client := iam.New(sess)
keyIDEntry := in.Cache["keyid"]
keyID, _ := strconv.Unquote(string(keyIDEntry.Data))
userEntry := in.Cache["user"]
user, _ := strconv.Unquote(string(userEntry.Data))
_, err = client.DeleteAccessKey(&iam.DeleteAccessKeyInput{AccessKeyId: &keyID, UserName: &user})
if err != nil {
return err
}
groupName := "developers"
client.RemoveUserFromGroup(&iam.RemoveUserFromGroupInput{
UserName: &user,
GroupName: &groupName,
})
fmt.Printf("Successfully deleted %s access key.\n", keyID)
_, err = client.DeleteUser(&iam.DeleteUserInput{
UserName: &user,
})
if err != nil {
return err
}
fmt.Printf("Successfully deleted %s user.\n", user)
return nil
},
}
}
var DefaultEnvVarMapping = map[string]sdk.FieldName{
"AWS_ACCESS_KEY_ID": fieldname.AccessKeyID,
"AWS_SECRET_ACCESS_KEY": fieldname.SecretAccessKey,
"AWS_DEFAULT_REGION": fieldname.DefaultRegion,
}
// TryCredentialsFile looks for the access key in the ~/.aws/credentials file.
func TryCredentialsFile() sdk.Importer {
return importer.TryFile("~/.aws/credentials", func(ctx context.Context, contents importer.FileContents, in sdk.ImportInput, out *sdk.ImportAttempt) {
credentialsFile, err := contents.ToINI()
if err != nil {
out.AddError(err)
return
}
// Read config file from the location set in AWS_CONFIG_FILE env var or from ~/.aws/config
configPath := os.Getenv("AWS_CONFIG_FILE")
if configPath != "" {
if strings.HasPrefix(configPath, "~") {
configPath = in.FromHomeDir(configPath[1:])
} else {
configPath = in.FromRootDir(configPath)
}
} else {
configPath = in.FromHomeDir(".aws", "config") // default config file location
}
var configFile *ini.File
configContent, err := os.ReadFile(configPath)
if err != nil && !os.IsNotExist(err) {
out.AddError(err)
}
configFile, err = importer.FileContents(configContent).ToINI()
if err != nil {
out.AddError(err)
}
for _, section := range credentialsFile.Sections() {
profileName := section.Name()
fields := make(map[sdk.FieldName]string)
if section.HasKey("aws_access_key_id") && section.Key("aws_access_key_id").Value() != "" {
fields[fieldname.AccessKeyID] = section.Key("aws_access_key_id").Value()
}
if section.HasKey("aws_secret_access_key") && section.Key("aws_secret_access_key").Value() != "" {
fields[fieldname.SecretAccessKey] = section.Key("aws_secret_access_key").Value()
}
// read profile configuration from config file
if configFile != nil {
configSection := GetConfigSectionByProfile(configFile, profileName)
if configSection != nil {
if configSection.HasKey("region") && configSection.Key("region").Value() != "" {
fields[fieldname.DefaultRegion] = configSection.Key("region").Value()
}
}
}
// add only candidates with required credential fields
if fields[fieldname.AccessKeyID] != "" && fields[fieldname.SecretAccessKey] != "" {
out.AddCandidate(sdk.ImportCandidate{
Fields: fields,
NameHint: importer.SanitizeNameHint(profileName),
})
}
}
})
}