This repository has been archived by the owner on Jul 16, 2019. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
credentialStore.go
85 lines (72 loc) · 2.18 KB
/
credentialStore.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
package credentials // import "github.com/Luzifer/awsenv/credentials"
import (
"io/ioutil"
"os"
"path"
"github.com/Luzifer/awsenv/security"
"gopkg.in/yaml.v2"
)
// AWSCredentialStore represents a storage for all the credentials
type AWSCredentialStore struct {
Credentials map[string]AWSCredential
databasePassword *security.DatabasePassword `yaml:"-"`
storageFile string `yaml:"-"`
}
// AWSCredential holds the credential set for an environment
type AWSCredential struct {
AWSAccessKeyID string
AWSSecretAccessKey string
AWSRegion string
}
// SaveToFile stores the encrypted version of the AWSCredentialStore to the file
// the store has been loaded from
func (a *AWSCredentialStore) SaveToFile() error {
t, err := yaml.Marshal(a)
if err != nil {
return err
}
enc, err := a.databasePassword.Encrypt(t)
if err != nil {
return err
}
// We don't care about that newline at the end, OpenSSL does throw an
// error if it's not there. So lets add it.
enc = append(enc, '\n')
err = os.MkdirAll(path.Dir(a.storageFile), 0755)
if err != nil {
return err
}
err = ioutil.WriteFile(a.storageFile, enc, 0600)
return err
}
// UpdatePassword changes the password of the store and saves the store encrypted
// with the new password back to its file
func (a *AWSCredentialStore) UpdatePassword(passwd string) error {
a.databasePassword = security.LoadDatabasePasswordFromInput(passwd)
return a.SaveToFile()
}
// FromFile loads an AWSCredentialStore from the given file and decrypts it
func FromFile(filename string, pass *security.DatabasePassword) (*AWSCredentialStore, error) {
enc, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
dec, err := pass.Decrypt(enc)
if err != nil {
return nil, err
}
t := &AWSCredentialStore{
databasePassword: pass,
storageFile: filename,
}
err = yaml.Unmarshal(dec, t)
return t, err
}
// New creates an empty credential store and sets the storage location
func New(storefile string, pass *security.DatabasePassword) *AWSCredentialStore {
return &AWSCredentialStore{
databasePassword: pass,
storageFile: storefile,
Credentials: make(map[string]AWSCredential),
}
}