forked from rusenask/casbin-go-cloud-watcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatcher_test.go
484 lines (392 loc) · 12 KB
/
watcher_test.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package watcher
import (
"context"
"fmt"
"testing"
"time"
_ "github.com/bartventer/casbin-go-cloud-watcher/drivers/mempubsub"
_ "github.com/bartventer/casbin-go-cloud-watcher/drivers/natspubsub"
"github.com/casbin/casbin/v2"
gnatsd "github.com/nats-io/nats-server/v2/test"
"github.com/nats-io/nats.go"
)
func TestNATSWatcher(t *testing.T) {
// Setup nats server
s := gnatsd.RunDefaultServer()
defer s.Shutdown()
natsEndpoint := fmt.Sprintf("nats://localhost:%d", nats.DefaultPort)
natsSubject := "nats://casbin-policy-updated-subject"
updaterCh := make(chan string, 1)
listenerCh := make(chan string, 1)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// gocloud.dev connects to NATS server based on env variable
t.Setenv("NATS_SERVER_URL", natsEndpoint)
// updater represents the Casbin enforcer instance that changes the policy in DB
// Use the endpoint of nats as parameter.
updater, err := New(ctx, natsSubject)
if err != nil {
t.Fatalf("Failed to create updater, error: %s", err)
}
defer updater.Close()
updater.SetUpdateCallback(func(msg string) {
updaterCh <- "updater"
})
// listener represents any other Casbin enforcer instance that watches the change of policy in DB
listener, err := New(ctx, natsSubject)
if err != nil {
t.Fatalf("Failed to create second listener: %s", err)
}
defer listener.Close()
// listener should set a callback that gets called when policy changes
err = listener.SetUpdateCallback(func(msg string) {
listenerCh <- "listener"
})
if err != nil {
t.Fatalf("Failed to set listener callback: %s", err)
}
// updater changes the policy, and sends the notifications.
err = updater.Update()
if err != nil {
t.Fatalf("The updater failed to send Update: %s", err)
}
// Validate that listener received message
var updaterReceived bool
var listenerReceived bool
for {
select {
case res := <-listenerCh:
if res != "listener" {
t.Fatalf("Message from unknown source: %v", res)
}
listenerReceived = true
case res := <-updaterCh:
if res != "updater" {
t.Fatalf("Message from unknown source: %v", res)
}
updaterReceived = true
case <-time.After(time.Second * 10):
t.Fatal("Updater or listener didn't received message in time")
}
if updaterReceived && listenerReceived {
close(listenerCh)
close(updaterCh)
break
}
}
}
func TestWithEnforcerNATS(t *testing.T) {
// Setup nats server
s := gnatsd.RunDefaultServer()
defer s.Shutdown()
natsEndpoint := fmt.Sprintf("nats://localhost:%d", nats.DefaultPort)
natsSubject := "nats://casbin-policy-updated-subject"
cannel := make(chan string, 1)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// gocloud.dev connects to NATS server based on env variable
t.Setenv("NATS_SERVER_URL", natsEndpoint)
w, err := New(ctx, natsSubject)
if err != nil {
t.Fatalf("Failed to create updater, error: %s", err)
}
defer w.Close()
// Initialize the enforcer.
e, _ := casbin.NewEnforcer("./testdata/model.conf", "./testdata/policy.csv")
// Set the watcher for the enforcer.
e.SetWatcher(w)
// By default, the watcher's callback is automatically set to the
// enforcer's LoadPolicy() in the SetWatcher() call.
// We can change it by explicitly setting a callback.
w.SetUpdateCallback(func(msg string) {
cannel <- "enforcer"
})
// Update the policy to test the effect.
e.SavePolicy()
// Validate that listener received message
select {
case res := <-cannel:
if res != "enforcer" {
t.Fatalf("Got unexpected message :%v", res)
}
case <-time.After(time.Second * 10):
t.Fatal("The enforcer didn't send message in time")
}
close(cannel)
}
func TestWithEnforcerMemory(t *testing.T) {
endpointURL := "mem://topicA"
cannel := make(chan string, 1)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
w, err := New(ctx, endpointURL)
if err != nil {
t.Fatalf("Failed to create updater, error: %s", err)
}
defer w.Close()
// Initialize the enforcer.
e, _ := casbin.NewEnforcer("./testdata/model.conf", "./testdata/policy.csv")
// Set the watcher for the enforcer.
e.SetWatcher(w)
// By default, the watcher's callback is automatically set to the
// enforcer's LoadPolicy() in the SetWatcher() call.
// We can change it by explicitly setting a callback.
w.SetUpdateCallback(func(msg string) {
cannel <- "enforcer"
})
// Update the policy to test the effect.
e.SavePolicy()
// Validate that listener received message
select {
case res := <-cannel:
if res != "enforcer" {
t.Fatalf("Got unexpected message :%v", res)
}
case <-time.After(time.Second * 5):
t.Fatal("The enforcer didn't send message in time")
}
close(cannel)
}
// Ensure that we can still use the same topic name.
func TestWithEnforcerMemoryB(t *testing.T) {
// endpointURL := "mem://topicA"
endpointURL := "mem://topicA"
cannel := make(chan string, 1)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
w, err := New(ctx, endpointURL)
if err != nil {
t.Fatalf("Failed to create updater, error: %s", err)
}
defer w.Close()
// Initialize the enforcer.
e, _ := casbin.NewEnforcer("./testdata/model.conf", "./testdata/policy.csv")
// Set the watcher for the enforcer.
e.SetWatcher(w)
// By default, the watcher's callback is automatically set to the
// enforcer's LoadPolicy() in the SetWatcher() call.
// We can change it by explicitly setting a callback.
w.SetUpdateCallback(func(msg string) {
cannel <- "enforcer"
})
// Update the policy to test the effect.
e.SavePolicy()
// Validate that listener received message
select {
case res := <-cannel:
if res != "enforcer" {
t.Fatalf("Got unexpected message :%v", res)
}
case <-time.After(time.Second * 5):
t.Fatal("The enforcer didn't send message in time")
}
close(cannel)
}
func initWithOption(t *testing.T, opt Option) (*Watcher, *casbin.Enforcer) {
w, err := NewWithOption(context.Background(), "mem://topicA", opt)
if err != nil {
t.Fatalf("failed to new watcher: %v", err)
}
// create enforcer.
e, err := casbin.NewEnforcer("testdata/model.conf", "testdata/policy.csv")
if err != nil {
t.Fatalf("failed to new enforcer: %v", err)
}
return w, e
}
func TestWatcherAddPolicy(t *testing.T) {
w, e := initWithOption(t, Option{
LocalID: "local-id",
})
if err := e.SetWatcher(w); err != nil {
t.Fatalf("failed to set watcher: %v", err)
}
recv := ""
if err := w.SetUpdateCallback(func(s string) {
recv = s
}); err != nil {
t.Fatalf("failed to set update callback: %v", err)
}
if _, err := e.AddPolicy("alice", "data2", "read"); err != nil {
t.Fatalf("failed to update: %v", err)
}
time.Sleep(time.Millisecond * 300)
w.Close()
if recv != `{"method":"UpdateForAddPolicy","id":"local-id","sec":"p","ptype":"p","new_rules":[["alice","data2","read"]]}` {
t.Fatalf("unexpected msg: %s", recv)
}
}
func TestWatcherRemovePolicy(t *testing.T) {
w, e := initWithOption(t, Option{
LocalID: "local-id",
})
if err := e.SetWatcher(w); err != nil {
t.Fatalf("failed to set watcher: %v", err)
}
recv := ""
if err := w.SetUpdateCallback(func(s string) {
recv = s
}); err != nil {
t.Fatalf("failed to set update callback: %v", err)
}
if _, err := e.RemovePolicy("alice", "data1", "read"); err != nil {
t.Fatalf("failed to update: %v", err)
}
time.Sleep(time.Millisecond * 300)
w.Close()
if recv != `{"method":"UpdateForRemovePolicy","id":"local-id","sec":"p","ptype":"p","new_rules":[["alice","data1","read"]]}` {
t.Fatalf("unexpected msg: %s", recv)
}
}
func TestWatcherSavePolicy(t *testing.T) {
w, e := initWithOption(t, Option{
LocalID: "local-id",
})
if err := e.SetWatcher(w); err != nil {
t.Fatalf("failed to set watcher: %v", err)
}
recv := ""
if err := w.SetUpdateCallback(func(s string) {
recv = s
}); err != nil {
t.Fatalf("failed to set update callback: %v", err)
}
if err := e.SavePolicy(); err != nil {
t.Fatalf("failed to update: %v", err)
}
time.Sleep(time.Millisecond * 300)
w.Close()
if recv != `{"method":"UpdateForSavePolicy","id":"local-id"}` {
t.Fatalf("unexpected msg: %s", recv)
}
}
func TestWatcherAddPolicies(t *testing.T) {
w, e := initWithOption(t, Option{
LocalID: "local-id",
})
if err := e.SetWatcher(w); err != nil {
t.Fatalf("failed to set watcher: %v", err)
}
recv := ""
if err := w.SetUpdateCallback(func(s string) {
recv = s
}); err != nil {
t.Fatalf("failed to set update callback: %v", err)
}
if _, err := e.AddPolicies([][]string{
{"alice", "data2", "read"},
{"alice", "data3", "read"},
}); err != nil {
t.Fatalf("failed to update: %v", err)
}
time.Sleep(time.Millisecond * 300)
w.Close()
if recv != `{"method":"UpdateForAddPolicies","id":"local-id","sec":"p","ptype":"p","new_rules":[["alice","data2","read"],["alice","data3","read"]]}` {
t.Fatalf("unexpected msg: %s", recv)
}
}
func TestWatcherRemovePolicies(t *testing.T) {
w, e := initWithOption(t, Option{
LocalID: "local-id",
})
if err := e.SetWatcher(w); err != nil {
t.Fatalf("failed to set watcher: %v", err)
}
recv := ""
if err := w.SetUpdateCallback(func(s string) {
recv = s
}); err != nil {
t.Fatalf("failed to set update callback: %v", err)
}
if _, err := e.RemovePolicies([][]string{
{"alice", "data1", "read"},
{"bob", "data2", "write"},
}); err != nil {
t.Fatalf("failed to update: %v", err)
}
time.Sleep(time.Millisecond * 300)
w.Close()
if recv != `{"method":"UpdateForRemovePolicies","id":"local-id","sec":"p","ptype":"p","new_rules":[["alice","data1","read"],["bob","data2","write"]]}` {
t.Fatalf("unexpected msg: %s", recv)
}
}
func TestWatcherUpdatePolicy(t *testing.T) {
w, e := initWithOption(t, Option{
LocalID: "local-id",
})
if err := e.SetWatcher(w); err != nil {
t.Fatalf("failed to set watcher: %v", err)
}
recv := ""
if err := w.SetUpdateCallback(func(s string) {
recv = s
}); err != nil {
t.Fatalf("failed to set update callback: %v", err)
}
if _, err := e.UpdatePolicy(
[]string{"alice", "data1", "read"},
[]string{"alice", "data1", "write"},
); err != nil {
t.Fatalf("failed to update: %v", err)
}
time.Sleep(time.Millisecond * 300)
w.Close()
if recv != `{"method":"UpdateForUpdatePolicy","id":"local-id","sec":"p","ptype":"p","old_rules":[["alice","data1","read"]],"new_rules":[["alice","data1","write"]]}` {
t.Fatalf("unexpected msg: %s", recv)
}
}
func TestWatcherUpdatePolicies(t *testing.T) {
w, e := initWithOption(t, Option{
LocalID: "local-id",
})
if err := e.SetWatcher(w); err != nil {
t.Fatalf("failed to set watcher: %v", err)
}
recv := ""
if err := w.SetUpdateCallback(func(s string) {
recv = s
}); err != nil {
t.Fatalf("failed to set update callback: %v", err)
}
if _, err := e.UpdatePolicies(
[][]string{{"alice", "data1", "read"}},
[][]string{{"alice", "data1", "write"}},
); err != nil {
t.Fatalf("failed to update: %v", err)
}
time.Sleep(time.Millisecond * 300)
w.Close()
if recv != `{"method":"UpdateForUpdatePolicies","id":"local-id","sec":"p","ptype":"p","old_rules":[["alice","data1","read"]],"new_rules":[["alice","data1","write"]]}` {
t.Fatalf("unexpected msg: %s", recv)
}
}
func TestWatcherWithDefaultCallback(t *testing.T) {
w1, e1 := initWithOption(t, Option{})
w2, e2 := initWithOption(t, Option{})
if err := e1.SetWatcher(w1); err != nil {
t.Fatalf("failed to set watcher1: %v", err)
}
if err := e2.SetWatcher(w2); err != nil {
t.Fatalf("failed to set watcher2: %v", err)
}
if err := w1.SetUpdateCallback(DefaultCallback(e1)); err != nil {
t.Fatalf("failed to set update callback1: %v", err)
}
if err := w2.SetUpdateCallback(DefaultCallback(e2)); err != nil {
t.Fatalf("failed to set update callback2: %v", err)
}
if _, err := e1.AddPolicy("foo", "data1", "read"); err != nil {
t.Fatalf("failed to update: %v", err)
}
time.Sleep(time.Millisecond * 300)
w1.Close()
w2.Close()
policies, err := e1.GetFilteredPolicy(0, "foo")
if err != nil {
t.Fatalf("failed to get policy: %v", err)
}
if len(policies) == 1 && policies[0][0] == "foo" && policies[0][1] == "data1" && policies[0][2] == "read" {
return
}
t.Fatalf("unexpected policy: %+v", policies)
}