forked from hashicorp/vault-plugin-auth-jwt
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcli.go
222 lines (180 loc) · 5.17 KB
/
cli.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
package jwtauth
import (
"errors"
"fmt"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"regexp"
"runtime"
"strings"
"github.com/hashicorp/vault/api"
)
const defaultMount = "oidc"
const defaultPort = "8250"
const defaultCallbackHost = "localhost"
var errorRegex = regexp.MustCompile(`(?s)Errors:.*\* *(.*)`)
type CLIHandler struct{}
type loginResp struct {
secret *api.Secret
err error
}
func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, error) {
// handle ctrl-c while waiting for the callback
sigintCh := make(chan os.Signal, 1)
signal.Notify(sigintCh, os.Interrupt)
defer signal.Stop(sigintCh)
doneCh := make(chan loginResp)
mount, ok := m["mount"]
if !ok {
mount = defaultMount
}
port, ok := m["port"]
if !ok {
port = defaultPort
}
callbackHost, ok := m["callbackhost"]
if !ok {
callbackHost = defaultCallbackHost
}
role := m["role"]
authURL, err := fetchAuthURL(c, role, mount, port, callbackHost)
if err != nil {
return nil, err
}
// Set up callback handler
http.HandleFunc("/oidc/callback", func(w http.ResponseWriter, req *http.Request) {
var response string
query := req.URL.Query()
code := query.Get("code")
state := query.Get("state")
data := map[string][]string{
"code": {code},
"state": {state},
}
secret, err := c.Logical().ReadWithData(fmt.Sprintf("auth/%s/oidc/callback", mount), data)
if err != nil {
summary, detail := parseError(err)
response = errorHTML(summary, detail)
} else {
response = successHTML
}
w.Write([]byte(response))
doneCh <- loginResp{secret, err}
})
listener, err := net.Listen("tcp", ":"+port)
if err != nil {
return nil, err
}
defer listener.Close()
// Open the default browser to the callback URL.
fmt.Fprintf(os.Stderr, "Complete the login via your OIDC provider. Launching browser to:\n\n %s\n\n\n", authURL)
if err := openURL(authURL); err != nil {
fmt.Fprintf(os.Stderr, "Error attempting to automatically open browser: '%s'.\nPlease visit the authorization URL manually.", err)
}
// Start local server
go func() {
err := http.Serve(listener, nil)
if err != nil && err != http.ErrServerClosed {
doneCh <- loginResp{nil, err}
}
}()
// Wait for either the callback to finish or SIGINT to be received
select {
case s := <-doneCh:
return s.secret, s.err
case <-sigintCh:
return nil, errors.New("Interrupted")
}
}
func fetchAuthURL(c *api.Client, role, mount, port string, callbackHost string) (string, error) {
var authURL string
data := map[string]interface{}{
"role": role,
"redirect_uri": fmt.Sprintf("http://%s:%s/oidc/callback", callbackHost, port),
}
secret, err := c.Logical().Write(fmt.Sprintf("auth/%s/oidc/auth_url", mount), data)
if err != nil {
return "", err
}
if secret != nil {
authURL = secret.Data["auth_url"].(string)
}
if authURL == "" {
return "", errors.New(fmt.Sprintf("Unable to authorize role %q. Check Vault logs for more information.", role))
}
return authURL, nil
}
// openURL opens the specified URL in the default browser of the user.
// Source: https://stackoverflow.com/a/39324149/453290
func openURL(url string) error {
var cmd string
var args []string
switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start"}
url = strings.Replace(url, "&", "^&", -1)
case "darwin":
cmd = "open"
default: // "linux", "freebsd", "openbsd", "netbsd"
cmd = "xdg-open"
}
args = append(args, url)
return exec.Command(cmd, args...).Start()
}
// parseError converts error from the API into summary and detailed portions.
// This is used to present a nicer UI by splitting up *known* prefix sentences
// from the rest of the text. e.g.
//
// "No response from provider. Gateway timeout from upstream proxy."
//
// becomes:
//
// "No response from provider.", "Gateway timeout from upstream proxy."
func parseError(err error) (string, string) {
headers := []string{errNoResponse, errLoginFailed, errTokenVerification}
summary := "Login error"
detail := ""
errorParts := errorRegex.FindStringSubmatch(err.Error())
switch len(errorParts) {
case 0:
summary = ""
case 1:
detail = errorParts[0]
case 2:
for _, h := range headers {
if strings.HasPrefix(errorParts[1], h) {
summary = h
detail = strings.TrimSpace(errorParts[1][len(h):])
break
}
}
if detail == "" {
detail = errorParts[1]
}
}
return summary, detail
}
// Help method for OIDC cli
func (h *CLIHandler) Help() string {
help := `
Usage: vault login -method=oidc [CONFIG K=V...]
The OIDC auth method allows users to authenticate using an OIDC provider.
The provider must be configured as part of a role by the operator.
Authenticate using role "engineering":
$ vault login -method=oidc role=engineering
Complete the login via your OIDC provider. Launching browser to:
https://accounts.google.com/o/oauth2/v2/...
The default browser will be opened for the user to complete the login. Alternatively,
the user may visit the provided URL directly.
Configuration:
role=<string>
Vault role of type "OIDC" to use for authentication.
port=<string>
Optional localhost port to use for OIDC callback (default: 8250).
`
return strings.TrimSpace(help)
}