-
Notifications
You must be signed in to change notification settings - Fork 162
/
redis.go
366 lines (306 loc) · 8.8 KB
/
redis.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
package backends
import (
"context"
"fmt"
"strconv"
"strings"
"time"
goredis "github.com/go-redis/redis/v8"
. "github.com/iegomez/mosquitto-go-auth/backends/constants"
"github.com/iegomez/mosquitto-go-auth/backends/topics"
"github.com/iegomez/mosquitto-go-auth/hashing"
log "github.com/sirupsen/logrus"
)
type RedisClient interface {
Get(ctx context.Context, key string) *goredis.StringCmd
SMembers(ctx context.Context, key string) *goredis.StringSliceCmd
Ping(ctx context.Context) *goredis.StatusCmd
Close() error
FlushDB(ctx context.Context) *goredis.StatusCmd
Set(ctx context.Context, key string, value interface{}, expiration time.Duration) *goredis.StatusCmd
SAdd(ctx context.Context, key string, members ...interface{}) *goredis.IntCmd
Expire(ctx context.Context, key string, expiration time.Duration) *goredis.BoolCmd
ReloadState(ctx context.Context)
}
type SingleRedisClient struct {
*goredis.Client
}
func (c SingleRedisClient) ReloadState(ctx context.Context) {
// NO-OP
}
type Redis struct {
Host string
Port string
Password string
SaltEncoding string
DB int32
conn RedisClient
disableSuperuser bool
ctx context.Context
hasher hashing.HashComparer
}
func NewRedis(authOpts map[string]string, logLevel log.Level, hasher hashing.HashComparer) (Redis, error) {
log.SetLevel(logLevel)
var redis = Redis{
Host: "localhost",
Port: "6379",
DB: 1,
SaltEncoding: "base64",
ctx: context.Background(),
hasher: hasher,
}
if authOpts["redis_disable_superuser"] == "true" {
redis.disableSuperuser = true
}
if redisHost, ok := authOpts["redis_host"]; ok {
redis.Host = redisHost
}
if redisPort, ok := authOpts["redis_port"]; ok {
redis.Port = redisPort
}
if redisPassword, ok := authOpts["redis_password"]; ok {
redis.Password = redisPassword
}
if redisDB, ok := authOpts["redis_db"]; ok {
db, err := strconv.ParseInt(redisDB, 10, 32)
if err == nil {
redis.DB = int32(db)
}
}
if authOpts["redis_mode"] == "cluster" {
addressesOpt := authOpts["redis_cluster_addresses"]
if addressesOpt == "" {
return redis, fmt.Errorf("redis backend: missing Redis Cluster addresses")
}
// Take the given addresses and trim spaces from them.
addresses := strings.Split(addressesOpt, ",")
for i := 0; i < len(addresses); i++ {
addresses[i] = strings.TrimSpace(addresses[i])
}
clusterClient := goredis.NewClusterClient(
&goredis.ClusterOptions{
Addrs: addresses,
Password: redis.Password,
})
redis.conn = clusterClient
} else {
addr := fmt.Sprintf("%s:%s", redis.Host, redis.Port)
redisClient := goredis.NewClient(&goredis.Options{
Addr: addr,
Password: redis.Password,
DB: int(redis.DB),
})
redis.conn = &SingleRedisClient{redisClient}
}
for {
if _, err := redis.conn.Ping(redis.ctx).Result(); err != nil {
log.Errorf("ping redis error, will retry in 2s: %s", err)
time.Sleep(2 * time.Second)
} else {
break
}
}
return redis, nil
}
// Checks if an error was caused by a moved record in a cluster.
func isMovedError(err error) bool {
s := err.Error()
if strings.HasPrefix(s, "MOVED ") || strings.HasPrefix(s, "ASK ") {
return true
}
return false
}
//GetUser checks that the username exists and the given password hashes to the same password.
func (o Redis) GetUser(username, password, _ string) (bool, error) {
ok, err := o.getUser(username, password)
if err == nil {
return ok, nil
}
//If using Redis Cluster, reload state and attempt once more.
if isMovedError(err) {
o.conn.ReloadState(o.ctx)
//Retry once.
ok, err = o.getUser(username, password)
}
if err != nil {
log.Debugf("redis get user error: %s", err)
}
return ok, err
}
func (o Redis) getUser(username, password string) (bool, error) {
pwHash, err := o.conn.Get(o.ctx, username).Result()
if err == goredis.Nil {
return false, nil
} else if err != nil {
return false, err
}
if o.hasher.Compare(password, pwHash) {
return true, nil
}
return false, nil
}
//GetSuperuser checks that the key username:su exists and has value "true".
func (o Redis) GetSuperuser(username string) (bool, error) {
if o.disableSuperuser {
return false, nil
}
ok, err := o.getSuperuser(username)
if err == nil {
return ok, nil
}
//If using Redis Cluster, reload state and attempt once more.
if isMovedError(err) {
o.conn.ReloadState(o.ctx)
//Retry once.
ok, err = o.getSuperuser(username)
}
if err != nil {
log.Debugf("redis get superuser error: %s", err)
}
return ok, err
}
func (o Redis) getSuperuser(username string) (bool, error) {
isSuper, err := o.conn.Get(o.ctx, fmt.Sprintf("%s:su", username)).Result()
if err == goredis.Nil {
return false, nil
} else if err != nil {
return false, err
}
if isSuper == "true" {
return true, nil
}
return false, nil
}
func (o Redis) CheckAcl(username, topic, clientid string, acc int32) (bool, error) {
ok, err := o.checkAcl(username, topic, clientid, acc)
if err == nil {
return ok, nil
}
//If using Redis Cluster, reload state and attempt once more.
if isMovedError(err) {
o.conn.ReloadState(o.ctx)
//Retry once.
ok, err = o.checkAcl(username, topic, clientid, acc)
}
if err != nil {
log.Debugf("redis check acl error: %s", err)
}
return ok, err
}
//CheckAcl gets all acls for the username and tries to match against topic, acc, and username/clientid if needed.
func (o Redis) checkAcl(username, topic, clientid string, acc int32) (bool, error) {
var acls []string //User specific acls.
var commonAcls []string //Common acls.
//We need to check if client is subscribing, reading or publishing to get correct acls.
switch acc {
case MOSQ_ACL_SUBSCRIBE:
//Get all user subscribe acls.
var err error
acls, err = o.conn.SMembers(o.ctx, fmt.Sprintf("%s:sacls", username)).Result()
if err == goredis.Nil {
return false, nil
} else if err != nil {
return false, err
}
//Get common subscribe acls.
commonAcls, err = o.conn.SMembers(o.ctx, "common:sacls").Result()
if err == goredis.Nil {
return false, nil
} else if err != nil {
return false, err
}
case MOSQ_ACL_READ:
//Get all user read and readwrite acls.
urAcls, err := o.conn.SMembers(o.ctx, fmt.Sprintf("%s:racls", username)).Result()
if err == goredis.Nil {
return false, nil
} else if err != nil {
return false, err
}
urwAcls, err := o.conn.SMembers(o.ctx, fmt.Sprintf("%s:rwacls", username)).Result()
if err == goredis.Nil {
return false, nil
} else if err != nil {
return false, err
}
//Get common read and readwrite acls
rAcls, err := o.conn.SMembers(o.ctx, "common:racls").Result()
if err == goredis.Nil {
return false, nil
} else if err != nil {
return false, err
}
rwAcls, err := o.conn.SMembers(o.ctx, "common:rwacls").Result()
if err == goredis.Nil {
return false, nil
} else if err != nil {
return false, err
}
acls = make([]string, len(urAcls)+len(urwAcls))
acls = append(acls, urAcls...)
acls = append(acls, urwAcls...)
commonAcls = make([]string, len(rAcls)+len(rwAcls))
commonAcls = append(commonAcls, rAcls...)
commonAcls = append(commonAcls, rwAcls...)
case MOSQ_ACL_WRITE:
//Get all user write and readwrite acls.
uwAcls, err := o.conn.SMembers(o.ctx, fmt.Sprintf("%s:wacls", username)).Result()
if err == goredis.Nil {
return false, nil
} else if err != nil {
return false, err
}
urwAcls, err := o.conn.SMembers(o.ctx, fmt.Sprintf("%s:rwacls", username)).Result()
if err == goredis.Nil {
return false, nil
} else if err != nil {
return false, err
}
//Get common write and readwrite acls
wAcls, err := o.conn.SMembers(o.ctx, "common:wacls").Result()
if err == goredis.Nil {
return false, nil
} else if err != nil {
return false, err
}
rwAcls, err := o.conn.SMembers(o.ctx, "common:rwacls").Result()
if err == goredis.Nil {
return false, nil
} else if err != nil {
return false, err
}
acls = make([]string, len(uwAcls)+len(urwAcls))
acls = append(acls, uwAcls...)
acls = append(acls, urwAcls...)
commonAcls = make([]string, len(wAcls)+len(rwAcls))
commonAcls = append(commonAcls, wAcls...)
commonAcls = append(commonAcls, rwAcls...)
}
//Now loop through acls looking for a match.
for _, acl := range acls {
if topics.Match(acl, topic) {
return true, nil
}
}
for _, acl := range commonAcls {
aclTopic := strings.Replace(acl, "%c", clientid, -1)
aclTopic = strings.Replace(aclTopic, "%u", username, -1)
if topics.Match(aclTopic, topic) {
return true, nil
}
}
return false, nil
}
//GetName returns the backend's name
func (o Redis) GetName() string {
return "Redis"
}
//Halt terminates the connection.
func (o Redis) Halt() {
if o.conn != nil {
err := o.conn.Close()
if err != nil {
log.Errorf("Redis cleanup error: %s", err)
}
}
}