Repository navigation
Expand file tree
/
Copy pathengine_test.go
More file actions
737 lines (650 loc) · 23.4 KB
/
Copy pathengine_test.go
File metadata and controls
737 lines (650 loc) · 23.4 KB
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
package warden
import (
"context"
"strings"
"testing"
"time"
"github.com/xraph/warden/assignment"
"github.com/xraph/warden/id"
"github.com/xraph/warden/permission"
"github.com/xraph/warden/policy"
"github.com/xraph/warden/relation"
"github.com/xraph/warden/role"
"github.com/xraph/warden/store/memory"
)
func newTestEngine(t *testing.T) (*Engine, *memory.Store) {
t.Helper()
s := memory.New()
eng, err := NewEngine(WithStore(s))
if err != nil {
t.Fatal(err)
}
return eng, s
}
func TestNewEngine_RequiresStore(t *testing.T) {
_, err := NewEngine()
if err == nil {
t.Fatal("expected error when store is nil")
}
}
func TestRBACFlow(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, s := newTestEngine(t)
// Create role + permission.
roleID := id.NewRoleID()
permID := id.NewPermissionID()
_ = s.CreateRole(ctx, &role.Role{ID: roleID, TenantID: "t1", Name: "editor", Slug: "editor"})
_ = s.CreatePermission(ctx, &permission.Permission{ID: permID, TenantID: "t1", Name: "document:read", Resource: "document", Action: "read"})
_ = s.AttachPermission(ctx, "t1", roleID, permission.Ref{Name: "document:read"})
// Assign role to user.
_ = s.CreateAssignment(ctx, &assignment.Assignment{
TenantID: "t1",
RoleID: roleID,
SubjectKind: "user",
SubjectID: "u1",
})
// Check: user u1 should be allowed to read documents.
result, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "read"},
Resource: Resource{Type: "document", ID: "doc1"},
})
if err != nil {
t.Fatal(err)
}
if !result.Allowed {
t.Fatalf("expected allowed, got %s: %s", result.Decision, result.Reason)
}
if result.Decision != DecisionAllow {
t.Fatalf("expected decision allow, got %s", result.Decision)
}
// Check: user u1 should NOT be allowed to delete documents (no perm).
result, err = eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "delete"},
Resource: Resource{Type: "document", ID: "doc1"},
})
if err != nil {
t.Fatal(err)
}
if result.Allowed {
t.Fatal("expected denied for delete")
}
}
func TestRBACRoleInheritance(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, s := newTestEngine(t)
// Create parent role with permission.
parentID := id.NewRoleID()
childID := id.NewRoleID()
permID := id.NewPermissionID()
_ = s.CreateRole(ctx, &role.Role{ID: parentID, TenantID: "t1", Name: "viewer", Slug: "viewer"})
_ = s.CreateRole(ctx, &role.Role{ID: childID, TenantID: "t1", Name: "editor", Slug: "editor", ParentSlug: "viewer"})
_ = s.CreatePermission(ctx, &permission.Permission{ID: permID, TenantID: "t1", Name: "document:read", Resource: "document", Action: "read"})
_ = s.AttachPermission(ctx, "t1", parentID, permission.Ref{Name: "document:read"})
// Assign child role to user.
_ = s.CreateAssignment(ctx, &assignment.Assignment{
TenantID: "t1", RoleID: childID, SubjectKind: "user", SubjectID: "u1",
})
// User should inherit parent's permissions.
result, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "read"},
Resource: Resource{Type: "document", ID: "d1"},
})
if err != nil {
t.Fatal(err)
}
if !result.Allowed {
t.Fatalf("expected allowed via inheritance, got %s: %s", result.Decision, result.Reason)
}
}
// TestRBACRoleInheritance_MultiLevel verifies the walker traverses a chain of
// three roles (viewer ← editor ← admin) and that admin inherits permissions
// granted at every ancestor level.
func TestRBACRoleInheritance_MultiLevel(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, s := newTestEngine(t)
viewerID := id.NewRoleID()
editorID := id.NewRoleID()
adminID := id.NewRoleID()
readPerm := id.NewPermissionID()
writePerm := id.NewPermissionID()
deletePerm := id.NewPermissionID()
_ = s.CreateRole(ctx, &role.Role{ID: viewerID, TenantID: "t1", Name: "viewer", Slug: "viewer"})
_ = s.CreateRole(ctx, &role.Role{ID: editorID, TenantID: "t1", Name: "editor", Slug: "editor", ParentSlug: "viewer"})
_ = s.CreateRole(ctx, &role.Role{ID: adminID, TenantID: "t1", Name: "admin", Slug: "admin", ParentSlug: "editor"})
_ = s.CreatePermission(ctx, &permission.Permission{ID: readPerm, TenantID: "t1", Name: "doc:read", Resource: "doc", Action: "read"})
_ = s.CreatePermission(ctx, &permission.Permission{ID: writePerm, TenantID: "t1", Name: "doc:write", Resource: "doc", Action: "write"})
_ = s.CreatePermission(ctx, &permission.Permission{ID: deletePerm, TenantID: "t1", Name: "doc:delete", Resource: "doc", Action: "delete"})
_ = s.AttachPermission(ctx, "t1", viewerID, permission.Ref{Name: "doc:read"})
_ = s.AttachPermission(ctx, "t1", editorID, permission.Ref{Name: "doc:write"})
_ = s.AttachPermission(ctx, "t1", adminID, permission.Ref{Name: "doc:delete"})
_ = s.CreateAssignment(ctx, &assignment.Assignment{
TenantID: "t1", RoleID: adminID, SubjectKind: "user", SubjectID: "u1",
})
for _, action := range []string{"read", "write", "delete"} {
result, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: action},
Resource: Resource{Type: "doc", ID: "d1"},
})
if err != nil {
t.Fatalf("Check(%s): %v", action, err)
}
if !result.Allowed {
t.Fatalf("admin should inherit %q via chain, got %s: %s", action, result.Decision, result.Reason)
}
}
}
// TestRBACRoleInheritance_CircularSlug verifies that a cycle in parent_slug
// (A → B → A) terminates safely via the seen-set guard rather than recursing
// forever or duplicating roles. Even with a cycle, the engine still returns a
// correct Check result based on the cycle members' permissions.
func TestRBACRoleInheritance_CircularSlug(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, s := newTestEngine(t)
aID := id.NewRoleID()
bID := id.NewRoleID()
permID := id.NewPermissionID()
_ = s.CreateRole(ctx, &role.Role{ID: aID, TenantID: "t1", Name: "A", Slug: "role-a", ParentSlug: "role-b"})
_ = s.CreateRole(ctx, &role.Role{ID: bID, TenantID: "t1", Name: "B", Slug: "role-b", ParentSlug: "role-a"})
_ = s.CreatePermission(ctx, &permission.Permission{ID: permID, TenantID: "t1", Name: "doc:read", Resource: "doc", Action: "read"})
_ = s.AttachPermission(ctx, "t1", bID, permission.Ref{Name: "doc:read"})
_ = s.CreateAssignment(ctx, &assignment.Assignment{
TenantID: "t1", RoleID: aID, SubjectKind: "user", SubjectID: "u1",
})
done := make(chan struct{})
var result *CheckResult
var err error
go func() {
result, err = eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "read"},
Resource: Resource{Type: "doc", ID: "d1"},
})
close(done)
}()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("Check did not terminate on circular inheritance — walker did not bound itself")
}
if err != nil {
t.Fatal(err)
}
if !result.Allowed {
t.Fatalf("expected allow via cycle member B's permission, got %s: %s", result.Decision, result.Reason)
}
}
// TestRBACRoleInheritance_DanglingParentSlug verifies that a role pointing at
// a non-existent parent slug terminates the walk cleanly and returns the
// permissions granted to the role itself (no panic, no error).
func TestRBACRoleInheritance_DanglingParentSlug(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, s := newTestEngine(t)
roleID := id.NewRoleID()
permID := id.NewPermissionID()
_ = s.CreateRole(ctx, &role.Role{ID: roleID, TenantID: "t1", Name: "orphan", Slug: "orphan", ParentSlug: "ghost"})
_ = s.CreatePermission(ctx, &permission.Permission{ID: permID, TenantID: "t1", Name: "doc:read", Resource: "doc", Action: "read"})
_ = s.AttachPermission(ctx, "t1", roleID, permission.Ref{Name: "doc:read"})
_ = s.CreateAssignment(ctx, &assignment.Assignment{
TenantID: "t1", RoleID: roleID, SubjectKind: "user", SubjectID: "u1",
})
result, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "read"},
Resource: Resource{Type: "doc", ID: "d1"},
})
if err != nil {
t.Fatal(err)
}
if !result.Allowed {
t.Fatalf("expected allow via own permission despite dangling parent, got %s: %s", result.Decision, result.Reason)
}
}
func TestReBAC_DirectRelation(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, s := newTestEngine(t)
// Create direct relation: user u1 is viewer of document doc1.
_ = s.CreateRelation(ctx, &relation.Tuple{
TenantID: "t1",
ObjectType: "document",
ObjectID: "doc1",
Relation: "read",
SubjectType: "user",
SubjectID: "u1",
})
result, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "read"},
Resource: Resource{Type: "document", ID: "doc1"},
})
if err != nil {
t.Fatal(err)
}
if !result.Allowed {
t.Fatalf("expected allowed via direct relation, got %s: %s", result.Decision, result.Reason)
}
}
func TestReBAC_TransitiveRelation(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, s := newTestEngine(t)
// document:doc1#read -> folder:f1#read (subject set: read on folder grants read on doc)
_ = s.CreateRelation(ctx, &relation.Tuple{
TenantID: "t1",
ObjectType: "document", ObjectID: "doc1", Relation: "read",
SubjectType: "folder", SubjectID: "f1", SubjectRelation: "read",
})
// folder:f1#read -> user:u1
_ = s.CreateRelation(ctx, &relation.Tuple{
TenantID: "t1",
ObjectType: "folder", ObjectID: "f1", Relation: "read",
SubjectType: "user", SubjectID: "u1",
})
result, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "read"},
Resource: Resource{Type: "document", ID: "doc1"},
})
if err != nil {
t.Fatal(err)
}
if !result.Allowed {
t.Fatalf("expected allowed via transitive relation, got %s: %s", result.Decision, result.Reason)
}
}
// TestReBAC_NamespaceCascade verifies that relation tuples defined at an
// ancestor namespace grant access when the request is scoped to a descendant
// namespace — matching how RBAC roles and ABAC policies already cascade.
// A tuple at a non-ancestor namespace must NOT leak into the decision.
func TestReBAC_NamespaceCascade(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, s := newTestEngine(t)
// Direct relation at PARENT namespace "eng".
_ = s.CreateRelation(ctx, &relation.Tuple{
TenantID: "t1",
NamespacePath: "eng",
ObjectType: "document", ObjectID: "doc1", Relation: "read",
SubjectType: "user", SubjectID: "u1",
})
// Transitive chain at PARENT namespace "eng":
// document:doc2#read -> folder:f1#read (subject set) -> user:u2
_ = s.CreateRelation(ctx, &relation.Tuple{
TenantID: "t1",
NamespacePath: "eng",
ObjectType: "document", ObjectID: "doc2", Relation: "read",
SubjectType: "folder", SubjectID: "f1", SubjectRelation: "read",
})
_ = s.CreateRelation(ctx, &relation.Tuple{
TenantID: "t1",
NamespacePath: "eng",
ObjectType: "folder", ObjectID: "f1", Relation: "read",
SubjectType: "user", SubjectID: "u2",
})
// Decoy at NON-ancestor namespace "other".
_ = s.CreateRelation(ctx, &relation.Tuple{
TenantID: "t1",
NamespacePath: "other",
ObjectType: "document", ObjectID: "doc3", Relation: "read",
SubjectType: "user", SubjectID: "u3",
})
// Request scoped to the CHILD namespace "eng/platform".
check := func(subjectID, docID string) *CheckResult {
t.Helper()
res, err := eng.Check(ctx, &CheckRequest{
NamespacePath: "eng/platform",
Subject: Subject{Kind: SubjectUser, ID: subjectID},
Action: Action{Name: "read"},
Resource: Resource{Type: "document", ID: docID},
})
if err != nil {
t.Fatalf("check %s/%s: %v", subjectID, docID, err)
}
return res
}
if r := check("u1", "doc1"); !r.Allowed {
t.Errorf("direct relation at ancestor namespace should cascade: got %s: %s", r.Decision, r.Reason)
}
if r := check("u2", "doc2"); !r.Allowed {
t.Errorf("transitive relation at ancestor namespace should cascade: got %s: %s", r.Decision, r.Reason)
}
if r := check("u3", "doc3"); r.Allowed {
t.Errorf("relation at non-ancestor namespace must NOT cascade, but access was granted")
}
}
func TestABACFlow(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, s := newTestEngine(t)
// Create allow policy for users with role=admin attribute.
_ = s.CreatePolicy(ctx, &policy.Policy{
TenantID: "t1",
Name: "admin-allow",
Effect: policy.EffectAllow,
IsActive: true,
Subjects: []policy.SubjectMatch{{Kind: "user"}},
Actions: []string{"*"},
Conditions: []policy.Condition{
{Field: "subject.role", Operator: policy.OpEquals, Value: "admin"},
},
})
// Check with matching attribute.
result, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1", Attributes: map[string]any{"role": "admin"}},
Action: Action{Name: "delete"},
Resource: Resource{Type: "document", ID: "doc1"},
})
if err != nil {
t.Fatal(err)
}
if !result.Allowed {
t.Fatalf("expected allowed for admin, got %s: %s", result.Decision, result.Reason)
}
// Check with non-matching attribute.
result, err = eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u2", Attributes: map[string]any{"role": "viewer"}},
Action: Action{Name: "delete"},
Resource: Resource{Type: "document", ID: "doc1"},
})
if err != nil {
t.Fatal(err)
}
if result.Allowed {
t.Fatal("expected denied for non-admin")
}
}
func TestABACDenyOverridesAllow(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, s := newTestEngine(t)
// Allow policy.
_ = s.CreatePolicy(ctx, &policy.Policy{
TenantID: "t1", Name: "allow-all",
Effect: policy.EffectAllow, IsActive: true,
Actions: []string{"*"},
})
// Deny policy for specific IP range.
_ = s.CreatePolicy(ctx, &policy.Policy{
TenantID: "t1", Name: "deny-internal",
Effect: policy.EffectDeny, IsActive: true,
Actions: []string{"*"},
Conditions: []policy.Condition{
{Field: "context.ip", Operator: policy.OpIPInCIDR, Value: "10.0.0.0/8"},
},
})
// Request from internal IP — should be denied.
result, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "read"},
Resource: Resource{Type: "document", ID: "doc1"},
Context: map[string]any{"ip": "10.0.1.5"},
})
if err != nil {
t.Fatal(err)
}
if result.Allowed {
t.Fatal("expected denied for internal IP")
}
if result.Decision != DecisionDenyExplicit {
t.Fatalf("expected explicit deny, got %s", result.Decision)
}
// Request from external IP — should be allowed.
result, err = eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "read"},
Resource: Resource{Type: "document", ID: "doc1"},
Context: map[string]any{"ip": "203.0.113.1"},
})
if err != nil {
t.Fatal(err)
}
if !result.Allowed {
t.Fatalf("expected allowed for external IP, got %s: %s", result.Decision, result.Reason)
}
}
func TestEnforce(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, s := newTestEngine(t)
_ = s.CreatePolicy(ctx, &policy.Policy{
TenantID: "t1", Name: "allow-all",
Effect: policy.EffectAllow, IsActive: true, Actions: []string{"*"},
})
err := eng.Enforce(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "read"},
Resource: Resource{Type: "doc", ID: "d1"},
})
if err != nil {
t.Fatalf("expected no error for allowed check, got %v", err)
}
}
func TestCanI(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, s := newTestEngine(t)
_ = s.CreatePolicy(ctx, &policy.Policy{
TenantID: "t1", Name: "allow-all",
Effect: policy.EffectAllow, IsActive: true, Actions: []string{"*"},
})
allowed, err := eng.CanI(ctx, SubjectUser, "u1", "read", "doc", "d1")
if err != nil {
t.Fatal(err)
}
if !allowed {
t.Fatal("expected allowed")
}
}
func TestDefaultDeny(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, _ := newTestEngine(t)
// No roles, no relations, no policies — should be default deny.
result, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "read"},
Resource: Resource{Type: "document", ID: "doc1"},
})
if err != nil {
t.Fatal(err)
}
if result.Allowed {
t.Fatal("expected default deny")
}
}
func TestCheckEvalTime(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, _ := newTestEngine(t)
result, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "read"},
Resource: Resource{Type: "doc", ID: "d1"},
})
if err != nil {
t.Fatal(err)
}
if result.EvalTimeNs <= 0 {
t.Fatal("expected positive eval time")
}
}
func TestResourceScopedRole(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, s := newTestEngine(t)
roleID := id.NewRoleID()
permID := id.NewPermissionID()
_ = s.CreateRole(ctx, &role.Role{ID: roleID, TenantID: "t1", Name: "doc-editor", Slug: "doc-editor"})
_ = s.CreatePermission(ctx, &permission.Permission{ID: permID, TenantID: "t1", Name: "document:write", Resource: "document", Action: "write"})
_ = s.AttachPermission(ctx, "t1", roleID, permission.Ref{Name: "document:write"})
// Assign role scoped to a specific document.
_ = s.CreateAssignment(ctx, &assignment.Assignment{
TenantID: "t1", RoleID: roleID,
SubjectKind: "user", SubjectID: "u1",
ResourceType: "document", ResourceID: "doc1",
})
// Check on the scoped resource — should pass.
result, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "write"},
Resource: Resource{Type: "document", ID: "doc1"},
})
if err != nil {
t.Fatal(err)
}
if !result.Allowed {
t.Fatalf("expected allowed on scoped resource, got %s: %s", result.Decision, result.Reason)
}
}
func TestABACTimeCondition(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, s := newTestEngine(t)
future := time.Now().Add(time.Hour).Format(time.RFC3339)
_ = s.CreatePolicy(ctx, &policy.Policy{
TenantID: "t1", Name: "time-limited",
Effect: policy.EffectAllow, IsActive: true,
Actions: []string{"*"},
Conditions: []policy.Condition{
{Field: "context.time", Operator: policy.OpTimeBefore, Value: future},
},
})
result, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "read"},
Resource: Resource{Type: "doc", ID: "d1"},
Context: map[string]any{"time": time.Now().Format(time.RFC3339)},
})
if err != nil {
t.Fatal(err)
}
if !result.Allowed {
t.Fatalf("expected allowed before time limit, got %s: %s", result.Decision, result.Reason)
}
}
func TestCheckWithTenantOverride(t *testing.T) {
// Context has tenant "t1", but CheckRequest overrides to "t2".
ctx := WithTenant(context.Background(), "app1", "t1")
eng, s := newTestEngine(t)
// Create role + permission in tenant "t2".
roleID := id.NewRoleID()
permID := id.NewPermissionID()
_ = s.CreateRole(ctx, &role.Role{ID: roleID, TenantID: "t2", Name: "admin", Slug: "admin"})
_ = s.CreatePermission(ctx, &permission.Permission{ID: permID, TenantID: "t2", Name: "document:read", Resource: "document", Action: "read"})
_ = s.AttachPermission(ctx, "t2", roleID, permission.Ref{Name: "document:read"})
_ = s.CreateAssignment(ctx, &assignment.Assignment{
TenantID: "t2",
RoleID: roleID, SubjectKind: "user", SubjectID: "u1",
})
// Without tenant override — context tenant "t1" is used, should be denied.
result, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "read"},
Resource: Resource{Type: "document", ID: "doc1"},
})
if err != nil {
t.Fatal(err)
}
if result.Allowed {
t.Fatal("expected denied when using context tenant t1 (no data in t1)")
}
// With tenant override — should use "t2" and find the role/permission.
result, err = eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "read"},
Resource: Resource{Type: "document", ID: "doc1"},
TenantID: "t2",
})
if err != nil {
t.Fatal(err)
}
if !result.Allowed {
t.Fatalf("expected allowed with tenant override t2, got %s: %s", result.Decision, result.Reason)
}
}
func TestCheck_MissingResourceType(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, _ := newTestEngine(t)
_, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "read"},
Resource: Resource{Type: "", ID: "doc1"},
})
if err == nil {
t.Fatal("expected error for missing resource type")
}
if !strings.Contains(err.Error(), "resource type is required") {
t.Fatalf("expected error about resource type, got: %v", err)
}
}
func TestCheck_MissingSubjectID(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, _ := newTestEngine(t)
_, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: ""},
Action: Action{Name: "read"},
Resource: Resource{Type: "document", ID: "doc1"},
})
if err == nil {
t.Fatal("expected error for missing subject ID")
}
if !strings.Contains(err.Error(), "subject ID is required") {
t.Fatalf("expected error about subject ID, got: %v", err)
}
}
func TestCheck_MissingAction(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, _ := newTestEngine(t)
_, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: ""},
Resource: Resource{Type: "document", ID: "doc1"},
})
if err == nil {
t.Fatal("expected error for missing action")
}
if !strings.Contains(err.Error(), "action name is required") {
t.Fatalf("expected error about action, got: %v", err)
}
}
func TestCheck_DenyReasonIncludesContext(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, s := newTestEngine(t)
// Create a role but no permission — should get "no role grants permission" with details.
roleID := id.NewRoleID()
_ = s.CreateRole(ctx, &role.Role{ID: roleID, TenantID: "t1", Name: "viewer", Slug: "viewer"})
_ = s.CreateAssignment(ctx, &assignment.Assignment{
TenantID: "t1",
RoleID: roleID, SubjectKind: "user", SubjectID: "u1",
})
result, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "delete"},
Resource: Resource{Type: "document", ID: "doc1"},
})
if err != nil {
t.Fatal(err)
}
if result.Allowed {
t.Fatal("expected denied")
}
// Reason should include the permission name and subject.
if !strings.Contains(result.Reason, "document:delete") {
t.Fatalf("expected reason to include permission name, got: %s", result.Reason)
}
if !strings.Contains(result.Reason, "user:u1") {
t.Fatalf("expected reason to include subject, got: %s", result.Reason)
}
}
func TestCheck_DenyNoRolesReasonIncludesSubject(t *testing.T) {
ctx := WithTenant(context.Background(), "app1", "t1")
eng, _ := newTestEngine(t)
result, err := eng.Check(ctx, &CheckRequest{
Subject: Subject{Kind: SubjectUser, ID: "u1"},
Action: Action{Name: "read"},
Resource: Resource{Type: "document", ID: "doc1"},
})
if err != nil {
t.Fatal(err)
}
if result.Allowed {
t.Fatal("expected denied")
}
// With all models enabled, the merged result should contain informative context.
if result.Reason == "" {
t.Fatal("expected non-empty reason")
}
}