forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpc_backup_handlers.go
183 lines (141 loc) · 4.49 KB
/
rpc_backup_handlers.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
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"github.com/Sirupsen/logrus"
"github.com/gorilla/mux"
"io"
"net/http"
"strings"
)
const RPCKeyPrefix string = "rpc:"
const BackupKeyBase string = "node-definition-backup:"
func getTagListAsString() string {
tagList := ""
if len(config.DBAppConfOptions.Tags) > 0 {
tagList = strings.Join(config.DBAppConfOptions.Tags, "-")
}
return tagList
}
func SaveRPCDefinitionsBackup(thisList string) {
log.Info("Storing RPC backup")
tagList := getTagListAsString()
log.Info("--> Connecting to DB")
thisStore := &RedisClusterStorageManager{KeyPrefix: RPCKeyPrefix, HashKeys: false}
connected := thisStore.Connect()
log.Info("--> Connected to DB")
if !connected {
log.Error("--> RPC Backup save failed: redis connection failed")
return
}
secret := rightPad2Len(config.Secret, "=", 32)
cryptoText := encrypt([]byte(secret), thisList)
rErr := thisStore.SetKey(BackupKeyBase+tagList, cryptoText, -1)
if rErr != nil {
log.Error("Failed to store node backup: ", rErr)
}
}
func LoadDefinitionsFromRPCBackup() *[]*APISpec {
tagList := getTagListAsString()
checkKey := BackupKeyBase + tagList
thisStore := &RedisClusterStorageManager{KeyPrefix: RPCKeyPrefix, HashKeys: false}
connected := thisStore.Connect()
log.Info("[RPC] --> Connected to DB")
if !connected {
log.Error("[RPC] --> RPC Backup recovery failed: redis connection failed")
return nil
}
secret := rightPad2Len(config.Secret, "=", 32)
cryptoText, rErr := thisStore.GetKey(checkKey)
apiListAsString := decrypt([]byte(secret), cryptoText)
if rErr != nil {
log.Error("[RPC] --> Failed to get node backup (", checkKey, "): ", rErr)
return nil
}
a := APIDefinitionLoader{}
return a.processRPCDefinitions(apiListAsString)
}
func doLoadWithBackup(specs *[]*APISpec) {
log.Warning("[RPC Backup] --> Load Policies too!")
if len(*specs) == 0 {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Warning("No API Definitions found, not loading backup")
return
}
// Reset the JSVM
GlobalEventsJSVM.Init(config.TykJSPath)
log.Warning("[RPC Backup] --> Initialised JSVM")
newRouter := mux.NewRouter()
mainRouter = newRouter
var newMuxes *mux.Router
if getHostName() != "" {
newMuxes = newRouter.Host(getHostName()).Subrouter()
} else {
newMuxes = newRouter
}
log.Warning("[RPC Backup] --> Set up routers")
log.Warning("[RPC Backup] --> Loading endpoints")
loadAPIEndpoints(newMuxes)
log.Warning("[RPC Backup] --> Loading APIs")
loadApps(specs, newMuxes)
log.Warning("[RPC Backup] --> API Load Done")
newServeMux := http.NewServeMux()
newServeMux.Handle("/", mainRouter)
http.DefaultServeMux = newServeMux
log.Warning("[RPC Backup] --> Replaced muxer")
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("API backup load complete")
log.Warning("[RPC Backup] --> Ready to listen")
RPC_EmergencyModeLoaded = true
listen()
}
// encrypt string to base64 crypto using AES
func encrypt(key []byte, text string) string {
// key := []byte(keyText)
plaintext := []byte(text)
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
// The IV needs to be unique, but not secure. Therefore it's common to
// include it at the beginning of the ciphertext.
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
// convert to base64
return base64.URLEncoding.EncodeToString(ciphertext)
}
// decrypt from base64 to decrypted string
func decrypt(key []byte, cryptoText string) string {
ciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
// The IV needs to be unique, but not secure. Therefore it's common to
// include it at the beginning of the ciphertext.
if len(ciphertext) < aes.BlockSize {
panic("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
// XORKeyStream can work in-place if the two arguments are the same.
stream.XORKeyStream(ciphertext, ciphertext)
return fmt.Sprintf("%s", ciphertext)
}
func rightPad2Len(s string, padStr string, overallLen int) string {
var padCountInt int
padCountInt = 1 + ((overallLen - len(padStr)) / len(padStr))
var retStr = s + strings.Repeat(padStr, padCountInt)
return retStr[:overallLen]
}