-
Notifications
You must be signed in to change notification settings - Fork 13
/
cli-client.go
336 lines (276 loc) · 8.2 KB
/
cli-client.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
package main
import (
"fmt"
"io/ioutil"
"log"
"net"
"os"
"os/signal"
"syscall"
"time"
"golang.org/x/net/context"
"gopkg.in/yaml.v2"
"github.com/aws/aws-sdk-go/aws/credentials"
pb "github.com/otm/limes/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
)
type awsEnv struct {
AccessKeyID string
SecretAccessKey string
SessionToken string
Region string
}
type cliClient struct {
conn *grpc.ClientConn
srv pb.InstanceMetaServiceClient
}
func newCliClient(address string) *cliClient {
client := &cliClient{}
dialer := func(addr string, timeout time.Duration) (net.Conn, error) {
return net.DialTimeout("unix", addr, timeout)
}
grpclog.SetLogger(log.New(ioutil.Discard, "", log.LstdFlags))
conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithDialer(dialer), grpc.WithTimeout(1*time.Second))
if err != nil {
log.Fatalf("did not connect: %v\n", err)
}
client.conn = conn
client.srv = pb.NewInstanceMetaServiceClient(conn)
return client
}
// StartService bootstraps the metadata service
func StartService(configFile, address, profileName, MFA string, port int, fake bool) {
log := &ConsoleLogger{}
config := Config{}
// TODO: Move to function and use a default configuration file
if configFile != "" {
// Parse in options from the given config file.
log.Debug("Loading configuration: %s\n", configFile)
configContents, configErr := ioutil.ReadFile(configFile)
if configErr != nil {
log.Fatalf("Error reading config: %s\n", configErr.Error())
}
configParseErr := yaml.Unmarshal(configContents, &config)
if configParseErr != nil {
log.Fatalf("Error in parsing config file: %s\n", configParseErr.Error())
}
if len(config.Profiles) == 0 {
log.Info("No profiles found, falling back to old config format.\n")
configParseErr := yaml.Unmarshal(configContents, &config.Profiles)
if configParseErr != nil {
log.Fatalf("Error in parsing config file: %s\n", configParseErr.Error())
}
if len(config.Profiles) > 0 {
log.Warning("WARNING: old deprecated config format is used.\n")
}
}
} else {
log.Debug("No configuration file given\n")
}
defer func() {
log.Debug("Removing socket: %v\n", address)
os.Remove(address)
}()
if port == 0 {
port = config.Port
}
if port == 0 {
port = 80
}
// Startup the HTTP server and respond to requests.
listener, err := net.ListenTCP("tcp", &net.TCPAddr{
IP: net.ParseIP("169.254.169.254"),
Port: port,
})
if err != nil {
log.Fatalf("Failed to bind to socket: %s\n", err)
}
var credsManager CredentialsManager
if fake {
credsManager = &FakeCredentialsManager{}
} else {
credsManager = NewCredentialsExpirationManager(profileName, config, MFA)
}
log.Info("Starting web service: %v:%v\n", "169.254.169.254", port)
mds, metadataError := NewMetadataService(listener, credsManager)
if metadataError != nil {
log.Fatalf("Failed to start metadata service: %s\n", metadataError.Error())
}
mds.Start()
stop := make(chan struct{})
agentServer := NewCliHandler(address, credsManager, stop, config)
err = agentServer.Start()
if err != nil {
log.Fatalf("Failed to start agentServer: %s\n", err.Error())
}
// Wait for a graceful shutdown signal
terminate := make(chan os.Signal)
signal.Notify(terminate, syscall.SIGINT, syscall.SIGTERM)
log.Info("Service: online\n")
defer log.Info("Caught signal: shutting down.\n")
for {
select {
case <-stop:
return
case <-terminate:
return
}
}
}
func (c *cliClient) close() error {
return c.conn.Close()
}
func (c *cliClient) stop(args *Stop) error {
_, err := c.srv.Stop(context.Background(), &pb.Void{})
if err != nil {
if grpc.ErrorDesc(err) == grpc.ErrClientConnClosing.Error() {
return nil
}
fmt.Fprintf(os.Stderr, "limes: unknown error: %v\n", err)
os.Exit(1)
}
fmt.Println("Limes service is stopping")
return nil
}
func (c *cliClient) printStatus(args *Status) error {
status := true
service := "up"
r, err := c.srv.Status(context.Background(), &pb.Void{})
if err != nil {
r = &pb.StatusReply{
Role: "n/a",
AccessKeyId: "n/a",
SecretAccessKey: "n/a",
SessionToken: "n/a",
Expiration: "n/a",
}
service = "down"
status = false
defer fmt.Fprintf(errout, "\n%v", lookupCorrection(err))
}
if r.Error != "" {
service = "error"
status = false
defer fmt.Fprintf(errout, "\nerror communication with daemon: %v\n", r.Error)
}
env := "ok"
errConf := checkActiveAWSConfig()
if errConf != nil {
env = "nok"
status = false
defer fmt.Fprintf(errout, "run 'limes fix' to automatically resolve the problem\n")
defer fmt.Fprintf(errout, "\nwarning: %v\n", errConf)
}
if !status {
fmt.Fprintf(out, "Status: %v\n", "nok")
} else {
fmt.Fprintf(out, "Status: %v\n", "ok")
}
fmt.Fprintf(out, "Profile: %v\n", r.Role)
if args.Verbose == false {
return err
}
fmt.Fprintf(out, "Server: %v\n", service)
fmt.Fprintf(out, "AWS Config: %v\n", env)
fmt.Fprintf(out, "AccessKeyId: %v\n", r.AccessKeyId)
fmt.Fprintf(out, "SecretAccessKey: %v\n", r.SecretAccessKey)
fmt.Fprintf(out, "SessionToken: %v\n", r.SessionToken)
fmt.Fprintf(out, "Expiration: %v\n", r.Expiration)
return err
}
func (c *cliClient) status() (*pb.StatusReply, error) {
return c.srv.Status(context.Background(), &pb.Void{})
}
func (c *cliClient) assumeRole(role string, MFA string) error {
r, err := c.srv.AssumeRole(context.Background(), &pb.AssumeRoleRequest{Name: role, Mfa: MFA})
if err != nil {
if grpc.Code(err) == codes.FailedPrecondition && grpc.ErrorDesc(err) == errMFANeeded.Error() {
return c.assumeRole(role, askMFA())
}
fmt.Fprintf(os.Stderr, "error: %v\n", err)
return err
}
fmt.Fprintf(out, "Assumed: %v\n", r.Role)
return nil
}
func (c *cliClient) retreiveRole(role, MFA string) (*credentials.Credentials, error) {
r, err := c.srv.RetrieveRole(context.Background(), &pb.AssumeRoleRequest{Name: role, Mfa: MFA})
if err != nil {
if grpc.Code(err) == codes.FailedPrecondition && grpc.ErrorDesc(err) == errMFANeeded.Error() {
return c.retreiveRole(role, askMFA())
}
fmt.Fprintf(os.Stderr, "error: %v\n", err)
return nil, err
}
creds := credentials.NewStaticCredentials(
r.AccessKeyId,
r.SecretAccessKey,
r.SessionToken,
)
return creds, nil
}
func (c *cliClient) retreiveAWSEnv(role, MFA string) (awsEnv, error) {
r, err := c.srv.RetrieveRole(context.Background(), &pb.AssumeRoleRequest{Name: role, Mfa: MFA})
if err != nil {
if grpc.Code(err) == codes.FailedPrecondition && grpc.ErrorDesc(err) == errMFANeeded.Error() {
return c.retreiveAWSEnv(role, askMFA())
}
fmt.Fprintf(os.Stderr, "error: %v\n", err)
return awsEnv{}, err
}
fmt.Println("client got region: ", r.Region)
creds := awsEnv{
AccessKeyID: r.AccessKeyId,
SecretAccessKey: r.SecretAccessKey,
SessionToken: r.SessionToken,
Region: r.Region,
}
return creds, nil
}
// Config(ctx context.Context, in *Void, opts ...grpc.CallOption) (*ConfigReply, error)
func (c *cliClient) listRoles() ([]string, error) {
r, err := c.srv.Config(context.Background(), &pb.Void{})
if err != nil {
showCorrectionAndExit(err)
fmt.Fprintf(os.Stderr, "communication error: %v\n", err)
return nil, err
}
roles := make([]string, 0, len(r.Profiles))
for role := range r.Profiles {
roles = append(roles, role)
}
return roles, nil
}
// ask the user for an MFA token
func askMFA() string {
var MFA string
fmt.Printf("Enter MFA: ")
_, err := fmt.Scanf("%s", &MFA)
if err != nil {
log.Fatalf("err: %v\n", err)
}
return MFA
}
func showCorrectionAndExit(err error) {
fmt.Fprintf(errout, lookupCorrection(err))
os.Exit(1)
}
func lookupCorrection(err error) string {
switch grpc.Code(err) {
case codes.FailedPrecondition:
switch grpc.ErrorDesc(err) {
case errMFANeeded.Error():
return fmt.Sprintf("%v: run 'limes assume <profile>'\n", grpc.ErrorDesc(err))
case errUnknownProfile.Error():
return fmt.Sprintf("%v: run 'limes assume <profile>'\n", grpc.ErrorDesc(err))
}
case codes.Unknown:
switch grpc.ErrorDesc(err) {
case grpc.ErrClientConnClosing.Error(), grpc.ErrClientConnTimeout.Error():
return fmt.Sprintf("service down: run 'limes start'\n")
}
}
return fmt.Sprintf("%s\n", err)
}