-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathevaluate.go
More file actions
428 lines (377 loc) · 14.1 KB
/
Copy pathevaluate.go
File metadata and controls
428 lines (377 loc) · 14.1 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
package access
import (
"context"
"errors"
"fmt"
"log/slog"
"slices"
"strings"
authz "github.com/opentdf/platform/protocol/go/authorization/v2"
"github.com/opentdf/platform/protocol/go/policy"
attrs "github.com/opentdf/platform/protocol/go/policy/attributes"
"github.com/opentdf/platform/service/internal/subjectmappingbuiltin"
"github.com/opentdf/platform/service/logger"
)
var (
ErrInvalidResource = errors.New("access: invalid resource")
ErrFQNNotFound = errors.New("access: FQN not found")
ErrDefinitionNotFound = errors.New("access: definition not found for FQN")
ErrFailedEvaluation = errors.New("access: failed to evaluate definition")
ErrMissingRequiredSpecifiedRule = errors.New("access: AttributeDefinition rule cannot be unspecified")
ErrUnrecognizedRule = errors.New("access: unrecognized AttributeDefinition rule")
)
// getResourceDecision evaluates the access decision for a single resource, driving the flows
// between entitlement checks for the different types of resources
func getResourceDecision(
ctx context.Context,
l *logger.Logger,
accessibleAttributeValues map[string]*attrs.GetAttributeValuesByFqnsResponse_AttributeAndValue,
accessibleRegisteredResourceValues map[string]*policy.RegisteredResourceValue,
entitlements subjectmappingbuiltin.AttributeValueFQNsToActions,
action *policy.Action,
resource *authz.Resource,
) (*ResourceDecision, error) {
var (
resourceID = resource.GetEphemeralId()
registeredResourceValueFQN string
resourceAttributeValues *authz.Resource_AttributeValues
failure = &ResourceDecision{
Entitled: false,
ResourceID: resourceID,
ResourceName: resourceID,
}
)
if err := validateGetResourceDecision(entitlements, action, resource); err != nil {
return nil, err
}
l.DebugContext(
ctx,
"getting decision on one resource",
slog.Any("resource", resource.GetResource()),
)
switch resource.GetResource().(type) {
case *authz.Resource_RegisteredResourceValueFqn:
registeredResourceValueFQN = strings.ToLower(resource.GetRegisteredResourceValueFqn())
l = l.With("registered_resource_value_fqn", registeredResourceValueFQN)
failure.ResourceName = registeredResourceValueFQN
regResValue, found := accessibleRegisteredResourceValues[registeredResourceValueFQN]
if !found {
l.WarnContext(
ctx,
"registered resource value not found - denying access",
)
return failure, nil
}
l.DebugContext(
ctx,
"registered_resource_value",
slog.Any("action_attribute_values", regResValue.GetActionAttributeValues()),
)
resourceAttributeValues = &authz.Resource_AttributeValues{
Fqns: make([]string, 0),
}
for _, aav := range regResValue.GetActionAttributeValues() {
aavAttrValueFQN := aav.GetAttributeValue().GetFqn()
// skip evaluating attribute rules on any action-attribute-values without the requested action
if aav.GetAction().GetName() != action.GetName() {
continue
}
if !slices.Contains(resourceAttributeValues.GetFqns(), aavAttrValueFQN) {
resourceAttributeValues.Fqns = append(resourceAttributeValues.Fqns, aavAttrValueFQN)
}
}
// if no relevant attributes from action-attribute-values with the requested action,
// indicates a failure before attribute definition rule evaluation
if len(resourceAttributeValues.GetFqns()) == 0 {
l.WarnContext(ctx, "registered resource value missing action-attribute-values for requested action")
return failure, nil
}
case *authz.Resource_AttributeValues_:
resourceAttributeValues = resource.GetAttributeValues()
default:
return nil, fmt.Errorf("unsupported resource type: %w", ErrInvalidResource)
}
// Cannot entitle any resource
if len(accessibleAttributeValues) == 0 {
l.WarnContext(ctx, "resource is not able to be entitled", slog.Any("resource", resource.GetResource()))
return failure, nil
}
return evaluateResourceAttributeValues(ctx, l, resourceAttributeValues, resourceID, registeredResourceValueFQN, action, entitlements, accessibleAttributeValues)
}
// evaluateResourceAttributeValues evaluates a list of attribute values against the action and entitlements
// and lowercases the FQNs to ensure case-insensitive matching
func evaluateResourceAttributeValues(
ctx context.Context,
l *logger.Logger,
resourceAttributeValues *authz.Resource_AttributeValues,
resourceID string,
resourceName string,
action *policy.Action,
entitlements subjectmappingbuiltin.AttributeValueFQNsToActions,
accessibleAttributeValues map[string]*attrs.GetAttributeValuesByFqnsResponse_AttributeAndValue,
) (*ResourceDecision, error) {
// Group value FQNs by parent definition
definitionFqnToValueFqns := make(map[string][]string)
definitionsLookup := make(map[string]*policy.Attribute)
notFoundFQNs := make([]string, 0)
for _, valueFQN := range resourceAttributeValues.GetFqns() {
attributeAndValue, ok := accessibleAttributeValues[valueFQN]
if !ok {
notFoundFQNs = append(notFoundFQNs, valueFQN)
continue
}
definition := attributeAndValue.GetAttribute()
definitionFqnToValueFqns[definition.GetFqn()] = append(definitionFqnToValueFqns[definition.GetFqn()], valueFQN)
definitionsLookup[definition.GetFqn()] = definition
}
// If ANY FQNs are missing, DENY the resource
if len(notFoundFQNs) > 0 {
l.WarnContext(ctx, "attribute value FQN(s) not found - denying access to resource",
slog.Any("not_found_fqns", notFoundFQNs),
slog.String("resource_id", resourceID))
result := &ResourceDecision{
Entitled: false,
ResourceID: resourceID,
}
if resourceName != "" {
result.ResourceName = resourceName
}
return result, nil
}
// Evaluate each definition by rule, resource attributes, action, and entitlements
passed := true
dataRuleResults := make([]DataRuleResult, 0)
for defFQN, resourceValueFQNs := range definitionFqnToValueFqns {
definition := definitionsLookup[defFQN]
if definition == nil {
return nil, fmt.Errorf("%w: %s", ErrDefinitionNotFound, defFQN)
}
dataRuleResult, err := evaluateDefinition(ctx, l, entitlements, action, resourceValueFQNs, definition)
if err != nil {
return nil, errors.Join(ErrFailedEvaluation, err)
}
if !dataRuleResult.Passed {
passed = false
}
dataRuleResults = append(dataRuleResults, *dataRuleResult)
}
// Return results in the appropriate structure
result := &ResourceDecision{
Entitled: passed,
ResourceID: resourceID,
DataRuleResults: dataRuleResults,
}
if resourceName != "" {
result.ResourceName = resourceName
}
return result, nil
}
func evaluateDefinition(
ctx context.Context,
l *logger.Logger,
entitlements subjectmappingbuiltin.AttributeValueFQNsToActions,
action *policy.Action,
resourceValueFQNs []string,
attrDefinition *policy.Attribute,
) (*DataRuleResult, error) {
var entitlementFailures []EntitlementFailure
l = l.With("definitionRule", attrDefinition.GetRule().String())
l = l.With("definitionFQN", attrDefinition.GetFqn())
l.DebugContext(
ctx,
"evaluating definition",
slog.Any("resource_value_fqns", resourceValueFQNs),
)
switch attrDefinition.GetRule() {
case policy.AttributeRuleTypeEnum_ATTRIBUTE_RULE_TYPE_ENUM_ALL_OF:
entitlementFailures = allOfRule(ctx, l, entitlements, action, resourceValueFQNs)
case policy.AttributeRuleTypeEnum_ATTRIBUTE_RULE_TYPE_ENUM_ANY_OF:
entitlementFailures = anyOfRule(ctx, l, entitlements, action, resourceValueFQNs)
case policy.AttributeRuleTypeEnum_ATTRIBUTE_RULE_TYPE_ENUM_HIERARCHY:
entitlementFailures = hierarchyRule(ctx, l, entitlements, action, resourceValueFQNs, attrDefinition)
case policy.AttributeRuleTypeEnum_ATTRIBUTE_RULE_TYPE_ENUM_UNSPECIFIED:
return nil, fmt.Errorf("%w: %s, rule: %s", ErrMissingRequiredSpecifiedRule, attrDefinition.GetFqn(), attrDefinition.GetRule().String())
default:
return nil, fmt.Errorf("%w: %s", ErrUnrecognizedRule, attrDefinition.GetRule().String())
}
passed := len(entitlementFailures) == 0
simpleAttribute := &policy.Attribute{
Id: attrDefinition.GetId(),
Fqn: attrDefinition.GetFqn(),
Rule: attrDefinition.GetRule(),
}
result := &DataRuleResult{
Passed: passed,
Attribute: simpleAttribute,
ResourceValueFQNs: resourceValueFQNs,
}
l.DebugContext(ctx, "definition evaluation result", slog.Bool("passed", passed))
if !passed {
result.EntitlementFailures = entitlementFailures
}
return result, nil
}
// allOfRule validates that:
// 1. For each resource attribute value FQN, the action is entitled
// 2. If any FQN is not entitled, or the FQN is missing the requested action, the rule fails
func allOfRule(
_ context.Context,
_ *logger.Logger,
entitlements subjectmappingbuiltin.AttributeValueFQNsToActions,
action *policy.Action,
resourceValueFQNs []string,
) []EntitlementFailure {
actionName := action.GetName()
failures := make([]EntitlementFailure, 0, len(resourceValueFQNs)) // Pre-allocate for efficiency
// Single loop through all resource value FQNs
for _, valueFQN := range resourceValueFQNs {
hasEntitlement := false
// Check if this FQN has the entitled action
if entitledActions, ok := entitlements[valueFQN]; ok {
for _, entitledAction := range entitledActions {
if strings.EqualFold(entitledAction.GetName(), actionName) {
hasEntitlement = true
break
}
}
}
// If no entitlement found for this FQN, add to failures immediately
if !hasEntitlement {
failures = append(failures, EntitlementFailure{
AttributeValueFQN: valueFQN,
ActionName: actionName,
})
}
}
return failures
}
// anyOfRule validates that:
// 1. At least one resource attribute value FQN has the action entitled
// 2. If none of the FQNs are found the entitlements, the rule fails
// 3. If none of the matching FQNs in the entitlements contain the requested action, the rule fails
func anyOfRule(
_ context.Context,
_ *logger.Logger,
entitlements subjectmappingbuiltin.AttributeValueFQNsToActions,
action *policy.Action,
resourceValueFQNs []string,
) []EntitlementFailure {
// No resources to check
if len(resourceValueFQNs) == 0 {
return nil
}
actionName := action.GetName()
anyEntitlementFound := false
entitlementFailures := make([]EntitlementFailure, 0, len(resourceValueFQNs))
// Single loop through all resource value FQNs
for _, valueFQN := range resourceValueFQNs {
foundEntitlementForThisFQN := false
entitledActions, ok := entitlements[valueFQN]
if ok {
for _, entitledAction := range entitledActions {
if strings.EqualFold(entitledAction.GetName(), actionName) {
foundEntitlementForThisFQN = true
anyEntitlementFound = true
break
}
}
}
if !foundEntitlementForThisFQN {
entitlementFailures = append(entitlementFailures, EntitlementFailure{
AttributeValueFQN: valueFQN,
ActionName: actionName,
})
}
}
// Rule is satisfied if at least one FQN has the entitled action
if anyEntitlementFound {
return nil
}
return entitlementFailures
}
// hierarchyRule validates that:
// 1. The user has entitlement to the specified action on the highest value FQN in the hierarchy or any hierarchically higher value
// 2. The highest value FQN is determined by the lowest index in the hierarchy definition
// 3. If the highest value FQN or any higher value has the required entitlement, the rule passes with no failures
// 4. If no hierarchically relevant FQN has the required entitlement, the rule fails with all missing entitlements
func hierarchyRule(
ctx context.Context,
l *logger.Logger,
entitlements subjectmappingbuiltin.AttributeValueFQNsToActions,
action *policy.Action,
resourceValueFQNs []string,
attrDefinition *policy.Attribute,
) []EntitlementFailure {
// No resources to check
if len(resourceValueFQNs) == 0 {
return nil
}
actionName := action.GetName()
attrValues := attrDefinition.GetValues()
// Create a lookup map for the attribute value indices - O(n) where n is the number of values in the attribute
valueFQNToIndex := make(map[string]int, len(attrValues))
for idx, value := range attrValues {
valueFQNToIndex[value.GetFqn()] = idx
}
// Find the lowest indexed value FQN (highest in hierarchy) - O(m) where m is the number of resource values
lowestValueFQNIndex := len(attrValues)
for _, valueFQN := range resourceValueFQNs {
if idx, exists := valueFQNToIndex[valueFQN]; exists && idx < lowestValueFQNIndex {
lowestValueFQNIndex = idx
}
}
// If we didn't find any matching value indices, fail with all as missing
if lowestValueFQNIndex == len(attrValues) {
failures := make([]EntitlementFailure, 0, len(resourceValueFQNs))
for _, fqn := range resourceValueFQNs {
failures = append(failures, EntitlementFailure{
AttributeValueFQN: fqn,
ActionName: actionName,
})
}
return failures
}
// Check entitlement at or above the hierarchy level:
// Scan only the FQNs in the definition up to the highest requested index (O(h))
// This is more efficient than scanning all entitlements (O(e)) when e >> h
for i := 0; i <= lowestValueFQNIndex; i++ {
candidateFQN := attrValues[i].GetFqn()
if entitledActions, ok := entitlements[candidateFQN]; ok {
for _, entitledAction := range entitledActions {
if strings.EqualFold(entitledAction.GetName(), actionName) {
l.DebugContext(ctx, "hierarchy rule satisfied",
slog.Group("entitled_by_value",
slog.String("FQN", candidateFQN),
slog.Int("index", i),
),
slog.Group("resource_highest_hierarchy_value",
slog.String("FQN", attrValues[lowestValueFQNIndex].GetFqn()),
slog.Int("index", lowestValueFQNIndex),
),
)
return nil
}
}
}
}
// The rule was not satisfied - collect failures - O(m) where m is the number of resource values
entitlementFailures := make([]EntitlementFailure, 0, len(resourceValueFQNs))
for _, valueFQN := range resourceValueFQNs {
foundValue := false
if entitledActions, ok := entitlements[valueFQN]; ok {
for _, entitledAction := range entitledActions {
if strings.EqualFold(entitledAction.GetName(), actionName) {
foundValue = true
break
}
}
}
if !foundValue {
entitlementFailures = append(entitlementFailures, EntitlementFailure{
AttributeValueFQN: valueFQN,
ActionName: actionName,
})
}
}
return entitlementFailures
}