-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc_backup_handlers.go
203 lines (156 loc) · 5.25 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"io"
"strings"
"github.com/Sirupsen/logrus"
"github.com/TykTechnologies/tyk/config"
"github.com/TykTechnologies/tyk/storage"
"github.com/TykTechnologies/tyk/user"
)
const RPCKeyPrefix = "rpc:"
const BackupApiKeyBase = "node-definition-backup:"
const BackupPolicyKeyBase = "node-policy-backup:"
func getTagListAsString() string {
tagList := ""
if tags := config.Global().DBAppConfOptions.Tags; len(tags) > 0 {
tagList = strings.Join(tags, "-")
}
return tagList
}
func LoadDefinitionsFromRPCBackup() ([]*APISpec, error) {
tagList := getTagListAsString()
checkKey := BackupApiKeyBase + tagList
store := storage.RedisCluster{KeyPrefix: RPCKeyPrefix}
connected := store.Connect()
log.Info("[RPC] --> Loading API definitions from backup")
if !connected {
return nil, errors.New("[RPC] --> RPC Backup recovery failed: redis connection failed")
}
secret := rightPad2Len(config.Global().Secret, "=", 32)
cryptoText, err := store.GetKey(checkKey)
apiListAsString := decrypt([]byte(secret), cryptoText)
if err != nil {
return nil, errors.New("[RPC] --> Failed to get node backup (" + checkKey + "): " + err.Error())
}
a := APIDefinitionLoader{}
return a.processRPCDefinitions(apiListAsString)
}
func saveRPCDefinitionsBackup(list string) error {
if !json.Valid([]byte(list)) {
return errors.New("--> RPC Backup save failure: wrong format, skipping.")
}
log.Info("Storing RPC Definitions backup")
tagList := getTagListAsString()
log.Info("--> Connecting to DB")
store := storage.RedisCluster{KeyPrefix: RPCKeyPrefix}
connected := store.Connect()
log.Info("--> Connected to DB")
if !connected {
return errors.New("--> RPC Backup save failed: redis connection failed")
}
secret := rightPad2Len(config.Global().Secret, "=", 32)
cryptoText := encrypt([]byte(secret), list)
err := store.SetKey(BackupApiKeyBase+tagList, cryptoText, -1)
if err != nil {
return errors.New("Failed to store node backup: " + err.Error())
}
return nil
}
func LoadPoliciesFromRPCBackup() (map[string]user.Policy, error) {
tagList := getTagListAsString()
checkKey := BackupPolicyKeyBase + tagList
store := storage.RedisCluster{KeyPrefix: RPCKeyPrefix}
connected := store.Connect()
log.Info("[RPC] Loading Policies from backup")
if !connected {
return nil, errors.New("[RPC] --> RPC Policy Backup recovery failed: redis connection failed")
}
secret := rightPad2Len(config.Global().Secret, "=", 32)
cryptoText, err := store.GetKey(checkKey)
listAsString := decrypt([]byte(secret), cryptoText)
if err != nil {
return nil, errors.New("[RPC] --> Failed to get node policy backup (" + checkKey + "): " + err.Error())
}
if policies, err := parsePoliciesFromRPC(listAsString); err != nil {
log.WithFields(logrus.Fields{
"prefix": "policy",
}).Error("Failed decode: ", err)
return nil, err
} else {
return policies, nil
}
}
func saveRPCPoliciesBackup(list string) error {
if !json.Valid([]byte(list)) {
return errors.New("--> RPC Backup save failure: wrong format, skipping.")
}
log.Info("Storing RPC policies backup")
tagList := getTagListAsString()
log.Info("--> Connecting to DB")
store := storage.RedisCluster{KeyPrefix: RPCKeyPrefix}
connected := store.Connect()
log.Info("--> Connected to DB")
if !connected {
return errors.New("--> RPC Backup save failed: redis connection failed")
}
secret := rightPad2Len(config.Global().Secret, "=", 32)
cryptoText := encrypt([]byte(secret), list)
err := store.SetKey(BackupPolicyKeyBase+tagList, cryptoText, -1)
if err != nil {
return errors.New("Failed to store node backup: " + err.Error())
}
return nil
}
// encrypt string to base64 crypto using AES
func encrypt(key []byte, text string) string {
plaintext := []byte(text)
block, err := aes.NewCipher(key)
if err != nil {
log.Error(err)
return ""
}
// 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 {
log.Error(err)
return ""
}
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 {
log.Error(err)
return ""
}
// 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 {
log.Error("ciphertext too short")
return ""
}
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 string(ciphertext)
}
func rightPad2Len(s, padStr string, overallLen int) string {
padCountInt := 1 + (overallLen-len(padStr))/len(padStr)
retStr := s + strings.Repeat(padStr, padCountInt)
return retStr[:overallLen]
}