-
Notifications
You must be signed in to change notification settings - Fork 243
/
check.go
382 lines (326 loc) · 12.7 KB
/
check.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
package graph
import (
"context"
"errors"
v0 "github.com/authzed/authzed-go/proto/authzed/api/v0"
v1_proto "github.com/authzed/authzed-go/proto/authzed/api/v1"
"github.com/rs/zerolog/log"
"github.com/shopspring/decimal"
"github.com/authzed/spicedb/internal/datastore"
"github.com/authzed/spicedb/internal/dispatch"
"github.com/authzed/spicedb/internal/namespace"
v1 "github.com/authzed/spicedb/internal/proto/dispatch/v1"
"github.com/authzed/spicedb/pkg/tuple"
)
// NewConcurrentChecker creates an instance of ConcurrentChecker.
func NewConcurrentChecker(d dispatch.Check, ds datastore.GraphDatastore, nsm namespace.Manager) *ConcurrentChecker {
return &ConcurrentChecker{d: d, ds: ds, nsm: nsm}
}
// ConcurrentChecker exposes a method to perform Check requests, and delegates subproblems to the
// provided dispatch.Check instance.
type ConcurrentChecker struct {
d dispatch.Check
ds datastore.GraphDatastore
nsm namespace.Manager
}
func onrEqual(lhs, rhs *v0.ObjectAndRelation) bool {
// Properties are sorted by highest to lowest cardinality to optimize for short-circuiting.
return lhs.ObjectId == rhs.ObjectId && lhs.Relation == rhs.Relation && lhs.Namespace == rhs.Namespace
}
// ValidatedCheckRequest represents a request after it has been validated and parsed for internal
// consumption.
type ValidatedCheckRequest struct {
*v1.DispatchCheckRequest
Revision decimal.Decimal
}
// Check performs a check request with the provided request and context
func (cc *ConcurrentChecker) Check(ctx context.Context, req ValidatedCheckRequest, relation *v0.Relation) (*v1.DispatchCheckResponse, error) {
var directFunc ReduceableCheckFunc
if req.Subject.ObjectId == tuple.PublicWildcard {
directFunc = checkError(NewErrInvalidArgument(errors.New("cannot perform check on wildcard")))
} else if onrEqual(req.Subject, req.ObjectAndRelation) {
// If we have found the goal's ONR, then we know that the ONR is a member.
directFunc = alwaysMember()
} else if relation.UsersetRewrite == nil {
directFunc = cc.checkDirect(ctx, req)
} else {
directFunc = cc.checkUsersetRewrite(ctx, req, relation.UsersetRewrite)
}
resolved := any(ctx, []ReduceableCheckFunc{directFunc})
resolved.Resp.Metadata = addCallToResponseMetadata(resolved.Resp.Metadata)
return resolved.Resp, resolved.Err
}
func (cc *ConcurrentChecker) dispatch(req ValidatedCheckRequest) ReduceableCheckFunc {
return func(ctx context.Context, resultChan chan<- CheckResult) {
log.Ctx(ctx).Trace().Object("dispatch", req).Send()
result, err := cc.d.DispatchCheck(ctx, req.DispatchCheckRequest)
resultChan <- CheckResult{result, err}
}
}
func onrEqualOrWildcard(tpl, target *v0.ObjectAndRelation) bool {
return onrEqual(tpl, target) || (tpl.Namespace == target.Namespace && tpl.ObjectId == tuple.PublicWildcard)
}
func (cc *ConcurrentChecker) checkDirect(ctx context.Context, req ValidatedCheckRequest) ReduceableCheckFunc {
return func(ctx context.Context, resultChan chan<- CheckResult) {
log.Ctx(ctx).Trace().Object("direct", req).Send()
// TODO(jschorr): Use type information to further optimize this query.
it, err := cc.ds.QueryTuples(ctx, &v1_proto.RelationshipFilter{
ResourceType: req.ObjectAndRelation.Namespace,
OptionalResourceId: req.ObjectAndRelation.ObjectId,
OptionalRelation: req.ObjectAndRelation.Relation,
}, req.Revision)
if err != nil {
resultChan <- checkResultError(NewCheckFailureErr(err), emptyMetadata)
return
}
defer it.Close()
var requestsToDispatch []ReduceableCheckFunc
for tpl := it.Next(); tpl != nil; tpl = it.Next() {
tplUserset := tpl.User.GetUserset()
if onrEqualOrWildcard(tplUserset, req.Subject) {
resultChan <- checkResult(v1.DispatchCheckResponse_MEMBER, emptyMetadata)
return
}
if tplUserset.Relation != Ellipsis {
// We need to recursively call check here, potentially changing namespaces
requestsToDispatch = append(requestsToDispatch, cc.dispatch(ValidatedCheckRequest{
&v1.DispatchCheckRequest{
ObjectAndRelation: tplUserset,
Subject: req.Subject,
Metadata: decrementDepth(req.Metadata),
},
req.Revision,
}))
}
}
if it.Err() != nil {
resultChan <- checkResultError(NewCheckFailureErr(it.Err()), emptyMetadata)
return
}
resultChan <- any(ctx, requestsToDispatch)
}
}
func (cc *ConcurrentChecker) checkUsersetRewrite(ctx context.Context, req ValidatedCheckRequest, usr *v0.UsersetRewrite) ReduceableCheckFunc {
switch rw := usr.RewriteOperation.(type) {
case *v0.UsersetRewrite_Union:
return cc.checkSetOperation(ctx, req, rw.Union, any)
case *v0.UsersetRewrite_Intersection:
return cc.checkSetOperation(ctx, req, rw.Intersection, all)
case *v0.UsersetRewrite_Exclusion:
return cc.checkSetOperation(ctx, req, rw.Exclusion, difference)
default:
return AlwaysFail
}
}
func (cc *ConcurrentChecker) checkSetOperation(ctx context.Context, req ValidatedCheckRequest, so *v0.SetOperation, reducer Reducer) ReduceableCheckFunc {
var requests []ReduceableCheckFunc
for _, childOneof := range so.Child {
switch child := childOneof.ChildType.(type) {
case *v0.SetOperation_Child_XThis:
requests = append(requests, cc.checkDirect(ctx, req))
case *v0.SetOperation_Child_ComputedUserset:
requests = append(requests, cc.checkComputedUserset(ctx, req, child.ComputedUserset, nil))
case *v0.SetOperation_Child_UsersetRewrite:
requests = append(requests, cc.checkUsersetRewrite(ctx, req, child.UsersetRewrite))
case *v0.SetOperation_Child_TupleToUserset:
requests = append(requests, cc.checkTupleToUserset(ctx, req, child.TupleToUserset))
}
}
return func(ctx context.Context, resultChan chan<- CheckResult) {
log.Ctx(ctx).Trace().Object("setOperation", req).Stringer("operation", so).Send()
resultChan <- reducer(ctx, requests)
}
}
func (cc *ConcurrentChecker) checkComputedUserset(ctx context.Context, req ValidatedCheckRequest, cu *v0.ComputedUserset, tpl *v0.RelationTuple) ReduceableCheckFunc {
var start *v0.ObjectAndRelation
if cu.Object == v0.ComputedUserset_TUPLE_USERSET_OBJECT {
if tpl == nil {
panic("computed userset for tupleset without tuple")
}
start = tpl.User.GetUserset()
} else if cu.Object == v0.ComputedUserset_TUPLE_OBJECT {
if tpl != nil {
start = tpl.ObjectAndRelation
} else {
start = req.ObjectAndRelation
}
}
targetOnr := &v0.ObjectAndRelation{
Namespace: start.Namespace,
ObjectId: start.ObjectId,
Relation: cu.Relation,
}
// If we will be dispatching to the goal's ONR, then we know that the ONR is a member.
if onrEqual(req.Subject, targetOnr) {
return alwaysMember()
}
// Check if the target relation exists. If not, return nothing.
err := cc.nsm.CheckNamespaceAndRelation(ctx, start.Namespace, cu.Relation, true, req.Revision)
if err != nil {
if errors.As(err, &namespace.ErrRelationNotFound{}) {
return notMember()
}
return checkError(err)
}
return cc.dispatch(ValidatedCheckRequest{
&v1.DispatchCheckRequest{
ObjectAndRelation: targetOnr,
Subject: req.Subject,
Metadata: decrementDepth(req.Metadata),
},
req.Revision,
})
}
func (cc *ConcurrentChecker) checkTupleToUserset(ctx context.Context, req ValidatedCheckRequest, ttu *v0.TupleToUserset) ReduceableCheckFunc {
return func(ctx context.Context, resultChan chan<- CheckResult) {
log.Ctx(ctx).Trace().Object("ttu", req).Send()
it, err := cc.ds.QueryTuples(ctx, &v1_proto.RelationshipFilter{
ResourceType: req.ObjectAndRelation.Namespace,
OptionalResourceId: req.ObjectAndRelation.ObjectId,
OptionalRelation: ttu.Tupleset.Relation,
}, req.Revision)
if err != nil {
resultChan <- checkResultError(NewCheckFailureErr(err), emptyMetadata)
return
}
defer it.Close()
var requestsToDispatch []ReduceableCheckFunc
for tpl := it.Next(); tpl != nil; tpl = it.Next() {
requestsToDispatch = append(requestsToDispatch, cc.checkComputedUserset(ctx, req, ttu.ComputedUserset, tpl))
}
if it.Err() != nil {
resultChan <- checkResultError(NewCheckFailureErr(it.Err()), emptyMetadata)
return
}
resultChan <- any(ctx, requestsToDispatch)
}
}
// all returns whether all of the lazy checks pass, and is used for intersection.
func all(ctx context.Context, requests []ReduceableCheckFunc) CheckResult {
if len(requests) == 0 {
return checkResult(v1.DispatchCheckResponse_NOT_MEMBER, emptyMetadata)
}
responseMetadata := emptyMetadata
resultChan := make(chan CheckResult, len(requests))
childCtx, cancelFn := context.WithCancel(ctx)
defer cancelFn()
for _, req := range requests {
go req(childCtx, resultChan)
}
for i := 0; i < len(requests); i++ {
select {
case result := <-resultChan:
responseMetadata = combineResponseMetadata(responseMetadata, result.Resp.Metadata)
if result.Err != nil {
return checkResultError(result.Err, responseMetadata)
}
if result.Resp.Membership != v1.DispatchCheckResponse_MEMBER {
return checkResult(v1.DispatchCheckResponse_NOT_MEMBER, responseMetadata)
}
case <-ctx.Done():
return checkResultError(NewRequestCanceledErr(), responseMetadata)
}
}
return checkResult(v1.DispatchCheckResponse_MEMBER, responseMetadata)
}
// checkError returns the error.
func checkError(err error) ReduceableCheckFunc {
return func(ctx context.Context, resultChan chan<- CheckResult) {
resultChan <- checkResultError(err, emptyMetadata)
}
}
// alwaysMember returns that the check always passes.
func alwaysMember() ReduceableCheckFunc {
return func(ctx context.Context, resultChan chan<- CheckResult) {
resultChan <- checkResult(v1.DispatchCheckResponse_MEMBER, emptyMetadata)
}
}
// notMember returns that the check always returns false.
func notMember() ReduceableCheckFunc {
return func(ctx context.Context, resultChan chan<- CheckResult) {
resultChan <- checkResult(v1.DispatchCheckResponse_NOT_MEMBER, emptyMetadata)
}
}
// any returns whether any one of the lazy checks pass, and is used for union.
func any(ctx context.Context, requests []ReduceableCheckFunc) CheckResult {
if len(requests) == 0 {
return checkResult(v1.DispatchCheckResponse_NOT_MEMBER, emptyMetadata)
}
resultChan := make(chan CheckResult, len(requests))
childCtx, cancelFn := context.WithCancel(ctx)
defer cancelFn()
for _, req := range requests {
go req(childCtx, resultChan)
}
responseMetadata := emptyMetadata
for i := 0; i < len(requests); i++ {
select {
case result := <-resultChan:
log.Ctx(ctx).Trace().Object("anyResult", result.Resp).Send()
responseMetadata = combineResponseMetadata(responseMetadata, result.Resp.Metadata)
if result.Err == nil && result.Resp.Membership == v1.DispatchCheckResponse_MEMBER {
return checkResult(v1.DispatchCheckResponse_MEMBER, result.Resp.Metadata)
}
if result.Err != nil {
return checkResultError(result.Err, result.Resp.Metadata)
}
case <-ctx.Done():
log.Ctx(ctx).Trace().Msg("anyCanceled")
return checkResultError(NewRequestCanceledErr(), responseMetadata)
}
}
return checkResult(v1.DispatchCheckResponse_NOT_MEMBER, responseMetadata)
}
// difference returns whether the first lazy check passes and none of the supsequent checks pass.
func difference(ctx context.Context, requests []ReduceableCheckFunc) CheckResult {
childCtx, cancelFn := context.WithCancel(ctx)
defer cancelFn()
baseChan := make(chan CheckResult, 1)
othersChan := make(chan CheckResult, len(requests)-1)
go requests[0](childCtx, baseChan)
for _, req := range requests[1:] {
go req(childCtx, othersChan)
}
responseMetadata := emptyMetadata
for i := 0; i < len(requests); i++ {
select {
case base := <-baseChan:
responseMetadata = combineResponseMetadata(responseMetadata, base.Resp.Metadata)
if base.Err != nil {
return checkResultError(base.Err, responseMetadata)
}
if base.Resp.Membership != v1.DispatchCheckResponse_MEMBER {
return checkResult(v1.DispatchCheckResponse_NOT_MEMBER, responseMetadata)
}
case sub := <-othersChan:
responseMetadata = combineResponseMetadata(responseMetadata, sub.Resp.Metadata)
if sub.Err != nil {
return checkResultError(sub.Err, responseMetadata)
}
if sub.Resp.Membership == v1.DispatchCheckResponse_MEMBER {
return checkResult(v1.DispatchCheckResponse_NOT_MEMBER, responseMetadata)
}
case <-ctx.Done():
return checkResultError(NewRequestCanceledErr(), responseMetadata)
}
}
return checkResult(v1.DispatchCheckResponse_MEMBER, responseMetadata)
}
func checkResult(membership v1.DispatchCheckResponse_Membership, subProblemMetadata *v1.ResponseMeta) CheckResult {
return CheckResult{
&v1.DispatchCheckResponse{
Metadata: ensureMetadata(subProblemMetadata),
Membership: membership,
},
nil,
}
}
func checkResultError(err error, subProblemMetadata *v1.ResponseMeta) CheckResult {
return CheckResult{
&v1.DispatchCheckResponse{
Metadata: ensureMetadata(subProblemMetadata),
Membership: v1.DispatchCheckResponse_UNKNOWN,
},
err,
}
}