-
Notifications
You must be signed in to change notification settings - Fork 165
/
jwt_remote.go
308 lines (241 loc) · 6.49 KB
/
jwt_remote.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
package backends
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
h "net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
type remoteJWTChecker struct {
userUri string
superuserUri string
aclUri string
host string
port string
withTLS bool
verifyPeer bool
paramsMode string
responseMode string
options tokenOptions
client *h.Client
}
type Response struct {
Ok bool `json:"ok"`
Error string `json:"error"`
}
func NewRemoteJWTChecker(authOpts map[string]string, options tokenOptions) (jwtChecker, error) {
var checker = &remoteJWTChecker{
withTLS: false,
verifyPeer: false,
responseMode: "status",
paramsMode: "json",
options: options,
}
missingOpts := ""
remoteOk := true
if responseMode, ok := authOpts["jwt_response_mode"]; ok {
if responseMode == "text" || responseMode == "json" {
checker.responseMode = responseMode
}
}
if paramsMode, ok := authOpts["jwt_params_mode"]; ok {
if paramsMode == "form" {
checker.paramsMode = paramsMode
}
}
if userUri, ok := authOpts["jwt_getuser_uri"]; ok {
checker.userUri = userUri
} else {
remoteOk = false
missingOpts += " jwt_getuser_uri"
}
if superuserUri, ok := authOpts["jwt_superuser_uri"]; ok {
checker.superuserUri = superuserUri
}
if aclUri, ok := authOpts["jwt_aclcheck_uri"]; ok {
checker.aclUri = aclUri
} else {
remoteOk = false
missingOpts += " jwt_aclcheck_uri"
}
if hostname, ok := authOpts["jwt_host"]; ok {
checker.host = hostname
} else {
remoteOk = false
missingOpts += " jwt_host"
}
if port, ok := authOpts["jwt_port"]; ok {
checker.port = port
} else {
remoteOk = false
missingOpts += " jwt_port"
}
if withTLS, ok := authOpts["jwt_with_tls"]; ok && withTLS == "true" {
checker.withTLS = true
}
if verifyPeer, ok := authOpts["jwt_verify_peer"]; ok && verifyPeer == "true" {
checker.verifyPeer = true
}
if !remoteOk {
return nil, errors.Errorf("JWT backend error: missing remote options: %s", missingOpts)
}
checker.client = &h.Client{Timeout: 5 * time.Second}
if !checker.verifyPeer {
tr := &h.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
checker.client.Transport = tr
}
return checker, nil
}
func (o *remoteJWTChecker) GetUser(token string) (bool, error) {
var dataMap map[string]interface{}
var urlValues url.Values
if o.options.parseToken {
username, err := getUsernameForToken(o.options, token, o.options.skipUserExpiration)
if err != nil {
log.Printf("jwt remote get user error: %s", err)
return false, err
}
dataMap = map[string]interface{}{
"username": username,
}
urlValues = url.Values{
"username": []string{username},
}
}
return o.jwtRequest(o.host, o.userUri, token, dataMap, urlValues)
}
func (o *remoteJWTChecker) GetSuperuser(token string) (bool, error) {
if o.superuserUri == "" {
return false, nil
}
var dataMap map[string]interface{}
var urlValues = url.Values{}
if o.options.parseToken {
username, err := getUsernameForToken(o.options, token, o.options.skipUserExpiration)
if err != nil {
log.Printf("jwt remote get superuser error: %s", err)
return false, err
}
dataMap = map[string]interface{}{
"username": username,
}
urlValues = url.Values{
"username": []string{username},
}
}
return o.jwtRequest(o.host, o.superuserUri, token, dataMap, urlValues)
}
func (o *remoteJWTChecker) CheckAcl(token, topic, clientid string, acc int32) (bool, error) {
dataMap := map[string]interface{}{
"clientid": clientid,
"topic": topic,
"acc": acc,
}
var urlValues = url.Values{
"clientid": []string{clientid},
"topic": []string{topic},
"acc": []string{strconv.Itoa(int(acc))},
}
if o.options.parseToken {
username, err := getUsernameForToken(o.options, token, o.options.skipACLExpiration)
if err != nil {
log.Printf("jwt remote check acl error: %s", err)
return false, err
}
dataMap["username"] = username
urlValues.Add("username", username)
}
return o.jwtRequest(o.host, o.aclUri, token, dataMap, urlValues)
}
func (o *remoteJWTChecker) Halt() {
// NO-OP
}
func (o *remoteJWTChecker) jwtRequest(host, uri, token string, dataMap map[string]interface{}, urlValues url.Values) (bool, error) {
// Don't do the request if the client is nil.
if o.client == nil {
return false, errors.New("jwt http client not initialized")
}
tlsStr := "http:https://"
if o.withTLS {
tlsStr = "https://"
}
fullURI := fmt.Sprintf("%s%s%s", tlsStr, o.host, uri)
if o.port != "" {
fullURI = fmt.Sprintf("%s%s:%s%s", tlsStr, o.host, o.port, uri)
}
var resp *h.Response
var err error
var req *h.Request
switch o.paramsMode {
case "json":
dataJSON, err := json.Marshal(dataMap)
if err != nil {
log.Errorf("marshal error: %s", err)
return false, err
}
contentReader := bytes.NewReader(dataJSON)
req, err = h.NewRequest("POST", fullURI, contentReader)
if err != nil {
log.Errorf("req error: %s", err)
return false, err
}
req.Header.Set("Content-Type", "application/json")
default:
req, err = h.NewRequest("POST", fullURI, strings.NewReader(urlValues.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Content-Length", strconv.Itoa(len(urlValues.Encode())))
if err != nil {
log.Errorf("req error: %s", err)
return false, err
}
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
resp, err = o.client.Do(req)
if err != nil {
log.Errorf("error: %v", err)
return false, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorf("read error: %s", err)
return false, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
log.Infof("error code: %d", resp.StatusCode)
if resp.StatusCode >= 500 {
err = fmt.Errorf("error code: %d", resp.StatusCode)
}
return false, err
}
if o.responseMode == "text" {
//For test response, we expect "ok" or an error message.
if string(body) != "ok" {
log.Infof("api error: %s", string(body))
return false, nil
}
} else if o.responseMode == "json" {
//For json response, we expect Ok and Error fields.
response := Response{Ok: false, Error: ""}
err = json.Unmarshal(body, &response)
if err != nil {
log.Errorf("unmarshal error: %s", err)
return false, err
}
if !response.Ok {
log.Infof("api error: %s", response.Error)
return false, nil
}
}
log.Debugf("jwt request approved for %s", token)
return true, nil
}