-
Notifications
You must be signed in to change notification settings - Fork 7
/
secrets.go
263 lines (232 loc) · 7.79 KB
/
secrets.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
package main
import (
"bufio"
"encoding/json"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"os/user"
"path/filepath"
"strconv"
"strings"
"sync"
)
// Mutex to protect critical regions when performing file system related activities
// with possible race conditions such as checking for the existance of directory
// before creating it.
var fileSysCreateMutex sync.Mutex
// http://stackoverflow.com/questions/21060945/simple-way-to-copy-a-file-in-golang/21067803#21067803
// copyFileContents copies the contents of the file named src to the file named
// by dst. The file will be created if it does not already exist. If the
// destination file exists, all it's contents will be replaced by the contents
// of the source file.
func copyFileContents(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer func() {
cerr := out.Close()
if err == nil {
err = cerr
}
}()
if _, err = io.Copy(out, in); err != nil {
return err
}
err = out.Sync()
return err
}
//
// return a list of secrets file names from the --secrets-files option and env var $SECRETS_FILES
//
// Secrets can come from (in order of precedence):
// 1) --secrets-file <file> (one or more times)
// 2) $SECRETS_FILES
func getSecretsFileNames() []string {
var secretsFileNames []string
//:= make([]string, len(secretsFilesFlag)+len(strings.Split(os.Getenv("SECRETS_FILES"), ":"))+1)
// backward compatibility for OLD env var
if os.Getenv("SECRETS_FILE") != "" {
log.Println("Warning $SECRETS_FILE is deprecated, use $SECRETS_FILES instead")
secretsFileNames = append(secretsFileNames, os.Getenv("SECRETS_FILE"))
}
if os.Getenv("SECRETS_FILES") != "" {
secretsFileNames = append(secretsFileNames, strings.Split(os.Getenv("SECRETS_FILES"), ":")...)
}
// Command line options override the environment, so we process those LAST
for _, secretsFileName := range secretsFilesFlag {
secretsFileNames = append(secretsFileNames, strings.Split(secretsFileName, ":")...)
}
// Allow template substitutions in file names. Works for {{ .Env.VAR }}, but not for {{ .Secret.VAR }}
for i, secretsFileName := range secretsFileNames {
secretsFileNames[i] = string_template_eval(secretsFileName)
}
return secretsFileNames
}
//
// return a map of secrets
//
func getSecrets() map[string]string {
secrets := make(map[string]string)
for _, secretsFileName := range getSecretsFileNames() {
secretsFile, err := os.Open(secretsFileName)
if err != nil {
log.Fatalf("Error opening secrets file '%s':%s", secretsFileName, err)
}
if verboseFlag {
log.Printf("Loading secrets from: %s:", secretsFileName)
}
defer secretsFile.Close()
bSecretsFile := bufio.NewReader(secretsFile)
if strings.HasSuffix(secretsFileName, ".env") {
for {
line_bytes, isPrefix, err := bSecretsFile.ReadLine()
line := string(line_bytes)
if err == io.EOF {
break
}
if err != nil {
log.Fatalf("Error reading secrets file '%s':%s", secretsFileName, err)
}
if isPrefix {
log.Fatal("Error secrets file too long: ", secretsFileName)
}
if strings.HasPrefix(line, "#") {
continue
}
parts := strings.SplitN(line, "=", 2)
if len(parts) < 2 {
continue
}
key, value := parts[0], strings.Trim(strings.TrimSpace(parts[1]), `'"`)
secrets[key] = value
if debugFlag {
log.Printf("loaded secret: %s", key)
}
}
} else if strings.HasSuffix(secretsFileName, ".json") {
jsonData, err := ioutil.ReadAll(secretsFile)
if err != nil {
log.Fatalf("Error reading JSON secrets file '%s':%s", secretsFileName, err)
}
err = json.Unmarshal(jsonData, &secrets)
if err != nil {
log.Fatalf("Error reading JSON secrets file '%s':%s", secretsFileName, err)
}
for key, value := range secrets {
secrets[key] = value
if debugFlag {
log.Printf("loaded secret: %s", key)
}
}
} else {
log.Fatalf("Unknown file extension '%s' must end with .env or .json\n", secretsFileName)
}
log.Println("")
}
return secrets
}
// Note that secrets files are typically readable only the root user, and node programs and python programs
// may benefit from the illusion that there is a single SECRETS_FILE (combining all keys)
//
// If this command is running under a different user account, then copy the SECRETS_FILES
// and --secret-files into the home directory .secrets (as an emphermeral file)
// and make them readable by the by the user account in case the application wants
// to read the file directly, instead of just using a template to alter a config file.
//
// Set the cmd.Env['SECRETS_FILES'] to point to the new, readable copy
func copySecretsFiles(cmd *exec.Cmd) error {
// If there is no Credential.Uid or its root, then there is no need to copy the secrets files
// because the root user can always read them, but on the otherhand, the combined file is useful
// so lets just do it.
// if cmd.SysProcAttr == nil || cmd.SysProcAttr.Credential == nil || cmd.SysProcAttr.Credential.Uid == 0 {
// return nil
// }
// If we are not running in a container, then do not copy secrets files because the copies
// will not be ephemeral
if _, err := os.Stat("/.dockerenv"); os.IsNotExist(err) {
return nil
}
fileSysCreateMutex.Lock()
defer fileSysCreateMutex.Unlock()
cmdUid := os.Getuid()
cmdGid := os.Getgid()
if cmd.SysProcAttr != nil && cmd.SysProcAttr.Credential != nil {
cmdUid = int(cmd.SysProcAttr.Credential.Uid)
cmdGid = int(cmd.SysProcAttr.Credential.Gid)
}
if cmdUser, err := user.LookupId(strconv.Itoa(cmdUid)); err != nil {
return err
} else {
// Pass new SECRETS_FILES to the cmd.Env
cmd.Env = make([]string, len(os.Environ())+2, len(os.Environ())+2)
envCount := 0
// Copy all ENV vars, except SECRETS_FILE.*
for _, envLine := range os.Environ() {
if !strings.HasPrefix(envLine, "SECRETS_FILE") {
cmd.Env[envCount] = envLine
envCount++
}
}
secretsDir := cmdUser.HomeDir + "/.secrets/"
cmd.Env[envCount] = "SECRETS_FILE=" + secretsDir + "combined_secrets.json"
envCount++
// Rebase all individual secrets-files paths to secretsDir
secretsFileNames := getSecretsFileNames()
newSecretsFileNames := make([]string, len(secretsFileNames))
for i, secretsFileName := range getSecretsFileNames() {
newSecretsFileNames[i] = secretsDir + filepath.Base(secretsFileName)
}
cmd.Env[envCount] = "SECRETS_FILES=" + strings.Join(newSecretsFileNames, ":")
envCount++
// If we have not already done so, then copy all the secrets files to secretsDir
// and write the combined_secrets.json file
if _, err := os.Stat(secretsDir); err == nil {
// we've already created it for some other Cmd run as this cmdUser
return nil
}
// Create ~/.secrets dir for the cmdUser
if _, err := os.Stat(secretsDir); os.IsNotExist(err) {
// path/to/whatever does not exist
if err := os.Mkdir(secretsDir, 0700); err != nil {
return err
}
if err := os.Chown(secretsDir, cmdUid, cmdGid); err != nil {
return err
}
}
// Create a combined secrets file with all secrets
if jsonData, err := json.MarshalIndent(getSecrets(), "", " "); err == nil {
if err := ioutil.WriteFile(secretsDir+"combined_secrets.json", jsonData, 0400); err != nil {
return err
}
if err := os.Chown(secretsDir+"combined_secrets.json", cmdUid, cmdGid); err != nil {
return err
}
} else {
return err
}
// Copy all the individual secrets files into secretsDir
for _, secretsFileName := range getSecretsFileNames() {
copyName := secretsDir + "/" + filepath.Base(secretsFileName)
if err := copyFileContents(secretsFileName, copyName); err != nil {
return err
}
if err := os.Chown(copyName, cmdUid, cmdGid); err != nil {
return err
}
if err := os.Chmod(copyName, 0400); err != nil {
return err
}
}
}
return nil
}