forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
le_helpers.go
120 lines (91 loc) · 2.54 KB
/
le_helpers.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
package main
import (
"rsc.io/letsencrypt"
"encoding/json"
"github.com/TykTechnologies/logrus"
)
const LEKeyPrefix string = "le_ssl:"
func StoreLEState(m *letsencrypt.Manager) {
log.Debug("Storing SSL backup")
log.Debug("[SSL] --> Connecting to DB")
thisStore := &RedisClusterStorageManager{KeyPrefix: LEKeyPrefix, HashKeys: false}
connected := thisStore.Connect()
log.Debug("--> Connected to DB")
if !connected {
log.Error("[SSL] --> SSL Backup save failed: redis connection failed")
return
}
state := m.Marshal()
secret := rightPad2Len(config.Secret, "=", 32)
cryptoText := encrypt([]byte(secret), state)
rErr := thisStore.SetKey("cache", cryptoText, -1)
if rErr != nil {
log.Error("[SSL] --> Failed to store SSL backup: ", rErr)
return
}
}
func GetLEState(m *letsencrypt.Manager) {
checkKey := "cache"
thisStore := &RedisClusterStorageManager{KeyPrefix: LEKeyPrefix, HashKeys: false}
connected := thisStore.Connect()
log.Debug("[SSL] --> Connected to DB")
if !connected {
log.Error("[SSL] --> SSL Backup recovery failed: redis connection failed")
return
}
cryptoText, rErr := thisStore.GetKey(checkKey)
if rErr != nil {
log.Warning("[SSL] --> No SSL backup: ", rErr)
return
}
secret := rightPad2Len(config.Secret, "=", 32)
sslState := decrypt([]byte(secret), cryptoText)
m.Unmarshal(sslState)
}
type LE_ServerInfo struct {
HostName string
ID string
}
func NotifyLEStateChange() {
thisServer := LE_ServerInfo{
HostName: HostDetails.Hostname,
ID: NodeID,
}
asJson, jsErr := json.Marshal(thisServer)
if jsErr != nil {
log.Error("Failed to encode payload: ", jsErr)
return
}
n := Notification{
Command: NoticeGatewayLENotification,
Payload: string(asJson),
}
MainNotifier.Notify(n)
}
func OnLESSLStatusReceivedHandler(payload string) {
thisServerData := LE_ServerInfo{}
jsErr := json.Unmarshal([]byte(payload), &thisServerData)
if jsErr != nil {
log.WithFields(logrus.Fields{
"prefix": "pub-sub",
}).Error("Failed unmarshal server data: ", jsErr)
return
}
log.Debug("Received LE data: ", thisServerData)
// not great
if thisServerData.ID != NodeID {
log.Info("Received Redis LE change notification!")
GetLEState(&LE_MANAGER)
}
log.Info("Received Redis LE change notification from myself, ignoring")
}
func StartPeriodicStateBackup(m *letsencrypt.Manager) {
for range m.Watch() {
// First run will call a cache save that overwrites with null data
if LE_FIRSTRUN {
log.Info("[SSL] State change detected, storing")
StoreLEState(m)
}
LE_FIRSTRUN = true
}
}