-
Notifications
You must be signed in to change notification settings - Fork 123
/
index.go
527 lines (427 loc) · 13.2 KB
/
index.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
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
// Copyright 2021-2023 Zenauth Ltd.
// SPDX-License-Identifier: Apache-2.0
package index
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"sort"
"sync"
"go.opencensus.io/stats"
"go.opencensus.io/tag"
"go.uber.org/zap"
"golang.org/x/sync/singleflight"
policyv1 "github.com/cerbos/cerbos/api/genpb/cerbos/policy/v1"
"github.com/cerbos/cerbos/internal/namer"
"github.com/cerbos/cerbos/internal/observability/metrics"
"github.com/cerbos/cerbos/internal/policy"
"github.com/cerbos/cerbos/internal/storage"
"github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap"
)
var (
// ErrDuplicatePolicy signals that there are duplicate policy definitions.
ErrDuplicatePolicy = errors.New("duplicate policy definitions")
// ErrInvalidEntry signals that the index entry is invalid.
ErrInvalidEntry = errors.New("invalid index entry")
// ErrPolicyNotFound signals that the policy does not exist.
ErrPolicyNotFound = errors.New("policy not found")
)
type Entry struct {
File string
Policy policy.Wrapper
}
type Index interface {
io.Closer
storage.Instrumented
GetFirstMatch([]namer.ModuleID) (*policy.CompilationUnit, error)
GetCompilationUnits(...namer.ModuleID) (map[namer.ModuleID]*policy.CompilationUnit, error)
GetDependents(...namer.ModuleID) (map[namer.ModuleID][]namer.ModuleID, error)
AddOrUpdate(Entry) (storage.Event, error)
Delete(Entry) (storage.Event, error)
GetFiles() []string
GetAllCompilationUnits(context.Context) <-chan *policy.CompilationUnit
Clear() error
ListPolicyIDs(context.Context) ([]string, error)
ListSchemaIDs(context.Context) ([]string, error)
LoadSchema(context.Context, string) (io.ReadCloser, error)
LoadPolicy(context.Context, ...string) ([]*policy.Wrapper, error)
Reload(ctx context.Context) ([]storage.Event, error)
}
type index struct {
fsys fs.FS
fileToModID map[string]namer.ModuleID
executables map[namer.ModuleID]struct{}
dependents map[namer.ModuleID]map[namer.ModuleID]struct{}
dependencies map[namer.ModuleID]map[namer.ModuleID]struct{}
modIDToFile map[namer.ModuleID]string
schemaLoader *SchemaLoader
sfGroup singleflight.Group
stats storage.RepoStats
buildOpts buildOptions
mu sync.RWMutex
}
func (idx *index) GetFiles() []string {
idx.mu.RLock()
defer idx.mu.RUnlock()
files := make([]string, len(idx.fileToModID))
i := 0
for f := range idx.fileToModID {
files[i] = f
i++
}
return files
}
func (idx *index) GetFirstMatch(candidates []namer.ModuleID) (*policy.CompilationUnit, error) {
idx.mu.RLock()
defer idx.mu.RUnlock()
for _, id := range candidates {
if _, ok := idx.modIDToFile[id]; !ok {
continue
}
p, err := idx.loadPolicy(id)
if err != nil {
return nil, err
}
policyKey := namer.PolicyKey(p)
cu := &policy.CompilationUnit{
ModID: id,
Definitions: map[namer.ModuleID]*policyv1.Policy{id: p},
}
// add dependencies
if err := idx.addDepsToCompilationUnit(cu, id); err != nil {
return nil, fmt.Errorf("failed to load dependencies of %s: %w", policyKey, err)
}
// load ancestors of the policy
for _, ancestor := range cu.Ancestors() {
p, err := idx.loadPolicy(ancestor)
if err != nil {
return nil, fmt.Errorf("failed to load ancestor %q of scoped policy %s: %w", ancestor.String(), policyKey, err)
}
cu.AddDefinition(ancestor, p)
if err := idx.addDepsToCompilationUnit(cu, ancestor); err != nil {
return nil, fmt.Errorf("failed to load dependencies of ancestor %q of %s: %w", ancestor.String(), policyKey, err)
}
}
return cu, nil
}
return nil, nil
}
func (idx *index) GetCompilationUnits(ids ...namer.ModuleID) (map[namer.ModuleID]*policy.CompilationUnit, error) {
result := make(map[namer.ModuleID]*policy.CompilationUnit, len(ids))
idx.mu.RLock()
defer idx.mu.RUnlock()
for _, id := range ids {
if _, ok := idx.modIDToFile[id]; !ok {
continue
}
p, err := idx.loadPolicy(id)
if err != nil {
return nil, err
}
policyKey := namer.PolicyKey(p)
cu := &policy.CompilationUnit{
ModID: id,
Definitions: map[namer.ModuleID]*policyv1.Policy{id: p},
}
result[id] = cu
// add dependencies
if err := idx.addDepsToCompilationUnit(cu, id); err != nil {
return nil, fmt.Errorf("failed to load dependencies of %s: %w", policyKey, err)
}
// load ancestors of the policy
for _, ancestor := range cu.Ancestors() {
p, err := idx.loadPolicy(ancestor)
if err != nil {
return nil, fmt.Errorf("failed to load ancestor %q of scoped policy %s: %w", ancestor.String(), policyKey, err)
}
cu.AddDefinition(ancestor, p)
if err := idx.addDepsToCompilationUnit(cu, ancestor); err != nil {
return nil, fmt.Errorf("failed to load dependencies of ancestor %q of %s: %w", ancestor.String(), policyKey, err)
}
}
}
return result, nil
}
func (idx *index) addDepsToCompilationUnit(cu *policy.CompilationUnit, id namer.ModuleID) error {
deps, ok := idx.dependencies[id]
if !ok {
return nil
}
for dep := range deps {
_, ok := cu.Definitions[dep]
if !ok {
p, err := idx.loadPolicy(dep)
if err != nil {
return err
}
cu.AddDefinition(dep, p)
}
err := idx.addDepsToCompilationUnit(cu, dep)
if err != nil {
return err
}
}
return nil
}
func (idx *index) loadPolicy(id namer.ModuleID) (*policyv1.Policy, error) {
fileName, ok := idx.modIDToFile[id]
if !ok {
return nil, fmt.Errorf("policy id %q does not exist: %w", id.String(), ErrPolicyNotFound)
}
f, err := idx.fsys.Open(fileName)
if err != nil {
return nil, err
}
defer f.Close()
p, err := policy.ReadPolicy(f)
if err != nil {
return nil, err
}
return policy.WithMetadata(p, fileName, nil, fileName), nil
}
func (idx *index) GetDependents(ids ...namer.ModuleID) (map[namer.ModuleID][]namer.ModuleID, error) {
idx.mu.RLock()
defer idx.mu.RUnlock()
results := make(map[namer.ModuleID][]namer.ModuleID, len(ids))
for _, id := range ids {
set := make(map[namer.ModuleID]struct{})
idx.addTransitiveDependents(set, id)
list := make([]namer.ModuleID, len(set))
i := 0
for dependent := range set {
list[i] = dependent
i++
}
results[id] = list
}
return results, nil
}
func (idx *index) addTransitiveDependents(dependents map[namer.ModuleID]struct{}, id namer.ModuleID) {
for dependent := range idx.dependents[id] {
_, ok := dependents[dependent]
if !ok {
dependents[dependent] = struct{}{}
idx.addTransitiveDependents(dependents, dependent)
}
}
}
func (idx *index) AddOrUpdate(entry Entry) (evt storage.Event, err error) {
if entry.Policy.Policy == nil {
return storage.Event{Kind: storage.EventNop}, ErrInvalidEntry
}
modID := entry.Policy.ID
evt = storage.NewPolicyEvent(storage.EventAddOrUpdatePolicy, modID)
crudKind := "create"
idx.mu.Lock()
defer idx.mu.Unlock()
// Is this is a duplicate of another file?
if otherFile, ok := idx.modIDToFile[modID]; ok && otherFile != entry.File {
return evt, fmt.Errorf("policy is already defined in %s: %w", otherFile, ErrDuplicatePolicy)
}
// if this is an existing file, clear its state first
if oldModID, ok := idx.fileToModID[entry.File]; ok {
// go through the dependencies and remove self from the dependents list of each dependency.
if deps, ok := idx.dependencies[oldModID]; ok {
for dep := range deps {
if refs, ok := idx.dependents[dep]; ok {
delete(refs, oldModID)
}
}
}
delete(idx.dependencies, oldModID)
delete(idx.modIDToFile, oldModID)
delete(idx.executables, oldModID)
delete(idx.fileToModID, entry.File)
if oldModID != modID {
evt.OldPolicyID = &oldModID
}
crudKind = "update"
}
// add to index
idx.fileToModID[entry.File] = modID
idx.modIDToFile[modID] = entry.File
if entry.Policy.Kind != policy.DerivedRolesKind {
idx.executables[modID] = struct{}{}
}
for _, dep := range entry.Policy.Dependencies() {
idx.addDep(modID, dep)
}
statsCtx := context.Background()
stats.Record(statsCtx, metrics.IndexEntryCount.M(int64(len(idx.modIDToFile))))
_ = stats.RecordWithTags(statsCtx, []tag.Mutator{tag.Upsert(metrics.KeyIndexCRUDKind, crudKind)}, metrics.IndexCRUDCount.M(1))
return evt, nil
}
func (idx *index) addDep(child, parent namer.ModuleID) {
// When we compile a policy, we need to load the dependencies (imported variables and derived roles).
if _, ok := idx.dependencies[child]; !ok {
idx.dependencies[child] = make(map[namer.ModuleID]struct{})
}
idx.dependencies[child][parent] = struct{}{}
// if a derived role or variable export changes, we need to recompile all the policies that import it (dependents).
if _, ok := idx.dependents[parent]; !ok {
idx.dependents[parent] = make(map[namer.ModuleID]struct{})
}
idx.dependents[parent][child] = struct{}{}
}
func (idx *index) Delete(entry Entry) (storage.Event, error) {
idx.mu.Lock()
defer idx.mu.Unlock()
modID, ok := idx.fileToModID[entry.File]
if !ok {
// nothing to do because we don't have that file in the index.
return storage.Event{Kind: storage.EventNop}, nil
}
evt := storage.NewPolicyEvent(storage.EventDeleteOrDisablePolicy, modID)
// go through the dependencies and remove self from the dependents list for each dependency.
if deps, ok := idx.dependencies[modID]; ok {
for dep := range deps {
if refs, ok := idx.dependents[dep]; ok {
delete(refs, modID)
}
}
}
delete(idx.fileToModID, entry.File)
delete(idx.modIDToFile, modID)
delete(idx.dependencies, modID)
delete(idx.executables, modID)
statsCtx := context.Background()
stats.Record(statsCtx, metrics.IndexEntryCount.M(int64(len(idx.modIDToFile))))
_ = stats.RecordWithTags(statsCtx, []tag.Mutator{tag.Upsert(metrics.KeyIndexCRUDKind, "delete")}, metrics.IndexCRUDCount.M(1))
return evt, nil
}
func (idx *index) GetAllCompilationUnits(ctx context.Context) <-chan *policy.CompilationUnit {
idx.mu.RLock()
toCompile := make([]namer.ModuleID, 0, len(idx.executables))
for modID := range idx.modIDToFile {
if _, ok := idx.executables[modID]; ok {
toCompile = append(toCompile, modID)
continue
}
// is this a policy that is referenced by another one? If so, it will be implicitly compiled.
if dependents, ok := idx.dependents[modID]; ok && len(dependents) > 0 {
continue
}
// No implicit compilation for this policy so add it to the list
toCompile = append(toCompile, modID)
}
idx.mu.RUnlock()
outChan := make(chan *policy.CompilationUnit, 1)
go func() {
defer close(outChan)
for _, modID := range toCompile {
unit, err := idx.GetCompilationUnits(modID)
if err != nil {
continue
}
select {
case <-ctx.Done():
return
case outChan <- unit[modID]:
}
}
}()
return outChan
}
func (idx *index) Clear() error {
idx.mu.Lock()
defer idx.mu.Unlock()
idx.fsys = nil
idx.executables = nil
idx.modIDToFile = nil
idx.fileToModID = nil
idx.dependents = nil
idx.dependencies = nil
return nil
}
type meta struct {
Dependencies []string
Dependents []string
}
func (idx *index) Inspect() map[string]meta {
idx.mu.RLock()
defer idx.mu.RUnlock()
entries := make(map[string]meta, len(idx.fileToModID))
for file, modID := range idx.fileToModID {
m := meta{}
for dep := range idx.dependencies[modID] {
m.Dependencies = append(m.Dependencies, idx.modIDToFile[dep])
}
for ref := range idx.dependents[modID] {
m.Dependents = append(m.Dependents, idx.modIDToFile[ref])
}
entries[file] = m
}
return entries
}
func (idx *index) ListPolicyIDs(_ context.Context) ([]string, error) {
idx.mu.RLock()
defer idx.mu.RUnlock()
entries := make([]string, 0, len(idx.modIDToFile))
for _, f := range idx.modIDToFile {
entries = append(entries, f)
}
sort.Strings(entries)
return entries, nil
}
func (idx *index) ListSchemaIDs(ctx context.Context) ([]string, error) {
return idx.schemaLoader.ListIDs(ctx)
}
func (idx *index) LoadSchema(ctx context.Context, url string) (io.ReadCloser, error) {
return idx.schemaLoader.Load(ctx, url)
}
func (idx *index) LoadPolicy(_ context.Context, file ...string) ([]*policy.Wrapper, error) {
idx.mu.RLock()
defer idx.mu.RUnlock()
policies := make([]*policy.Wrapper, len(file))
for i, f := range file {
p, err := idx.loadPolicy(idx.fileToModID[f])
if err != nil {
return nil, fmt.Errorf("failed to load policy file with file path %s: %w", f, err)
}
pw := policy.Wrap(p)
policies[i] = &pw
}
return policies, nil
}
func (idx *index) RepoStats(_ context.Context) storage.RepoStats {
return idx.stats
}
func (idx *index) Reload(ctx context.Context) ([]storage.Event, error) {
log := ctxzap.Extract(ctx)
log.Info("Start index reload")
_, err, _ := idx.sfGroup.Do("reload", func() (any, error) {
idxIface, err := build(ctx, idx.fsys, idx.buildOpts)
if err != nil {
log.Error("Failed to build index while re-indexing")
return nil, err
}
newIdx, ok := idxIface.(*index)
if !ok {
return nil, err
}
idx.mu.Lock()
defer idx.mu.Unlock()
idx.fileToModID = newIdx.fileToModID
idx.executables = newIdx.executables
idx.dependents = newIdx.dependents
idx.dependencies = newIdx.dependencies
idx.modIDToFile = newIdx.modIDToFile
idx.schemaLoader = newIdx.schemaLoader
idx.stats = newIdx.stats
return nil, nil
})
if err != nil {
log.Warn("Index reload failed", zap.Error(err))
return nil, err
}
log.Info("Index reload successful")
return []storage.Event{storage.NewReloadEvent()}, nil
}
func (idx *index) Close() error {
if c, ok := idx.fsys.(io.Closer); ok {
return c.Close()
}
return nil
}