-
Notifications
You must be signed in to change notification settings - Fork 31
/
main.go
293 lines (269 loc) · 7.81 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
package main
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"syscall"
"secrets-init/pkg/secrets" //nolint:gci
"secrets-init/pkg/secrets/aws"
"secrets-init/pkg/secrets/google"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
"golang.org/x/sys/unix" //nolint:gci
)
var (
// Version contains the current Version.
Version = "dev"
// BuildDate contains a string with the build BuildDate.
BuildDate = "unknown"
// GitCommit git commit sha
GitCommit = "dirty"
// GitBranch git branch
GitBranch = "dirty"
// Platform OS/ARCH
Platform = ""
)
func main() {
app := &cli.App{
Before: setLogFormatter,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "log-format, l",
Usage: "select logrus formatter ['json', 'text']",
Value: "text",
EnvVars: []string{"SECRETS_INIT_LOG_FORMAT", "LOG_FORMAT"},
},
&cli.StringFlag{
Name: "provider, p",
Usage: "supported secrets manager provider ['aws', 'google']",
Value: "aws",
EnvVars: []string{"SECRETS_INIT_SECRETS_PROVIDER", "SECRETS_PROVIDER"},
},
&cli.BoolFlag{
Name: "exit-early",
Usage: "exit when a provider fails or a secret is not found",
EnvVars: []string{"SECRETS_INIT_EXIT_EARLY", "EXIT_EARLY"},
},
&cli.StringFlag{
Name: "google-project",
Usage: "the google cloud project for secrets without a project prefix",
EnvVars: []string{"SECRETS_INIT_GOOGLE_PROJECT", "GOOGLE_PROJECT"},
},
&cli.BoolFlag{
Name: "interactive",
Aliases: []string{"i"},
Usage: "use this flag if the command expects some input from the stdin",
},
},
Commands: []*cli.Command{
{
Name: "copy",
Aliases: []string{"cp"},
Usage: "copy itself to a destination folder",
ArgsUsage: "destination",
Action: copyCmd,
},
},
Name: "secrets-init",
Usage: "enrich environment variables with secrets from secret manager",
Action: mainCmd,
Version: Version,
}
cli.VersionPrinter = func(_ *cli.Context) {
fmt.Printf("version: %s\n", Version)
fmt.Printf(" build date: %s\n", BuildDate)
fmt.Printf(" commit: %s\n", GitCommit)
fmt.Printf(" branch: %s\n", GitBranch)
fmt.Printf(" platform: %s\n", Platform)
fmt.Printf(" built with: %s\n", runtime.Version())
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func copyCmd(c *cli.Context) error {
if c.Args().Len() != 1 {
return errors.New("must specify copy destination")
}
// full path of current executable
src := os.Args[0]
// destination path
dest := filepath.Join(c.Args().First(), filepath.Base(src))
// copy file with current file mode flags
sourceFileStat, err := os.Stat(src)
if err != nil {
return errors.Wrap(err, "failed to stat source file")
}
if !sourceFileStat.Mode().IsRegular() {
return errors.Errorf("%s is not a regular file", src)
}
source, err := os.Open(src)
if err != nil {
return errors.Wrap(err, "failed to open source file")
}
srcInfo, err := source.Stat()
if err != nil {
return errors.Wrap(err, "failed to stat source file")
}
defer func() { _ = source.Close() }()
destination, err := os.Create(dest)
if err != nil {
return errors.Wrapf(err, "failed to create %s", dest)
}
defer func() { _ = destination.Close() }()
_, err = io.Copy(destination, source)
if err != nil {
return errors.Wrap(err, "failed to copy file")
}
err = destination.Chmod(srcInfo.Mode())
if err != nil {
return errors.Wrap(err, "failed to set file mode")
}
return nil
}
func mainCmd(c *cli.Context) error {
ctx := context.Background()
// get provider
var provider secrets.Provider
var err error
if c.String("provider") == "aws" {
provider, err = aws.NewAwsSecretsProvider()
} else if c.String("provider") == "google" {
provider, err = google.NewGoogleSecretsProvider(ctx, c.String("google-project"))
}
if err != nil {
log.WithField("provider", c.String("provider")).WithError(err).Error("failed to initialize secrets provider")
if c.Bool("exit-early") {
os.Exit(1)
}
}
// Launch main command
var childPid int
childPid, err = run(ctx, provider, c.Bool("exit-early"), c.Bool("interactive"), c.Args().Slice())
if err != nil {
log.WithError(err).Error("failed to run")
os.Exit(1)
}
// Routine to reap zombies (it's the job of init)
removeZombies(childPid)
return nil
}
func removeZombies(childPid int) {
var exitCode int
for {
var status syscall.WaitStatus
// wait for an orphaned zombie process
pid, err := syscall.Wait4(-1, &status, 0, nil)
if pid == -1 {
// if errno == ECHILD then no children remain; exit cleanly
if errors.Is(err, syscall.ECHILD) {
break
}
log.WithError(err).Error("unexpected wait4 error")
os.Exit(1)
}
// check if pid is child, if so save
// PID is > 0 if a child was reaped, and we immediately check if another one is waiting
if pid == childPid {
exitCode = status.ExitStatus()
}
continue
}
// no more children, exit with the same code as the child process
os.Exit(exitCode)
}
// run passed command
func run(ctx context.Context, provider secrets.Provider, exitEarly, interactive bool, commandSlice []string) (childPid int, err error) {
var commandStr string
var argsSlice []string
if len(commandSlice) == 0 {
log.Warn("no command specified")
return childPid, err
}
// split command and arguments
commandStr = commandSlice[0]
// if there is args
if len(commandSlice) > 1 {
argsSlice = commandSlice[1:]
}
// register a channel to receive system signals
sigs := make(chan os.Signal, 1)
signal.Notify(sigs)
// define a command and rebind its stdout and stdin
cmd := exec.Command(commandStr, argsSlice...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// create a dedicated pidgroup used to forward signals to the main process and its children
procAttrs := &syscall.SysProcAttr{Setpgid: true}
// rebind stdin if -i flag is set
if interactive {
cmd.Stdin = os.Stdin
// setting 'Foreground' to true will bind current TTY to the child process
procAttrs = &syscall.SysProcAttr{Setpgid: true, Foreground: true}
}
// set child process attributes
cmd.SysProcAttr = procAttrs
// set environment variables
if provider != nil {
cmd.Env, err = provider.ResolveSecrets(ctx, os.Environ())
if err != nil {
log.WithError(err).Error("failed to resolve secrets")
if exitEarly {
log.Error("Exiting early unable to retrieve secrets")
os.Exit(1)
}
}
} else {
log.Warn("no secrets provider available; using environment without resolving secrets")
cmd.Env = os.Environ()
}
// start the specified command
log.WithFields(log.Fields{
"command": commandStr,
"args": argsSlice,
"env": cmd.Env,
}).Debug("starting command")
err = cmd.Start()
if err != nil {
return childPid, errors.Wrap(err, "failed to start command")
}
childPid = cmd.Process.Pid
// Goroutine for signals forwarding
go func() {
for sig := range sigs {
// ignore:
// - SIGCHLD signals, since these are only useful for secrets-init
// - SIGURG signals, since they are used internally by the secrets-init
// go runtime (see https://github.com/golang/go/issues/37942) and are of
// no interest to the child process
if sig != syscall.SIGCHLD && sig != syscall.SIGURG {
// forward signal to the main process and its children
e := syscall.Kill(-cmd.Process.Pid, sig.(syscall.Signal))
if e != nil {
log.WithFields(log.Fields{
"pid": cmd.Process.Pid,
"path": cmd.Path,
"args": cmd.Args,
"signal": unix.SignalName(sig.(syscall.Signal)),
}).WithError(e).Error("failed to send system signal to the process")
}
}
}
}()
return childPid, nil
}
func setLogFormatter(c *cli.Context) error {
if c.String("log-format") == "json" {
log.SetFormatter(&log.JSONFormatter{})
} else if c.String("log-format") == "text" {
log.SetFormatter(&log.TextFormatter{})
}
return nil
}