Skip to content

Commit bdbda3c

Browse files
committed
chore: Add benchmark test for rbac.Filter
1 parent 1140e29 commit bdbda3c

File tree

2 files changed

+26
-13
lines changed

2 files changed

+26
-13
lines changed

coderd/rbac/authz.go

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,8 @@ var policy string
4343
func NewAuthorizer() (*RegoAuthorizer, error) {
4444
ctx := context.Background()
4545
query, err := rego.New(
46-
// allowed is the `allow` field from the prepared query. This is the field to check if authorization is
47-
// granted.
48-
rego.Query("allowed = data.authz.allow"),
46+
// Query returns true/false for authorization access
47+
rego.Query("data.authz.allow"),
4948
rego.Module("policy.rego", policy),
5049
).PrepareForEval(ctx)
5150

@@ -92,16 +91,7 @@ func (a RegoAuthorizer) Authorize(ctx context.Context, subjectID string, roles [
9291
return ForbiddenWithInternal(xerrors.Errorf("eval rego: %w", err), input, results)
9392
}
9493

95-
if len(results) != 1 {
96-
return ForbiddenWithInternal(xerrors.Errorf("expect only 1 result, got %d", len(results)), input, results)
97-
}
98-
99-
allowedResult, ok := (results[0].Bindings["allowed"]).(bool)
100-
if !ok {
101-
return ForbiddenWithInternal(xerrors.Errorf("expected allowed to be a bool but got %T", allowedResult), input, results)
102-
}
103-
104-
if !allowedResult {
94+
if !results.Allowed() {
10595
return ForbiddenWithInternal(xerrors.Errorf("policy disallows request"), input, results)
10696
}
10797

coderd/rbac/authz_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,29 @@ type subject struct {
2323
Roles []rbac.Role `json:"roles"`
2424
}
2525

26+
// BenchmarkRBACFilter benchmarks the rbac.Filter method. Authorizing batch
27+
// objects has a noticeable cost on performance.
28+
// go test -bench BenchmarkRBACFilter -benchmem -memprofile memprofile.out -cpuprofile profile.out
29+
func BenchmarkRBACFilter(b *testing.B) {
30+
ctx := context.Background()
31+
objectList := make([]rbac.Object, b.N)
32+
orgID := uuid.New()
33+
for i := range objectList {
34+
objectList[i] = rbac.ResourceWorkspace.
35+
InOrg(orgID).
36+
WithID(uuid.NewString()).
37+
WithOwner("other")
38+
}
39+
40+
authorizer, err := rbac.NewAuthorizer()
41+
require.NoError(b, err)
42+
43+
roles := []string{rbac.RoleOrgAdmin(orgID)}
44+
45+
b.ResetTimer()
46+
rbac.Filter(ctx, authorizer, "me", roles, rbac.ActionRead, objectList)
47+
}
48+
2649
func TestFilter(t *testing.T) {
2750
t.Parallel()
2851

0 commit comments

Comments
 (0)