forked from tonedefdev/terracreds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
447 lines (402 loc) · 13.7 KB
/
main.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
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
"os/user"
"runtime"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/danieljoos/wincred"
"github.com/fatih/color"
"github.com/urfave/cli/v2"
"github.com/zalando/go-keyring"
"gopkg.in/yaml.v2"
)
// CheckError processes the error
func CheckError(e error) {
if e != nil {
log.Fatal(e)
}
}
// CopyTerraCreds will create a copy of the binary to the
// destination path.
func CopyTerraCreds(dest string) error {
from, err := os.Open(string(os.Args[0]))
CheckError(err)
defer from.Close()
to, err := os.OpenFile(dest, os.O_RDWR|os.O_CREATE, 0755)
CheckError(err)
defer to.Close()
_, err = io.Copy(to, from)
CheckError(err)
fmt.Fprintf(color.Output, "%s: Copied binary '%s' to '%s'\n", color.CyanString("INFO"), string(os.Args[0]), dest)
return nil
}
// GetBinaryPath returns the directory of the binary path
func GetBinaryPath(binary string) string {
var path string
if runtime.GOOS == "windows" {
if strings.Contains(binary, "terraform-credentials-terracreds.exe") {
path = strings.Replace(binary, "terraform-credentials-terracreds.exe", "", -1)
} else if strings.Contains(binary, "terracreds.test.exe") {
path = strings.Replace(binary, "terracreds.test.exe", "", -1)
} else {
path = strings.Replace(binary, "terracreds.exe", "", -1)
}
}
if runtime.GOOS == "darwin" {
if strings.Contains(binary, "terraform-credentials-terracreds") {
path = strings.Replace(binary, "terraform-credentials-terracreds", "", -1)
} else if strings.Contains(binary, "terracreds.test") {
path = strings.Replace(binary, "terracreds.test", "", -1)
} else {
path = strings.Replace(binary, "terracreds", "", -1)
}
}
return path
}
// NewDirectory checks for the existence of a directory
// if it doesn't exist it creates it and checks for errors
func NewDirectory(path string) error {
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
err := os.Mkdir(path, 0755)
CheckError(err)
fmt.Fprintf(color.Output, "%s: Created directory '%s'\n", color.CyanString("INFO"), path)
}
}
return nil
}
// WriteToFile will print any string of text to a file safely by
// checking for errors and syncing at the end.
func WriteToFile(filename string, data string) error {
file, err := os.Create(filename)
CheckError(err)
defer file.Close()
_, err = io.WriteString(file, data)
CheckError(err)
fmt.Fprintf(color.Output, "%s: Created file '%s'\n", color.CyanString("INFO"), filename)
return file.Sync()
}
// WriteToLog will create a log if it doesn't exist and then append
// messages to the log
func WriteToLog(path string, data string, level string) error {
f, err := os.OpenFile(path,
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0755)
CheckError(err)
defer f.Close()
logger := log.New(f, level, log.LstdFlags)
logger.Println(data)
return nil
}
// CreateConfigFile creates a default terracreds config file if one does not
// exist in the same path as the binary
func CreateConfigFile() error {
bin := GetBinaryPath(os.Args[0])
path := bin + "config.yaml"
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
doc := heredoc.Doc(`
logging:
enabled: false
path:`)
WriteToFile(path, doc)
}
}
return nil
}
// LoadConfig loads the config file if it exists
// and creates the config file if doesn't exist
func LoadConfig(cfg *Config) error {
CreateConfigFile()
bin := GetBinaryPath(os.Args[0])
path := bin + "config.yaml"
f, err := os.Open(string(path))
CheckError(err)
defer f.Close()
decoder := yaml.NewDecoder(f)
err = decoder.Decode(cfg)
CheckError(err)
return err
}
// CreateCredential checks the current os
// then creates a credential object in its vault
func CreateCredential(c *cli.Context, hostname string, apiToken string) {
user, err := user.Current()
CheckError(err)
if runtime.GOOS == "windows" {
var method string
_, err := wincred.GetGenericCredential(hostname)
if err != nil {
method = "Created"
} else {
method = "Updated"
}
cred := wincred.NewGenericCredential(hostname)
cred.CredentialBlob = []byte(apiToken)
cred.UserName = string(user.Username)
err = cred.Write()
if err == nil {
fmt.Fprintf(color.Output, "%s: %s the credential object '%s'\n", color.GreenString("SUCCESS"), method, hostname)
} else {
fmt.Fprintf(color.Output, "%s: You do not have permission to create this credential\n", color.RedString("ERROR"))
}
}
if runtime.GOOS == "darwin" {
var method string
_, err := keyring.Get(hostname, string(user.Username))
if err != nil {
method = "Created"
} else {
method = "Updated"
}
err = keyring.Set(hostname, string(user.Username), apiToken)
if err == nil {
fmt.Fprintf(color.Output, "%s: %s the credential object '%s'\n", color.GreenString("SUCCESS"), method, hostname)
} else {
fmt.Fprintf(color.Output, "%s: You do not have permission to create this credential\n", color.RedString("ERROR"))
}
}
}
// DeleteCredential removes the identified credential
// from the vault
func DeleteCredential(c *cli.Context, cfg Config, hostname string) {
user, err := user.Current()
CheckError(err)
if runtime.GOOS == "windows" {
cred, err := wincred.GetGenericCredential(hostname)
if err == nil && cred.UserName == user.Username {
cred.Delete()
msg := "The credential object '" + hostname + "' has been removed"
fmt.Fprintf(color.Output, "%s: %s\n", color.GreenString("SUCCESS"), msg)
if cfg.Logging.Enabled == true {
logPath := cfg.Logging.Path + "terracreds.log"
WriteToLog(logPath, msg, "INFO: ")
}
} else {
fmt.Fprintf(color.Output, "%s: You do not have permission to modify this credential\n", color.RedString("ERROR"))
}
}
if runtime.GOOS == "darwin" {
err := keyring.Delete(hostname, string(user.Username))
if err == nil {
msg := "The credential object '" + hostname + "' has been removed"
fmt.Fprintf(color.Output, "%s: %s\n", color.GreenString("SUCCESS"), msg)
if cfg.Logging.Enabled == true {
logPath := cfg.Logging.Path + "terracreds.log"
WriteToLog(logPath, msg, "INFO: ")
}
} else {
fmt.Fprintf(color.Output, "%s: You do not have permission to modify this credential\n", color.RedString("ERROR"))
}
}
}
// GenerateTerracreds creates the binary to use this package as a credential helper
// and optionally the terraform.rc file
func GenerateTerracreds(c *cli.Context) {
var cliConfig string
var tfPlugins string
var binary string
if runtime.GOOS == "windows" {
userProfile := os.Getenv("USERPROFILE")
if c.Bool("windows-legacy-cli-config") == true {
cliConfig = userProfile + "\\AppData\\Roaming\\terraform.rc"
} else {
cliConfig = userProfile + "\\AppData\\Roaming\\terraform.d\\terraform.rc"
}
tfPlugins = userProfile + "\\AppData\\Roaming\\terraform.d\\plugins"
binary = tfPlugins + "\\terraform-credentials-terracreds.exe"
}
if runtime.GOOS == "darwin" {
userProfile := os.Getenv("HOME")
cliConfig = userProfile + "/.terraformrc"
tfPlugins = userProfile + "/plugins"
binary = tfPlugins + "/terraform-credentials-terracreds"
}
NewDirectory(tfPlugins)
CopyTerraCreds(binary)
if c.Bool("create-cli-config") == true || c.Bool("windows-legacy-cli-config") == true {
doc := heredoc.Doc(`
credentials_helper "terracreds" {
args = []
}`)
WriteToFile(cliConfig, doc)
}
}
// GetCredential returns the stored credential as a JSON
// object as required to be consumed by Terraform Cloud/Enterprise
func GetCredential(c *cli.Context, cfg Config, hostname string) {
user, err := user.Current()
var logPath string
CheckError(err)
if runtime.GOOS == "windows" {
if cfg.Logging.Enabled == true {
logPath = cfg.Logging.Path + "terracreds.log"
WriteToLog(logPath, "- terraform server: "+hostname, "INFO: ")
WriteToLog(logPath, "- user requesting access: "+string(user.Username), "INFO: ")
}
cred, err := wincred.GetGenericCredential(hostname)
if err == nil && cred.UserName == user.Username {
response := &CredentialResponse{
Token: string(cred.CredentialBlob),
}
responseA, _ := json.Marshal(response)
fmt.Println(string(responseA))
if cfg.Logging.Enabled == true {
WriteToLog(logPath, "- token was retrieved for: "+hostname, "INFO: ")
}
} else {
if cfg.Logging.Enabled == true {
WriteToLog(logPath, "- access was denied for user: "+string(user.Username), "ERROR: ")
}
fmt.Fprintf(color.Output, "%s: You do not have permission to view this credential\n", color.RedString("ERROR"))
}
}
if runtime.GOOS == "darwin" {
if cfg.Logging.Enabled == true {
logPath = cfg.Logging.Path + "terracreds.log"
WriteToLog(logPath, "- terraform server: "+hostname, "INFO: ")
WriteToLog(logPath, "- user requesting access: "+string(user.Username), "INFO: ")
}
secret, err := keyring.Get(hostname, string(user.Username))
if err != nil {
if cfg.Logging.Enabled == true {
WriteToLog(logPath, "- access was denied for user: "+string(user.Username), "ERROR: ")
}
fmt.Fprintf(color.Output, "%s: You do not have permission to view this credential\n", color.RedString("ERROR"))
} else {
response := &CredentialResponse{
Token: secret,
}
responseA, _ := json.Marshal(response)
fmt.Println(string(responseA))
if cfg.Logging.Enabled == true {
WriteToLog(logPath, "- token was retrieved for: "+hostname, "INFO: ")
}
}
}
}
// Config struct for terracreds custom configuration
type Config struct {
Logging struct {
Enabled bool `yaml:"enabled"`
Path string `yaml:"path"`
} `yaml:"logging"`
}
// CredentialResponse formatted for consumption by Terraform
type CredentialResponse struct {
Token string `json:"token"`
}
func main() {
var cfg Config
var logPath string
version := "1.0.3"
LoadConfig(&cfg)
app := &cli.App{
Name: "terracreds",
Usage: "a credential helper for Terraform Cloud/Enterprise that leverages the local operating system's credential manager for securely storing your API tokens.\n\n Visit https://github.com/tonedefdev/terracreds for more information",
UsageText: "terracreds create -n api.terraform.com -t sampleApiTokenString",
Version: version,
Commands: []*cli.Command{
{
Name: "create",
Aliases: []string{"store"},
Usage: "Create or update a credential object in the local operating sytem's credential manager that contains the Terraform Cloud/Enterprise authorization token",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "hostname",
Aliases: []string{"n"},
Value: "",
Usage: "The name of the Terraform Cloud/Enterprise server's hostname. This is also the display name of the credential object",
},
&cli.StringFlag{
Name: "apiToken",
Aliases: []string{"t"},
Value: "",
Usage: "The Terraform Cloud/Enterprise API authorization token to be securely stored in the local operating system's credential manager",
},
},
Action: func(c *cli.Context) error {
if len(os.Args) == 2 {
fmt.Fprintf(color.Output, "%s: No hostname or token was specified. Use 'terracreds create -h' to print help info\n", color.RedString("ERROR"))
} else {
CreateCredential(c, c.String("hostname"), c.String("apiToken"))
}
return nil
},
},
{
Name: "delete",
Aliases: []string{"forget"},
Usage: "Delete a credential stored in the local operating system's credential manager",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "hostname",
Aliases: []string{"n"},
Value: "",
Usage: "The name of the Terraform Cloud/Enterprise server's hostname. This is also the display name of the credential object",
},
},
Action: func(c *cli.Context) error {
if len(os.Args) == 2 {
fmt.Fprintf(color.Output, "%s: No hostname was specified. Use 'terracreds delete -h' for help info\n", color.RedString("ERROR"))
} else if !strings.Contains(os.Args[2], "-n") {
msg := "A hostname was not expected here. Did you mean"
if cfg.Logging.Enabled == true {
logPath = cfg.Logging.Path + "terracreds.log"
WriteToLog(logPath, msg, "WARNING: ")
}
fmt.Fprintf(color.Output, "%s: %s 'terracreds delete -n %s'?\n", color.YellowString("WARNING"), msg, os.Args[2])
} else {
hostname := c.String("hostname")
DeleteCredential(c, cfg, hostname)
}
return nil
},
},
{
Name: "generate",
Usage: "Generate the folders and plugin binary required to leverage terracreds as a Terraform credential helper",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "create-cli-config",
Value: false,
Usage: "Creates the Terraform CLI config with a terracreds credential helper block for Terraform 0.12 and newer. This will overwrite the existing file if it already exists.",
},
&cli.BoolFlag{
Name: "windows-legacy-cli-config",
Value: false,
Usage: "Generates the terraform.rc file in the %APPDATA%\\Roaming directory instead of in the terraform.d directory to support versions of Terraform 0.11 and older on Windows OS",
},
},
Action: func(c *cli.Context) error {
GenerateTerracreds(c)
return nil
},
},
{
Name: "get",
Usage: "Get the credential object value by passing the hostname of the Terraform Cloud/Enterprise server as an argument. The credential is returned as a JSON object and formatted for consumption by Terraform",
Action: func(c *cli.Context) error {
if len(os.Args) > 2 {
hostname := os.Args[2]
GetCredential(c, cfg, hostname)
} else {
msg := "A hostname was expected after the 'get' command but no argument was provided"
if cfg.Logging.Enabled == true {
logPath = cfg.Logging.Path + "terracreds.log"
WriteToLog(logPath, msg, "ERROR: ")
}
fmt.Fprintf(color.Output, "%s: %s\n", color.RedString("ERROR"), msg)
}
return nil
},
},
},
}
err := app.Run(os.Args)
CheckError(err)
}