forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
576 lines (473 loc) · 13.7 KB
/
api.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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
package main
import (
"encoding/base64"
"encoding/json"
"fmt"
"github.com/RangelReale/osin"
"github.com/Sirupsen/logrus"
"github.com/nu7hatch/gouuid"
"net/http"
"strings"
)
// APIModifyKeySuccess represents when a Key modification was successful
type APIModifyKeySuccess struct {
Key string `json:"key"`
Status string `json:"status"`
Action string `json:"action"`
}
// APIErrorMessage is an object that defines when a generic error occurred
type APIErrorMessage struct {
Status string `json:"status"`
Error string `json:"error"`
}
func createError(errorMsg string) []byte {
errorObj := APIErrorMessage{"error", errorMsg}
responseMsg, err := json.Marshal(&errorObj)
if err != nil {
log.Error("Couldn't marshal error stats")
log.Error(err)
}
return responseMsg
}
func handleAddOrUpdate(keyName string, r *http.Request) ([]byte, int) {
success := true
decoder := json.NewDecoder(r.Body)
var responseMessage []byte
var newSession SessionState
err := decoder.Decode(&newSession)
code := 200
if err != nil {
log.Error("Couldn't decode new session object")
log.Error(err)
code = 400
success = false
responseMessage = createError("Request malformed")
} else {
// Update our session object (create it)
if newSession.BasicAuthData.Password != "" {
// If we are using a basic auth user, then we need to make the keyname explicit against the OrgId in order to differentiate it
// Only if it's NEW
if r.Method == "POST" {
keyName = newSession.OrgID + keyName
}
}
authManager.UpdateSession(keyName, newSession)
log.WithFields(logrus.Fields{
"key": keyName,
}).Info("New key added or updated.")
}
var action string
if r.Method == "POST" {
action = "added"
} else {
action = "modified"
}
if success {
response := APIModifyKeySuccess{
keyName,
"ok",
action}
responseMessage, err = json.Marshal(&response)
if err != nil {
log.Error("Could not create response message")
log.Error(err)
code = 500
responseMessage = []byte(E_SYSTEM_ERROR)
}
}
return responseMessage, code
}
func handleGetDetail(sessionKey string) ([]byte, int) {
success := true
var responseMessage []byte
var err error
code := 200
thisSession, ok := authManager.GetSessionDetail(sessionKey)
if !ok {
success = false
} else {
responseMessage, err = json.Marshal(&thisSession)
if err != nil {
log.Error("Marshalling failed")
log.Error(err)
success = false
}
}
if !success {
notFound := APIStatusMessage{"error", "Key not found"}
responseMessage, _ = json.Marshal(¬Found)
code = 404
log.WithFields(logrus.Fields{
"key": sessionKey,
}).Info("Attempted key retrieval - failure.")
} else {
log.WithFields(logrus.Fields{
"key": sessionKey,
}).Info("Attempted key retrieval - success.")
}
return responseMessage, code
}
// APIAllKeys represents a list of keys in the memory store
type APIAllKeys struct {
APIKeys []string `json:"keys"`
}
func handleGetAllKeys(filter string) ([]byte, int) {
success := true
var responseMessage []byte
code := 200
var err error
sessions := authManager.GetSessions(filter)
sessionsObj := APIAllKeys{sessions}
responseMessage, err = json.Marshal(&sessionsObj)
if err != nil {
log.Error("Marshalling failed")
log.Error(err)
success = false
code = 500
}
if success {
return responseMessage, code
}
log.Info("Attempted keys retrieval - success.")
return []byte(E_SYSTEM_ERROR), code
}
// APIStatusMessage represents an API status message
type APIStatusMessage struct {
Status string `json:"status"`
Message string `json:"message"`
}
func handleDeleteKey(keyName string) ([]byte, int) {
var responseMessage []byte
var err error
authManager.Store.DeleteKey(keyName)
code := 200
statusObj := APIModifyKeySuccess{keyName, "ok", "deleted"}
responseMessage, err = json.Marshal(&statusObj)
if err != nil {
log.Error("Marshalling failed")
log.Error(err)
return []byte(E_SYSTEM_ERROR), 500
}
log.WithFields(logrus.Fields{
"key": keyName,
}).Info("Attempted key deletion - success.")
return responseMessage, code
}
func handleURLReload() ([]byte, int) {
var responseMessage []byte
var err error
ReloadURLStructure()
code := 200
statusObj := APIErrorMessage{"ok", ""}
responseMessage, err = json.Marshal(&statusObj)
if err != nil {
log.Error("Marshalling failed")
log.Error(err)
return []byte(E_SYSTEM_ERROR), 500
}
log.WithFields(logrus.Fields{}).Info("Reloaded URL Structure - Success")
return responseMessage, code
}
func keyHandler(w http.ResponseWriter, r *http.Request) {
keyName := r.URL.Path[len("/tyk/keys/"):]
filter := r.FormValue("filter")
var responseMessage []byte
var code int
if r.Method == "POST" || r.Method == "PUT" {
responseMessage, code = handleAddOrUpdate(keyName, r)
} else if r.Method == "GET" {
if keyName != "" {
// Return single key detail
responseMessage, code = handleGetDetail(keyName)
} else {
// Return list of keys
responseMessage, code = handleGetAllKeys(filter)
}
} else if r.Method == "DELETE" {
// Remove a key
responseMessage, code = handleDeleteKey(keyName)
} else {
// Return Not supported message (and code)
code = 405
responseMessage = createError("Method not supported")
}
w.WriteHeader(code)
fmt.Fprintf(w, string(responseMessage))
}
func resetHandler(w http.ResponseWriter, r *http.Request) {
var responseMessage []byte
var code int
if r.Method == "GET" {
responseMessage, code = handleURLReload()
} else {
// Return Not supported message (and code)
code = 405
responseMessage = createError("Method not supported")
}
w.WriteHeader(code)
fmt.Fprintf(w, string(responseMessage))
}
func expandKey(orgID, key string) string {
if orgID == "" {
return fmt.Sprintf("%s", key)
}
return fmt.Sprintf("%s%s", orgID, key)
}
func extractKey(orgID, key string) string {
replacementStr := fmt.Sprintf("%s", orgID)
replaced := strings.Replace(key, replacementStr, "", 1)
return replaced
}
func createKeyHandler(w http.ResponseWriter, r *http.Request) {
var responseMessage []byte
code := 200
var responseObj = APIModifyKeySuccess{}
if r.Method == "POST" {
decoder := json.NewDecoder(r.Body)
var newSession SessionState
err := decoder.Decode(&newSession)
if err != nil {
responseMessage = []byte(E_SYSTEM_ERROR)
code = 500
log.Error("Couldn't decode body")
log.Error(err)
} else {
newKey := authManager.GenerateAuthKey(newSession.OrgID)
// If we have enabled HMAC checking for keys, we need to generate a secret for the client to use
if newSession.HMACEnabled {
newSession.HmacSecret = authManager.GenerateHMACSecret()
}
authManager.UpdateSession(newKey, newSession)
responseObj.Action = "create"
responseObj.Key = newKey
responseObj.Status = "ok"
responseMessage, err = json.Marshal(&responseObj)
if err != nil {
log.Error("Marshalling failed")
log.Error(err)
responseMessage = []byte(E_SYSTEM_ERROR)
code = 500
} else {
log.WithFields(logrus.Fields{
"key": newKey,
}).Info("Generated new key - success.")
}
}
} else {
code = 405
responseMessage = createError("Method not supported")
}
w.WriteHeader(code)
fmt.Fprintf(w, string(responseMessage))
}
// NewClientRequest is an outward facing JSON object translated from osin OAuthClients
type NewClientRequest struct {
ClientRedirectURI string `json:"redirect_uri"`
APIID string `json:"api_id"`
}
func createOauthClientStorageID(APIID string, clientID string) string {
storageID := OAUTH_PREFIX + APIID + "." + CLIENT_PREFIX + clientID
return storageID
}
func createOauthClient(w http.ResponseWriter, r *http.Request) {
var responseMessage []byte
code := 200
if r.Method == "POST" {
decoder := json.NewDecoder(r.Body)
var newOauthClient NewClientRequest
err := decoder.Decode(&newOauthClient)
if err != nil {
responseMessage = []byte(E_SYSTEM_ERROR)
code = 500
log.Error("Couldn't decode body")
log.Error(err)
}
u5, err := uuid.NewV4()
cleanSting := strings.Replace(u5.String(), "-", "", -1)
u5Secret, err := uuid.NewV4()
secret := base64.StdEncoding.EncodeToString([]byte(u5Secret.String()))
newClient := osin.DefaultClient{
Id: cleanSting,
RedirectUri: newOauthClient.ClientRedirectURI,
Secret: secret,
}
storageID := createOauthClientStorageID(newOauthClient.APIID, newClient.GetId())
storeErr := genericOsinStorage.SetClient(storageID, &newClient, true)
if storeErr != nil {
log.Error("Failed to save new client data: ", storeErr)
responseMessage = createError("Failure in storing client data.")
}
reportableClientData := OAuthClient{
ClientID: newClient.GetId(),
ClientSecret: newClient.GetSecret(),
ClientRedirectURI: newClient.GetRedirectUri(),
}
responseMessage, err = json.Marshal(&reportableClientData)
if err != nil {
log.Error("Marshalling failed")
log.Error(err)
responseMessage = []byte(E_SYSTEM_ERROR)
code = 500
} else {
log.WithFields(logrus.Fields{
"key": newClient.GetId(),
}).Info("New OAuth Client registered successfully.")
}
} else {
code = 405
responseMessage = createError("Method not supported")
}
w.WriteHeader(code)
fmt.Fprintf(w, string(responseMessage))
}
func oAuthClientHandler(w http.ResponseWriter, r *http.Request) {
keyCombined := r.URL.Path[len("/tyk/oauth/clients/"):]
var responseMessage []byte
var code int
keyName := ""
apiID := ""
parts := strings.Split(keyCombined, "/")
if len(parts) == 2 {
keyName = parts[1]
apiID = parts[0]
} else if len(parts) == 1 {
apiID = parts[0]
} else {
// Return Not supported message (and code)
code = 405
responseMessage = createError("Method not supported")
w.WriteHeader(code)
fmt.Fprintf(w, string(responseMessage))
return
}
if r.Method == "GET" {
if keyName != "" {
// Return single client detail
responseMessage, code = getOauthClientDetails(keyName, apiID)
} else {
// Return list of keys
responseMessage, code = getOauthClients(apiID)
}
} else if r.Method == "DELETE" {
// Remove a key
responseMessage, code = handleDeleteOAuthClient(keyName, apiID)
} else {
// Return Not supported message (and code)
code = 405
responseMessage = createError("Method not supported")
}
w.WriteHeader(code)
fmt.Fprintf(w, string(responseMessage))
}
// Get client details
func getOauthClientDetails(keyName string, APIID string) ([]byte, int) {
success := true
var responseMessage []byte
var err error
code := 200
storageID := createOauthClientStorageID(APIID, keyName)
thisClientData, getClientErr := genericOsinStorage.GetClientNoPrefix(storageID)
if getClientErr != nil {
success = false
} else {
reportableClientData := OAuthClient{
ClientID: thisClientData.GetId(),
ClientSecret: thisClientData.GetSecret(),
ClientRedirectURI: thisClientData.GetRedirectUri(),
}
responseMessage, err = json.Marshal(&reportableClientData)
if err != nil {
log.Error("Marshalling failed")
log.Error(err)
success = false
}
}
if !success {
notFound := APIStatusMessage{"error", "OAuth Client ID not found"}
responseMessage, _ = json.Marshal(¬Found)
code = 404
log.WithFields(logrus.Fields{
"key": keyName,
}).Info("Attempted oauth client retrieval - failure.")
} else {
log.WithFields(logrus.Fields{
"key": keyName,
}).Info("Attempted oauth client retrieval - success.")
}
return responseMessage, code
}
// Delete Client
func handleDeleteOAuthClient(keyName string, APIID string) ([]byte, int) {
var responseMessage []byte
var err error
storageID := createOauthClientStorageID(APIID, keyName)
osinErr := genericOsinStorage.DeleteClient(storageID, true)
code := 200
statusObj := APIModifyKeySuccess{keyName, "ok", "deleted"}
if osinErr != nil {
code = 500
errObj := APIErrorMessage{"error", "Delete failed"}
responseMessage, err = json.Marshal(&errObj)
return responseMessage, code
}
responseMessage, err = json.Marshal(&statusObj)
if err != nil {
log.Error("Marshalling failed")
log.Error(err)
return []byte(E_SYSTEM_ERROR), 500
}
log.WithFields(logrus.Fields{
"key": keyName,
}).Info("Attempted OAuth client deletion - success.")
return responseMessage, code
}
// List Clients
func getOauthClients(APIID string) ([]byte, int) {
success := true
var responseMessage []byte
var err error
code := 200
filterID := OAUTH_PREFIX + APIID + "." + CLIENT_PREFIX
thisClientData, getClientsErr := genericOsinStorage.GetClients(filterID, true)
if getClientsErr != nil {
success = false
} else {
clients := []OAuthClient{}
for _, osinClient := range thisClientData {
reportableClientData := OAuthClient{
ClientID: osinClient.GetId(),
ClientSecret: osinClient.GetSecret(),
ClientRedirectURI: osinClient.GetRedirectUri(),
}
clients = append(clients, reportableClientData)
}
responseMessage, err = json.Marshal(&clients)
if err != nil {
log.Error("Marshalling failed")
log.Error(err)
success = false
}
}
if !success {
notFound := APIStatusMessage{"error", "OAuth slients not found"}
responseMessage, _ = json.Marshal(¬Found)
code = 404
log.WithFields(logrus.Fields{
"API": APIID,
}).Info("Attempted oauth client retrieval - failure.")
} else {
log.WithFields(logrus.Fields{
"API": APIID,
}).Info("Attempted oauth clients retrieval - success.")
}
return responseMessage, code
}
// MakeNewOsinServer creates a generic osinStorage object, used primarily by the API to create and get keys outside of an APISpec context.
// This is not ideal, but is only used in the Tyk API and nowhere else.
func MakeNewOsinServer() *RedisOsinStorageInterface {
log.Info("Creating generic redis OAuth connection")
storageManager := RedisStorageManager{KeyPrefix: ""}
storageManager.Connect()
osinStorage := &RedisOsinStorageInterface{&storageManager}
return osinStorage
}