-
Notifications
You must be signed in to change notification settings - Fork 163
/
cache.go
309 lines (258 loc) · 9.77 KB
/
cache.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
package cache
import (
"context"
"crypto/sha1"
b64 "encoding/base64"
"fmt"
"hash"
"math/rand"
"strings"
"time"
goredis "github.com/go-redis/redis/v8"
bes "github.com/iegomez/mosquitto-go-auth/backends"
goCache "github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
)
// redisCache stores necessary values for Redis cache
type redisStore struct {
authExpiration time.Duration
aclExpiration time.Duration
authJitter time.Duration
aclJitter time.Duration
refreshExpiration bool
client bes.RedisClient
h hash.Hash
}
type goStore struct {
authExpiration time.Duration
aclExpiration time.Duration
authJitter time.Duration
aclJitter time.Duration
refreshExpiration bool
client *goCache.Cache
h hash.Hash
}
const (
defaultExpiration = 30
)
type Store interface {
SetAuthRecord(ctx context.Context, username, password, granted string) error
CheckAuthRecord(ctx context.Context, username, password string) (bool, bool)
SetACLRecord(ctx context.Context, username, topic, clientid string, acc int, granted string) error
CheckACLRecord(ctx context.Context, username, topic, clientid string, acc int) (bool, bool)
Connect(ctx context.Context, reset bool) bool
Close()
}
// NewGoStore initializes a cache using go-cache as the store.
func NewGoStore(authExpiration, aclExpiration, authJitter, aclJitter time.Duration, refreshExpiration bool) *goStore {
// TODO: support hydrating the cache to retain previous values.
return &goStore{
authExpiration: authExpiration,
aclExpiration: aclExpiration,
authJitter: authJitter,
aclJitter: aclJitter,
refreshExpiration: refreshExpiration,
client: goCache.New(time.Second*defaultExpiration, time.Second*(defaultExpiration*2)),
h: sha1.New(),
}
}
// NewSingleRedisStore initializes a cache using a single Redis instance as the store.
func NewSingleRedisStore(host, port, password string, db int, authExpiration, aclExpiration, authJitter, aclJitter time.Duration, refreshExpiration bool) *redisStore {
addr := fmt.Sprintf("%s:%s", host, port)
redisClient := goredis.NewClient(&goredis.Options{
Addr: addr,
Password: password, // no password set
DB: db, // use default db
})
//If cache is on, try to start redis.
return &redisStore{
authExpiration: authExpiration,
aclExpiration: aclExpiration,
authJitter: authJitter,
aclJitter: aclJitter,
refreshExpiration: refreshExpiration,
client: bes.SingleRedisClient{redisClient},
h: sha1.New(),
}
}
// NewSingleRedisStore initializes a cache using a Redis Cluster as the store.
func NewRedisClusterStore(password string, addresses []string, authExpiration, aclExpiration, authJitter, aclJitter time.Duration, refreshExpiration bool) *redisStore {
clusterClient := goredis.NewClusterClient(
&goredis.ClusterOptions{
Addrs: addresses,
Password: password,
})
return &redisStore{
authExpiration: authExpiration,
aclExpiration: aclExpiration,
authJitter: authJitter,
aclJitter: aclJitter,
refreshExpiration: refreshExpiration,
client: clusterClient,
h: sha1.New(),
}
}
func toAuthRecord(username, password string, h hash.Hash) string {
sum := h.Sum([]byte(fmt.Sprintf("auth-%s-%s", username, password)))
log.Debugf("to auth record: %v\n", sum)
return b64.StdEncoding.EncodeToString(sum)
}
func toACLRecord(username, topic, clientid string, acc int, h hash.Hash) string {
sum := h.Sum([]byte(fmt.Sprintf("acl-%s-%s-%s-%d", username, topic, clientid, acc)))
log.Debugf("to auth record: %v\n", sum)
return b64.StdEncoding.EncodeToString(sum)
}
// Checks if an error was caused by a moved record in a Redis Cluster.
func isMovedError(err error) bool {
s := err.Error()
if strings.HasPrefix(s, "MOVED ") || strings.HasPrefix(s, "ASK ") {
return true
}
return false
}
// Return an expiration duration with a jitter added, i.e the actual expiration is in the range [expiration - jitter, expiration + jitter].
// If no expiration was set or jitter > expiration, then any negative value will yield 0 instead.
func expirationWithJitter(expiration, jitter time.Duration) time.Duration {
if jitter == 0 {
return expiration
}
result := expiration + time.Duration(rand.Int63n(int64(jitter)*2)-int64(jitter))
if result < 0 {
return 0
}
return result
}
// Connect flushes the cache if reset is set.
func (s *goStore) Connect(ctx context.Context, reset bool) bool {
log.Infoln("started go-cache")
if reset {
s.client.Flush()
log.Infoln("flushed go-cache")
}
return true
}
// Connect pings Redis and flushes the cache if reset is set.
func (s *redisStore) Connect(ctx context.Context, reset bool) bool {
_, err := s.client.Ping(ctx).Result()
if err != nil {
log.Errorf("couldn't start redis. error: %s", err)
return false
} else {
log.Infoln("started redis cache")
//Check if cache must be reset
if reset {
s.client.FlushDB(ctx)
log.Infoln("flushed redis cache")
}
}
return true
}
func (s *goStore) Close() {
//TODO: support serializing cache for re hydration.
}
func (s *redisStore) Close() {
s.client.Close()
}
// CheckAuthRecord checks if the username/password pair is present in the cache. Return if it's present and, if so, if it was granted privileges
func (s *goStore) CheckAuthRecord(ctx context.Context, username, password string) (bool, bool) {
record := toAuthRecord(username, password, s.h)
return s.checkRecord(ctx, record, expirationWithJitter(s.authExpiration, s.authJitter))
}
//CheckAclCache checks if the username/topic/clientid/acc mix is present in the cache. Return if it's present and, if so, if it was granted privileges.
func (s *goStore) CheckACLRecord(ctx context.Context, username, topic, clientid string, acc int) (bool, bool) {
record := toACLRecord(username, topic, clientid, acc, s.h)
return s.checkRecord(ctx, record, expirationWithJitter(s.aclExpiration, s.aclJitter))
}
func (s *goStore) checkRecord(ctx context.Context, record string, expirationTime time.Duration) (bool, bool) {
granted := false
v, present := s.client.Get(record)
if present {
value, ok := v.(string)
if ok && value == "true" {
granted = true
}
if s.refreshExpiration {
s.client.Set(record, value, expirationTime)
}
}
return present, granted
}
// CheckAuthRecord checks if the username/password pair is present in the cache. Return if it's present and, if so, if it was granted privileges
func (s *redisStore) CheckAuthRecord(ctx context.Context, username, password string) (bool, bool) {
record := toAuthRecord(username, password, s.h)
return s.checkRecord(ctx, record, s.authExpiration)
}
//CheckAclCache checks if the username/topic/clientid/acc mix is present in the cache. Return if it's present and, if so, if it was granted privileges.
func (s *redisStore) CheckACLRecord(ctx context.Context, username, topic, clientid string, acc int) (bool, bool) {
record := toACLRecord(username, topic, clientid, acc, s.h)
return s.checkRecord(ctx, record, s.aclExpiration)
}
func (s *redisStore) checkRecord(ctx context.Context, record string, expirationTime time.Duration) (bool, bool) {
present, granted, err := s.getAndRefresh(ctx, record, expirationTime)
if err == nil {
return present, granted
}
if isMovedError(err) {
s.client.ReloadState(ctx)
//Retry once.
present, granted, err = s.getAndRefresh(ctx, record, expirationTime)
}
if err != nil {
log.Debugf("set cache error: %s", err)
}
return present, granted
}
func (s *redisStore) getAndRefresh(ctx context.Context, record string, expirationTime time.Duration) (bool, bool, error) {
val, err := s.client.Get(ctx, record).Result()
if err != nil {
return false, false, err
}
if s.refreshExpiration {
_, err = s.client.Expire(ctx, record, expirationTime).Result()
if err != nil {
return false, false, err
}
}
if val == "true" {
return true, true, nil
}
return true, false, nil
}
// SetAuthRecord sets a pair, granted option and expiration time.
func (s *goStore) SetAuthRecord(ctx context.Context, username, password string, granted string) error {
record := toAuthRecord(username, password, s.h)
s.client.Set(record, granted, expirationWithJitter(s.authExpiration, s.authJitter))
return nil
}
//SetAclCache sets a mix, granted option and expiration time.
func (s *goStore) SetACLRecord(ctx context.Context, username, topic, clientid string, acc int, granted string) error {
record := toACLRecord(username, topic, clientid, acc, s.h)
s.client.Set(record, granted, expirationWithJitter(s.aclExpiration, s.aclJitter))
return nil
}
// SetAuthRecord sets a pair, granted option and expiration time.
func (s *redisStore) SetAuthRecord(ctx context.Context, username, password string, granted string) error {
record := toAuthRecord(username, password, s.h)
return s.setRecord(ctx, record, granted, expirationWithJitter(s.authExpiration, s.authJitter))
}
//SetAclCache sets a mix, granted option and expiration time.
func (s *redisStore) SetACLRecord(ctx context.Context, username, topic, clientid string, acc int, granted string) error {
record := toACLRecord(username, topic, clientid, acc, s.h)
return s.setRecord(ctx, record, granted, expirationWithJitter(s.aclExpiration, s.aclJitter))
}
func (s *redisStore) setRecord(ctx context.Context, record, granted string, expirationTime time.Duration) error {
err := s.set(ctx, record, granted, expirationTime)
if err == nil {
return nil
}
// If record was moved, reload and retry.
if isMovedError(err) {
s.client.ReloadState(ctx)
//Retry once.
err = s.set(ctx, record, granted, expirationTime)
}
return err
}
func (s *redisStore) set(ctx context.Context, record string, granted string, expirationTime time.Duration) error {
return s.client.Set(ctx, record, granted, expirationTime).Err()
}