forked from segmentio/aws-okta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.go
202 lines (167 loc) · 4.57 KB
/
exec.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
package cmd
import (
"fmt"
"os"
"os/exec"
"os/signal"
"strings"
"syscall"
"time"
"github.com/99designs/keyring"
"github.com/segmentio/aws-okta/lib"
"github.com/spf13/cobra"
)
var (
sessionTTL time.Duration
assumeRoleTTL time.Duration
)
// execCmd represents the exec command
var execCmd = &cobra.Command{
Use: "exec <profile> -- <command>",
Short: "exec will run the command specified with aws credentials set in the environment",
RunE: execRun,
PreRun: execPre,
}
func init() {
RootCmd.AddCommand(execCmd)
execCmd.Flags().DurationVarP(&sessionTTL, "session-ttl", "t", time.Hour, "Expiration time for okta role session")
execCmd.Flags().DurationVarP(&assumeRoleTTL, "assume-role-ttl", "a", time.Hour, "Expiration time for assumed role")
}
func loadDurationFlagFromEnv(cmd *cobra.Command, flagName string, envVar string, val *time.Duration) error {
if cmd.Flags().Lookup(flagName).Changed {
return nil
}
fromEnv, ok := os.LookupEnv(envVar)
if !ok {
return nil
}
dur, err := time.ParseDuration(fromEnv)
if err != nil {
return err
}
*val = dur
return nil
}
func execPre(cmd *cobra.Command, args []string) {
if err := loadDurationFlagFromEnv(cmd, "session-ttl", "AWS_SESSION_TTL", &sessionTTL); err != nil {
fmt.Fprintln(os.Stderr, "warning: failed to parse duration from AWS_SESSION_TTL")
}
if err := loadDurationFlagFromEnv(cmd, "assume-role-ttl", "AWS_ASSUME_ROLE_TTL", &assumeRoleTTL); err != nil {
fmt.Fprintln(os.Stderr, "warning: failed to parse duration from AWS_ASSUME_ROLE_TTL")
}
}
func execRun(cmd *cobra.Command, args []string) error {
dashIx := cmd.ArgsLenAtDash()
if dashIx == -1 {
return ErrCommandMissing
}
args, commandPart := args[:dashIx], args[dashIx:]
if len(args) < 1 {
return ErrTooFewArguments
}
if len(commandPart) == 0 {
return ErrCommandMissing
}
profile := args[0]
command := commandPart[0]
var commandArgs []string
if len(commandPart) > 1 {
commandArgs = commandPart[1:]
}
config, err := lib.NewConfigFromEnv()
if err != nil {
return err
}
profiles, err := config.Parse()
if err != nil {
return err
}
if _, ok := profiles[profile]; !ok {
return fmt.Errorf("Profile '%s' not found in your aws config", profile)
}
opts := lib.ProviderOptions{
Profiles: profiles,
SessionDuration: sessionTTL,
AssumeRoleDuration: assumeRoleTTL,
}
var allowedBackends []keyring.BackendType
if backend != "" {
allowedBackends = append(allowedBackends, keyring.BackendType(backend))
}
kr, err := keyring.Open(keyring.Config{
AllowedBackends: allowedBackends,
KeychainTrustApplication: true,
// this keychain name is for backwards compatibility
ServiceName: "aws-okta-login",
LibSecretCollectionName: "awsvault",
})
if err != nil {
return err
}
p, err := lib.NewProvider(kr, profile, opts)
if err != nil {
return err
}
creds, err := p.Retrieve()
if err != nil {
return err
}
env := environ(os.Environ())
env.Unset("AWS_ACCESS_KEY_ID")
env.Unset("AWS_SECRET_ACCESS_KEY")
env.Unset("AWS_CREDENTIAL_FILE")
env.Unset("AWS_DEFAULT_PROFILE")
env.Unset("AWS_PROFILE")
if region, ok := profiles[profile]["region"]; ok {
env.Set("AWS_DEFAULT_REGION", region)
env.Set("AWS_REGION", region)
}
env.Set("AWS_ACCESS_KEY_ID", creds.AccessKeyID)
env.Set("AWS_SECRET_ACCESS_KEY", creds.SecretAccessKey)
if creds.SessionToken != "" {
env.Set("AWS_SESSION_TOKEN", creds.SessionToken)
env.Set("AWS_SECURITY_TOKEN", creds.SessionToken)
}
ecmd := exec.Command(command, commandArgs...)
ecmd.Stdin = os.Stdin
ecmd.Stdout = os.Stdout
ecmd.Stderr = os.Stderr
ecmd.Env = env
// Forward SIGINT, SIGTERM, SIGKILL to the child command
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGTERM, os.Interrupt, os.Kill)
go func() {
sig := <-sigChan
if ecmd.Process != nil {
ecmd.Process.Signal(sig)
}
}()
var waitStatus syscall.WaitStatus
if err := ecmd.Run(); err != nil {
if err != nil {
return err
}
if exitError, ok := err.(*exec.ExitError); ok {
waitStatus = exitError.Sys().(syscall.WaitStatus)
os.Exit(waitStatus.ExitStatus())
}
}
return nil
}
// environ is a slice of strings representing the environment, in the form "key=value".
type environ []string
// Unset an environment variable by key
func (e *environ) Unset(key string) {
for i := range *e {
if strings.HasPrefix((*e)[i], key+"=") {
(*e)[i] = (*e)[len(*e)-1]
*e = (*e)[:len(*e)-1]
break
}
}
}
// Set adds an environment variable, replacing any existing ones of the same key
func (e *environ) Set(key, val string) {
e.Unset(key)
*e = append(*e, key+"="+val)
}