-
Notifications
You must be signed in to change notification settings - Fork 10
/
engine.go
323 lines (290 loc) · 9.67 KB
/
engine.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
// Copyright 2022-2023 Snyk Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package engine
import (
"context"
"fmt"
"sort"
"github.com/open-policy-agent/opa/rego"
"github.com/snyk/policy-engine/pkg/bundle"
"github.com/snyk/policy-engine/pkg/bundle/base"
"github.com/snyk/policy-engine/pkg/data"
"github.com/snyk/policy-engine/pkg/logging"
"github.com/snyk/policy-engine/pkg/metrics"
"github.com/snyk/policy-engine/pkg/models"
"github.com/snyk/policy-engine/pkg/policy"
)
// Engine is responsible for evaluating some States with a given set of rules.
type Engine struct {
// InitializationErrors contains any errors that occurred during initialization.
InitializationErrors []error
instrumentation *engineInstrumentation
policySets []*policySet
}
// EngineOptions contains options for initializing an Engine instance
type EngineOptions struct {
// Providers contains functions that produce parsed OPA modules or data documents.
Providers []data.Provider
// Providers contains bundle.Reader objects that produce parsed bundles.
BundleReaders []bundle.Reader
// Logger is an optional instance of the logger.Logger interface
Logger logging.Logger
// Metrics is an optional instance of the metrics.Metrics interface
Metrics metrics.Metrics
}
// NewEngine constructs a new Engine instance.
func NewEngine(ctx context.Context, options *EngineOptions) *Engine {
logger := options.Logger
if logger == nil {
logger = logging.NopLogger
}
m := options.Metrics
if m == nil {
m = metrics.NewLocalMetrics(logger)
}
eng := &Engine{
instrumentation: &engineInstrumentation{
instrumentation: newInstrumentation(instrumentationOptions{
component: "policy_engine",
logger: logger,
metrics: m,
}),
},
}
eng.instrumentation.startInitialization(ctx)
eng.initPolicySets(ctx, options.Providers, options.BundleReaders)
eng.instrumentation.finishInitialization(ctx, eng)
return eng
}
func (e *Engine) initPolicySets(ctx context.Context, providers []data.Provider, readers []bundle.Reader) {
e.instrumentation.startInitializePolicySets(ctx)
if len(providers) > 0 {
policySet, err := newPolicySet(ctx, policySetOptions{
providers: providers,
source: POLICY_SOURCE_DATA,
instrumentation: e.instrumentation.child(
metrics.Labels{
"policy_set_source": string(POLICY_SOURCE_DATA),
},
info,
withField("policy_set_source", string(POLICY_SOURCE_DATA)),
),
})
if err != nil {
e.InitializationErrors = append(e.InitializationErrors, err)
} else {
e.policySets = append(e.policySets, policySet)
}
}
for _, r := range readers {
sourceInfo := r.Info()
var policySource PolicySource
if sourceInfo.SourceType == bundle.ARCHIVE {
policySource = POLICY_SOURCE_BUNDLE_ARCHIVE
} else if sourceInfo.SourceType == bundle.DIRECTORY {
policySource = POLICY_SOURCE_BUNDLE_DIRECTORY
}
b, err := bundle.ReadBundle(r)
if err != nil {
e.InitializationErrors = append(e.InitializationErrors,
newRuleBundleError(
&models.RuleBundle{
Name: sourceInfo.FileInfo.Path,
Source: string(policySource),
Checksum: sourceInfo.FileInfo.Checksum,
},
fmt.Errorf("%w: %v", ErrFailedToReadBundle, err),
))
continue
}
policySet, err := newPolicySet(ctx, policySetOptions{
providers: []data.Provider{b.Provider()},
source: policySource,
name: sourceInfo.FileInfo.Path,
checksum: sourceInfo.FileInfo.Checksum,
instrumentation: e.instrumentation.policySetInstrumentation(
string(policySource),
sourceInfo,
),
})
if err != nil {
e.InitializationErrors = append(e.InitializationErrors, err)
continue
}
e.policySets = append(e.policySets, policySet)
}
e.instrumentation.finishInitializePolicySets(ctx)
}
type policyResults struct {
err error
ruleResults []models.RuleResults
}
// EvalOptions contains options for Engine.Eval
type EvalOptions struct {
// Inputs are the State instances that the engine should evaluate.
Inputs []models.State
// Workers sets how many policies are to be evaluated concurrently. When
// unset or set to a value less than 1, this defaults to the number of CPU
// cores - 1.
Workers int
// ResourceResolver is a function that returns a resource state for the given
// ResourceRequest.
// Multiple ResourcesResolvers can be composed with And() and Or().
ResourcesResolver policy.ResourcesResolver
// RuleIDs determines which rules are executed. When this option is empty or
// unspecified, all rules will be run.
RuleIDs []string
}
// Eval evaluates the given states using the rules that the engine was initialized with.
func (e *Engine) Eval(ctx context.Context, options *EvalOptions) *models.Results {
e.instrumentation.startEvaluate(ctx)
results := []models.Result{}
for _, input := range options.Inputs {
loggerFields := inputFields(&input)
e.instrumentation.startEvaluateInput(ctx, loggerFields)
allRuleResults := []models.RuleResults{}
totalResults := 0
for _, p := range e.policySets {
ruleResults := p.eval(ctx, ¶llelEvalOptions{
resourcesResolver: options.ResourcesResolver,
regoOptions: []func(*rego.Rego){
rego.StrictBuiltinErrors(true),
},
input: &input,
ruleIDs: options.RuleIDs,
workers: options.Workers,
loggerFields: loggerFields,
})
allRuleResults = append(allRuleResults, ruleResults...)
for _, r := range ruleResults {
totalResults += len(r.Results)
}
}
// Ensure deterministic output.
sort.Slice(allRuleResults, func(i, j int) bool {
return allRuleResults[i].Package_ < allRuleResults[j].Package_
})
results = append(results, models.Result{
Input: input,
RuleResults: allRuleResults,
})
loggerFields = append(loggerFields,
withField("policies", len(allRuleResults)),
withField("results", totalResults),
)
e.instrumentation.finishEvaluateInput(ctx, loggerFields)
}
e.instrumentation.finishEvaluate(ctx)
ruleBundles := []models.RuleBundleInfo{}
for _, p := range e.policySets {
ruleBundles = append(ruleBundles, models.RuleBundleInfo{
RuleBundle: p.ruleBundle(),
})
}
for _, err := range e.InitializationErrors {
if err, ok := err.(*RuleBundleError); ok {
ruleBundles = append(ruleBundles, err.ToModel())
}
}
return &models.Results{
Format: "results",
FormatVersion: "1.2.0",
Results: results,
RuleBundles: ruleBundles,
}
}
type MetadataResult struct {
Package string `json:"package"`
Metadata policy.Metadata `json:"metadata"`
Error string `json:"error,omitempty"`
}
// Metadata returns the metadata of all Policies that have been loaded into this
// Engine instance.
func (e *Engine) Metadata(ctx context.Context) []MetadataResult {
metadata := []MetadataResult{}
for _, p := range e.policySets {
m := p.metadata(ctx, []func(*rego.Rego){
rego.StrictBuiltinErrors(true),
})
metadata = append(metadata, m...)
}
// Ensure a consistent ordering for policies to make our output
// deterministic.
sort.Slice(metadata, func(i, j int) bool {
return metadata[i].Package < metadata[j].Package
})
return metadata
}
type engineInstrumentation struct {
instrumentation
}
func (i *engineInstrumentation) startInitialization(ctx context.Context) {
i.startPhase(ctx, "initialize_engine")
}
func (i *engineInstrumentation) finishInitialization(ctx context.Context, eng *Engine) {
i.finishPhase(ctx, "initialize_engine",
withField("policy_sets", len(eng.policySets)),
withField("errors", len(eng.InitializationErrors)),
)
}
func (i *engineInstrumentation) startInitializePolicySets(ctx context.Context) {
i.startPhase(ctx, "initialize_policy_sets")
}
func (i *engineInstrumentation) finishInitializePolicySets(ctx context.Context) {
i.finishPhase(ctx, "initialize_policy_sets")
}
func (i *engineInstrumentation) startEvaluate(ctx context.Context) {
i.startPhase(ctx, "evaluate_all_inputs")
}
func (i *engineInstrumentation) finishEvaluate(ctx context.Context) {
i.finishPhase(ctx, "evaluate_all_inputs")
}
func (i *engineInstrumentation) startEvaluateInput(ctx context.Context, fields []loggerOption) {
i.startPhase(ctx, "evaluate_inputs", fields...)
}
func (i *engineInstrumentation) finishEvaluateInput(ctx context.Context, fields []loggerOption) {
i.finishPhase(ctx, "evaluate_inputs", fields...)
}
func (i *engineInstrumentation) policySetInstrumentation(policySource string, sourceInfo base.SourceInfo) instrumentation {
labels := metrics.Labels{
"policy_set_source": policySource,
"policy_set_name": sourceInfo.FileInfo.Path,
}
fields := []loggerOption{
withField("policy_set_source", policySource),
withField("policy_set_name", sourceInfo.FileInfo.Path),
}
if sourceInfo.FileInfo.Checksum != "" {
labels["policy_set_checksum"] = sourceInfo.FileInfo.Checksum
fields = append(fields, withField("policy_set_checksum", sourceInfo.FileInfo.Checksum))
}
return i.child(
labels,
info,
fields...,
)
}
func inputFields(input *models.State) []loggerOption {
resourceTypes := len(input.Resources)
resources := 0
for _, rt := range input.Resources {
resources += len(rt)
}
return []loggerOption{
withField("input_type", input.InputType),
withField("scope", input.Scope),
withField("resource_types", resourceTypes),
withField("resources", resources),
}
}