-
Notifications
You must be signed in to change notification settings - Fork 25
/
compiler.go
232 lines (195 loc) · 6.9 KB
/
compiler.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
package compiler
import (
"context"
"fmt"
"regexp"
"strings"
"github.com/open-policy-agent/opa/rego"
policylangv1 "github.com/fluxninja/aperture/v2/api/gen/proto/go/aperture/policy/language/v1"
policysyncv1 "github.com/fluxninja/aperture/v2/api/gen/proto/go/aperture/policy/sync/v1"
"github.com/fluxninja/aperture/v2/pkg/log"
"github.com/fluxninja/aperture/v2/pkg/policies/flowcontrol/resources/classifier/extractors"
)
const defaultPackageName = "fluxninja.classification.extractors"
// CompiledRuleset is compiled form of Classifier proto.
type CompiledRuleset struct {
Selectors []*policylangv1.Selector
Labelers []LabelerWithAttributes
ReportedRules []ReportedRule
}
// LabelerWithAttributes is a labeler with its attributes.
type LabelerWithAttributes struct {
Labeler *Labeler
ClassifierAttributes *policysyncv1.ClassifierAttributes
}
// Labeler is used to create flow labels.
type Labeler struct {
// rego query that is prepared to take envoy authz request as an input.
// Result expression should be a single value (if LabelName is set) or a
// map[string]interface{} otherwise.
Query rego.PreparedEvalQuery
// flags for created flow labels:
Labels map[string]LabelProperties
}
// LabelProperties is a set of properties for a label.
type LabelProperties struct {
Telemetry bool
}
// ReportedRule is a rule along with its selector and label name.
type ReportedRule struct {
Rule *policylangv1.Rule
RulesetName string
LabelName string
}
func rulesetToReportedRules(rs *policylangv1.Classifier, rulesetName string) []ReportedRule {
out := make([]ReportedRule, 0, len(rs.Rules))
for label, rule := range rs.Rules {
out = append(out, ReportedRule{
RulesetName: rulesetName,
LabelName: label,
Rule: rule,
})
}
return out
}
// BadExtractor is an error occurring when extractor is invalid.
var BadExtractor = extractors.BadExtractor
// BadRego is an error occurring when rego compilation fails.
var BadRego = badRego{}
type badRego struct{}
func (b badRego) Error() string { return "failed to compile rego" }
// BadSelector is an error occurring when selector is invalid.
var BadSelector = badSelector{}
type badSelector struct{}
func (b badSelector) Error() string { return "invalid ruleset selector" }
// BadLabelName is an error occurring when label name is invalid.
var BadLabelName = extractors.BadLabelName
// CompileRuleset parses ruleset's selector and compiles its rules.
func CompileRuleset(ctx context.Context, name string, classifierWrapper *policysyncv1.ClassifierWrapper) (CompiledRuleset, error) {
classifierMsg := classifierWrapper.GetClassifier()
labelers, err := compileRules(ctx, classifierWrapper)
if err != nil {
return CompiledRuleset{}, fmt.Errorf("failed to compile %q rules: %w", name, err)
}
cr := CompiledRuleset{
Selectors: classifierMsg.GetSelectors(),
Labelers: labelers,
ReportedRules: rulesetToReportedRules(classifierMsg, name),
}
return cr, nil
}
// compileRules compiles a set of rules into set of rego queries
//
// Raw rego rules are compiled 1:1 to rego queries. High-level extractor-based
// rules are compiled into a single rego query.
func compileRules(ctx context.Context, classifierWrapper *policysyncv1.ClassifierWrapper) ([]LabelerWithAttributes, error) {
log.Trace().Msg("Classifier.compileRules starting")
classifierAttributes := classifierWrapper.GetClassifierAttributes()
if classifierAttributes == nil {
return nil, fmt.Errorf("commonAttributes is nil")
}
var labelers []LabelerWithAttributes
labelRules := classifierWrapper.GetClassifier().GetRules()
if len(labelRules) > 0 {
// Group all the extractor-based rules so that we can compile them to a
// single rego query
labelExtractors := map[string]*policylangv1.Extractor{}
labelsProperties := map[string]LabelProperties{} // Telemetry flag for labels created by extractors
rawRegoCount := 0
for labelName, rule := range labelRules {
if strings.Contains(labelName, "/") {
// Forbidding '/' in case we want to support multiple rules for the
// same label:
// labels:
// user/1: <snip>
// user/2: <snip>
return nil, fmt.Errorf("%w: cannot contain '/'", BadLabelName)
}
switch source := rule.GetSource().(type) {
case *policylangv1.Rule_Extractor:
labelExtractors[labelName] = source.Extractor
labelsProperties[labelName] = LabelProperties{
Telemetry: rule.GetTelemetry(),
}
}
}
if len(labelExtractors) != 0 {
regoSrc, err := extractors.CompileToRego(defaultPackageName, labelExtractors)
if err != nil {
return nil, fmt.Errorf("failed to compile extractors to rego: %w", err)
}
query, err := rego.New(
rego.Query("data."+defaultPackageName),
rego.Module("tmp.rego", regoSrc),
).PrepareForEval(ctx)
if err != nil {
// Note: Not wrapping BadRego error here – the rego returned by
// compileExtractors should always be valid, otherwise it is a
// bug, and not user's fault.
log.Trace().Str("src", regoSrc).Msg("Failed to prepare for eval")
return nil, fmt.Errorf("(bug) failed to compile classification rules: %w", err)
}
labelers = append(labelers, LabelerWithAttributes{
Labeler: &Labeler{
Query: query,
Labels: labelsProperties,
},
ClassifierAttributes: classifierAttributes,
})
}
log.Debug().
Int("raw rego modules", rawRegoCount).
Int("extractors", len(labelExtractors)).
Msg("Compilation of extractor rules finished")
}
// compile rego rules
r := classifierWrapper.GetClassifier().GetRego()
if r != nil {
module := r.GetModule()
labels := r.GetLabels()
labelsProperties := map[string]LabelProperties{}
for labelKey, lp := range labels {
if !extractors.IsRegoIdent(labelKey) {
return nil, fmt.Errorf("%w: %q is not a valid label name", BadLabelName, labelKey)
}
labelsProperties[labelKey] = LabelProperties{
Telemetry: lp.Telemetry,
}
}
// get package name in module
// package name is specified in a line like "package foo"
p := regexp.MustCompile(`package\s+(\S+)`)
m := p.FindStringSubmatch(module)
if len(m) != 2 {
return nil, fmt.Errorf("failed to get package name from rego module")
}
packageName := m[1]
// compile rego module and queries
query, err := rego.New(rego.Query("data."+packageName),
rego.Module("tmp.rego", module)).PrepareForEval(ctx)
if err != nil {
log.Trace().Str("src", r.GetModule()).Msg("Failed to prepare for eval")
return nil, fmt.Errorf(
"failed to compile raw rego module, query: %s: %w: %v",
r.GetModule(),
BadRego,
err,
)
}
// add to labelers
labelers = append(labelers, LabelerWithAttributes{
Labeler: &Labeler{
Query: query,
Labels: labelsProperties,
},
ClassifierAttributes: classifierAttributes,
})
log.Debug().
Int("extractors", len(labels)).
Msg("Compilation of rego finished")
}
log.Debug().
Int("labelers", len(labelers)).
Msg("Compilation finished")
return labelers, nil
}