-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
auth.go
460 lines (387 loc) · 12.4 KB
/
auth.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
package command
import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/helper/kv-builder"
"github.com/hashicorp/vault/helper/password"
"github.com/hashicorp/vault/meta"
"github.com/mitchellh/mapstructure"
"github.com/ryanuber/columnize"
)
// AuthHandler is the interface that any auth handlers must implement
// to enable auth via the CLI.
type AuthHandler interface {
Auth(*api.Client, map[string]string) (string, error)
Help() string
}
// AuthCommand is a Command that handles authentication.
type AuthCommand struct {
meta.Meta
Handlers map[string]AuthHandler
// The fields below can be overwritten for tests
testStdin io.Reader
}
func (c *AuthCommand) Run(args []string) int {
var method, authPath string
var methods, methodHelp, noVerify, noStore, tokenOnly bool
flags := c.Meta.FlagSet("auth", meta.FlagSetDefault)
flags.BoolVar(&methods, "methods", false, "")
flags.BoolVar(&methodHelp, "method-help", false, "")
flags.BoolVar(&noVerify, "no-verify", false, "")
flags.BoolVar(&noStore, "no-store", false, "")
flags.BoolVar(&tokenOnly, "token-only", false, "")
flags.StringVar(&method, "method", "", "method")
flags.StringVar(&authPath, "path", "", "")
flags.Usage = func() { c.Ui.Error(c.Help()) }
if err := flags.Parse(args); err != nil {
return 1
}
if methods {
return c.listMethods()
}
args = flags.Args()
tokenHelper, err := c.TokenHelper()
if err != nil {
c.Ui.Error(fmt.Sprintf(
"Error initializing token helper: %s\n\n"+
"Please verify that the token helper is available and properly\n"+
"configured for your system. Please refer to the documentation\n"+
"on token helpers for more information.",
err))
return 1
}
// token is where the final token will go
handler := c.Handlers[method]
// Read token from stdin if first arg is exactly "-"
var stdin io.Reader = os.Stdin
if c.testStdin != nil {
stdin = c.testStdin
}
if len(args) > 0 && args[0] == "-" {
stdinR := bufio.NewReader(stdin)
args[0], err = stdinR.ReadString('\n')
if err != nil && err != io.EOF {
c.Ui.Error(fmt.Sprintf("Error reading from stdin: %s", err))
return 1
}
args[0] = strings.TrimSpace(args[0])
}
if method == "" {
token := ""
if len(args) > 0 {
token = args[0]
}
handler = &tokenAuthHandler{Token: token}
args = nil
switch authPath {
case "", "auth/token":
default:
c.Ui.Error("Token authentication does not support custom paths")
return 1
}
}
if handler == nil {
methods := make([]string, 0, len(c.Handlers))
for k := range c.Handlers {
methods = append(methods, k)
}
sort.Strings(methods)
c.Ui.Error(fmt.Sprintf(
"Unknown authentication method: %s\n\n"+
"Please use a supported authentication method. The list of supported\n"+
"authentication methods is shown below. Note that this list may not\n"+
"be exhaustive: Vault may support other auth methods. For auth methods\n"+
"unsupported by the CLI, please use the HTTP API.\n\n"+
"%s",
method,
strings.Join(methods, ", ")))
return 1
}
if methodHelp {
c.Ui.Output(handler.Help())
return 0
}
// Warn if the VAULT_TOKEN environment variable is set, as that will take
// precedence. Don't output on token-only since we're likely piping output.
if os.Getenv("VAULT_TOKEN") != "" && !tokenOnly {
c.Ui.Output("==> WARNING: VAULT_TOKEN environment variable set!\n")
c.Ui.Output(" The environment variable takes precedence over the value")
c.Ui.Output(" set by the auth command. Either update the value of the")
c.Ui.Output(" environment variable or unset it to use the new token.\n")
}
var vars map[string]string
if len(args) > 0 {
builder := kvbuilder.Builder{Stdin: os.Stdin}
if err := builder.Add(args...); err != nil {
c.Ui.Error(err.Error())
return 1
}
if err := mapstructure.Decode(builder.Map(), &vars); err != nil {
c.Ui.Error(fmt.Sprintf("Error parsing options: %s", err))
return 1
}
} else {
vars = make(map[string]string)
}
// Build the client so we can auth
client, err := c.Client()
if err != nil {
c.Ui.Error(fmt.Sprintf(
"Error initializing client to auth: %s", err))
return 1
}
if authPath != "" {
vars["mount"] = authPath
}
// Authenticate
token, err := handler.Auth(client, vars)
if err != nil {
c.Ui.Error(err.Error())
return 1
}
// Cache the previous token so that it can be restored if authentication fails
var previousToken string
if previousToken, err = tokenHelper.Get(); err != nil {
c.Ui.Error(fmt.Sprintf("Error caching the previous token: %s\n\n", err))
return 1
}
if tokenOnly {
c.Ui.Output(token)
return 0
}
// Store the token!
if !noStore {
if err := tokenHelper.Store(token); err != nil {
c.Ui.Error(fmt.Sprintf(
"Error storing token: %s\n\n"+
"Authentication was not successful and did not persist.\n"+
"Please reauthenticate, or fix the issue above if possible.",
err))
return 1
}
}
if noVerify {
c.Ui.Output(fmt.Sprintf(
"Authenticated - no token verification has been performed.",
))
if noStore {
if err := tokenHelper.Erase(); err != nil {
c.Ui.Error(fmt.Sprintf(
"Error removing prior token: %s\n\n"+
"Authentication was successful, but unable to remove the\n"+
"previous token.",
err))
return 1
}
}
return 0
}
// Build the client again so it can read the token we just wrote
client, err = c.Client()
if err != nil {
c.Ui.Error(fmt.Sprintf(
"Error initializing client to verify the token: %s", err))
if !noStore {
if err := tokenHelper.Store(previousToken); err != nil {
c.Ui.Error(fmt.Sprintf(
"Error restoring the previous token: %s\n\n"+
"Please reauthenticate with a valid token.",
err))
}
}
return 1
}
// If in no-store mode it won't have read the token from a token-helper (or
// will read an old one) so set it explicitly
if noStore {
client.SetToken(token)
}
// Verify the token
secret, err := client.Auth().Token().LookupSelf()
if err != nil {
c.Ui.Error(fmt.Sprintf(
"Error validating token: %s", err))
if err := tokenHelper.Store(previousToken); err != nil {
c.Ui.Error(fmt.Sprintf(
"Error restoring the previous token: %s\n\n"+
"Please reauthenticate with a valid token.",
err))
}
return 1
}
if secret == nil && !noStore {
c.Ui.Error(fmt.Sprintf("Error: Invalid token"))
if err := tokenHelper.Store(previousToken); err != nil {
c.Ui.Error(fmt.Sprintf(
"Error restoring the previous token: %s\n\n"+
"Please reauthenticate with a valid token.",
err))
}
return 1
}
if noStore {
if err := tokenHelper.Erase(); err != nil {
c.Ui.Error(fmt.Sprintf(
"Error removing prior token: %s\n\n"+
"Authentication was successful, but unable to remove the\n"+
"previous token.",
err))
return 1
}
}
// Get the policies we have
policiesRaw, ok := secret.Data["policies"]
if !ok {
policiesRaw = []string{"unknown"}
}
var policies []string
for _, v := range policiesRaw.([]interface{}) {
policies = append(policies, v.(string))
}
output := "Successfully authenticated! You are now logged in."
if noStore {
output += "\nThe token has not been stored to the configured token helper."
}
if method != "" {
output += "\nThe token below is already saved in the session. You do not"
output += "\nneed to \"vault auth\" again with the token."
}
output += fmt.Sprintf("\ntoken: %s", secret.Data["id"])
output += fmt.Sprintf("\ntoken_duration: %s", secret.Data["ttl"].(json.Number).String())
if len(policies) > 0 {
output += fmt.Sprintf("\ntoken_policies: %v", policies)
}
c.Ui.Output(output)
return 0
}
func (c *AuthCommand) listMethods() int {
client, err := c.Client()
if err != nil {
c.Ui.Error(fmt.Sprintf(
"Error initializing client: %s", err))
return 1
}
auth, err := client.Sys().ListAuth()
if err != nil {
c.Ui.Error(fmt.Sprintf(
"Error reading auth table: %s", err))
return 1
}
paths := make([]string, 0, len(auth))
for path := range auth {
paths = append(paths, path)
}
sort.Strings(paths)
columns := []string{"Path | Type | Accessor | Default TTL | Max TTL | Replication Behavior | Description"}
for _, path := range paths {
auth := auth[path]
defTTL := "system"
if auth.Config.DefaultLeaseTTL != 0 {
defTTL = strconv.Itoa(auth.Config.DefaultLeaseTTL)
}
maxTTL := "system"
if auth.Config.MaxLeaseTTL != 0 {
maxTTL = strconv.Itoa(auth.Config.MaxLeaseTTL)
}
replicatedBehavior := "replicated"
if auth.Local {
replicatedBehavior = "local"
}
columns = append(columns, fmt.Sprintf(
"%s | %s | %s | %s | %s | %s | %s", path, auth.Type, auth.Accessor, defTTL, maxTTL, replicatedBehavior, auth.Description))
}
c.Ui.Output(columnize.SimpleFormat(columns))
return 0
}
func (c *AuthCommand) Synopsis() string {
return "Prints information about how to authenticate with Vault"
}
func (c *AuthCommand) Help() string {
helpText := `
Usage: vault auth [options] [auth-information]
Authenticate with Vault using the given token or via any supported
authentication backend.
By default, the -method is assumed to be token. If not supplied via the
command-line, a prompt for input will be shown. If the authentication
information is "-", it will be read from stdin.
The -method option allows alternative authentication methods to be used,
such as userpass, GitHub, or TLS certificates. For these, additional
values as "key=value" pairs may be required. For example, to authenticate
to the userpass auth backend:
$ vault auth -method=userpass username=my-username
Use "-method-help" to get help for a specific method.
If an auth backend is enabled at a different path, the "-method" flag
should still point to the canonical name, and the "-path" flag should be
used. If a GitHub auth backend was mounted as "github-private", one would
authenticate to this backend via:
$ vault auth -method=github -path=github-private
The value of the "-path" flag is supplied to auth providers as the "mount"
option in the payload to specify the mount point.
General Options:
` + meta.GeneralOptionsUsage() + `
Auth Options:
-method=name Outputs help for the authentication method with the given
name for the remote server. If this authentication method
is not available, exit with code 1.
-method-help If set, the help for the selected method will be shown.
-methods List the available auth methods.
-no-verify Do not verify the token after creation; avoids a use count
decrement.
-no-store Do not store the token after creation; it will only be
displayed in the command output.
-token-only Output only the token to stdout. This implies -no-verify
and -no-store.
-path The path at which the auth backend is enabled. If an auth
backend is mounted at multiple paths, this option can be
used to authenticate against specific paths.
`
return strings.TrimSpace(helpText)
}
// tokenAuthHandler handles retrieving the token from the command-line.
type tokenAuthHandler struct {
Token string
}
func (h *tokenAuthHandler) Auth(*api.Client, map[string]string) (string, error) {
token := h.Token
if token == "" {
var err error
// No arguments given, read the token from user input
fmt.Printf("Token (will be hidden): ")
token, err = password.Read(os.Stdin)
fmt.Printf("\n")
if err != nil {
return "", fmt.Errorf(
"Error attempting to ask for token. The raw error message\n"+
"is shown below, but the most common reason for this error is\n"+
"that you attempted to pipe a value into auth. If you want to\n"+
"pipe the token, please pass '-' as the token argument.\n\n"+
"Raw error: %s", err)
}
}
if token == "" {
return "", fmt.Errorf(
"A token must be passed to auth. Please view the help\n" +
"for more information.")
}
return token, nil
}
func (h *tokenAuthHandler) Help() string {
help := `
No method selected with the "-method" flag, so the "auth" command assumes
you'll be using raw token authentication. For this, specify the token to
authenticate as the parameter to "vault auth". Example:
vault auth 123456
The token used to authenticate must come from some other source. A root
token is created when Vault is first initialized. After that, subsequent
tokens are created via the API or command line interface (with the
"token"-prefixed commands).
`
return strings.TrimSpace(help)
}