-
Notifications
You must be signed in to change notification settings - Fork 276
/
policy_evaluator.go
271 lines (237 loc) · 6.92 KB
/
policy_evaluator.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
package evaluator
import (
"context"
"fmt"
"strings"
"github.com/open-policy-agent/opa/rego"
octrace "go.opencensus.io/trace"
"github.com/pomerium/pomerium/authorize/internal/store"
"github.com/pomerium/pomerium/config"
"github.com/pomerium/pomerium/internal/log"
"github.com/pomerium/pomerium/internal/telemetry/trace"
"github.com/pomerium/pomerium/pkg/contextutil"
"github.com/pomerium/pomerium/pkg/cryptutil"
"github.com/pomerium/pomerium/pkg/policy"
"github.com/pomerium/pomerium/pkg/policy/criteria"
)
// PolicyRequest is the input to policy evaluation.
type PolicyRequest struct {
HTTP RequestHTTP `json:"http"`
Session RequestSession `json:"session"`
IsValidClientCertificate bool `json:"is_valid_client_certificate"`
}
// PolicyResponse is the result of evaluating a policy.
type PolicyResponse struct {
Allow, Deny RuleResult
Traces []contextutil.PolicyEvaluationTrace
}
// NewPolicyResponse creates a new PolicyResponse.
func NewPolicyResponse() *PolicyResponse {
return &PolicyResponse{
Allow: NewRuleResult(false),
Deny: NewRuleResult(false),
}
}
// A RuleResult is the result of evaluating a rule.
type RuleResult struct {
Value bool
Reasons criteria.Reasons
AdditionalData map[string]interface{}
}
// NewRuleResult creates a new RuleResult.
func NewRuleResult(value bool, reasons ...criteria.Reason) RuleResult {
return RuleResult{
Value: value,
Reasons: criteria.NewReasons(reasons...),
AdditionalData: map[string]interface{}{},
}
}
// MergeRuleResultsWithOr merges all the results using `or`.
func MergeRuleResultsWithOr(results ...RuleResult) RuleResult {
merged := NewRuleResult(false)
var trueResults, falseResults []RuleResult
for _, result := range results {
if result.Value {
trueResults = append(trueResults, result)
} else {
falseResults = append(falseResults, result)
}
}
if len(trueResults) > 0 {
merged.Value = true
for _, result := range trueResults {
merged.Reasons = merged.Reasons.Union(result.Reasons)
for k, v := range result.AdditionalData {
merged.AdditionalData[k] = v
}
}
} else {
merged.Value = false
for _, result := range falseResults {
merged.Reasons = merged.Reasons.Union(result.Reasons)
for k, v := range result.AdditionalData {
merged.AdditionalData[k] = v
}
}
}
return merged
}
type policyQuery struct {
rego.PreparedEvalQuery
script string
id string
explanation string
remediation string
}
func (q policyQuery) checksum() string {
return fmt.Sprintf("%x", cryptutil.Hash("script", []byte(q.script)))
}
// A PolicyEvaluator evaluates policies.
type PolicyEvaluator struct {
queries []policyQuery
policyChecksum uint64
}
// NewPolicyEvaluator creates a new PolicyEvaluator.
func NewPolicyEvaluator(
ctx context.Context, store *store.Store, configPolicy *config.Policy,
addDefaultClientCertificateRule bool,
) (*PolicyEvaluator, error) {
e := new(PolicyEvaluator)
e.policyChecksum = configPolicy.Checksum()
// generate the base rego script for the policy
ppl := configPolicy.ToPPL()
if addDefaultClientCertificateRule {
ppl.AddDefaultClientCertificateRule()
}
base, err := policy.GenerateRegoFromPolicy(ppl)
if err != nil {
return nil, err
}
e.queries = []policyQuery{{
script: base,
}}
// add any custom rego
for _, sp := range configPolicy.SubPolicies {
for _, src := range sp.Rego {
if src == "" {
continue
}
e.queries = append(e.queries, policyQuery{
script: src,
id: sp.ID,
explanation: sp.Explanation,
remediation: sp.Remediation,
})
}
}
// for each script, create a rego and prepare a query.
for i := range e.queries {
log.Debug(ctx).
Str("script", e.queries[i].script).
Str("from", configPolicy.From).
Interface("to", configPolicy.To).
Msg("authorize: rego script for policy evaluation")
r := rego.New(
rego.Store(store),
rego.Module("pomerium.policy", e.queries[i].script),
rego.Query("result = data.pomerium.policy"),
getGoogleCloudServerlessHeadersRegoOption,
store.GetDataBrokerRecordOption(),
)
q, err := r.PrepareForEval(ctx)
// if no package is in the src, add it
if err != nil && strings.Contains(err.Error(), "package expected") {
r := rego.New(
rego.Store(store),
rego.Module("pomerium.policy", "package pomerium.policy\n\n"+e.queries[i].script),
rego.Query("result = data.pomerium.policy"),
getGoogleCloudServerlessHeadersRegoOption,
store.GetDataBrokerRecordOption(),
)
q, err = r.PrepareForEval(ctx)
}
if err != nil {
return nil, err
}
e.queries[i].PreparedEvalQuery = q
}
return e, nil
}
// Evaluate evaluates the policy rego scripts.
func (e *PolicyEvaluator) Evaluate(ctx context.Context, req *PolicyRequest) (*PolicyResponse, error) {
res := NewPolicyResponse()
// run each query and merge the results
for _, query := range e.queries {
o, err := e.evaluateQuery(ctx, req, query)
if err != nil {
return nil, err
}
res.Allow = MergeRuleResultsWithOr(res.Allow, o.Allow)
res.Deny = MergeRuleResultsWithOr(res.Deny, o.Deny)
res.Traces = append(res.Traces, contextutil.PolicyEvaluationTrace{
ID: query.id,
Explanation: query.explanation,
Remediation: query.remediation,
Allow: o.Allow.Value,
Deny: o.Deny.Value,
})
}
return res, nil
}
func (e *PolicyEvaluator) evaluateQuery(ctx context.Context, req *PolicyRequest, query policyQuery) (*PolicyResponse, error) {
ctx, span := trace.StartSpan(ctx, "authorize.PolicyEvaluator.evaluateQuery")
defer span.End()
span.AddAttributes(octrace.StringAttribute("script_checksum", query.checksum()))
rs, err := safeEval(ctx, query.PreparedEvalQuery, rego.EvalInput(req))
if err != nil {
return nil, fmt.Errorf("authorize: error evaluating policy.rego: %w", err)
}
if len(rs) == 0 {
return nil, fmt.Errorf("authorize: unexpected empty result from evaluating policy.rego")
}
res := &PolicyResponse{
Allow: e.getRuleResult("allow", rs[0].Bindings),
Deny: e.getRuleResult("deny", rs[0].Bindings),
}
return res, nil
}
// getRuleResult gets the rule result var. It expects a boolean, [boolean, []string] or [boolean, []string, object].
func (e *PolicyEvaluator) getRuleResult(name string, vars rego.Vars) (result RuleResult) {
result = NewRuleResult(false)
m, ok := vars["result"].(map[string]interface{})
if !ok {
return result
}
switch t := m[name].(type) {
case bool:
result.Value = t
case []interface{}:
switch len(t) {
case 3:
v, ok := t[2].(map[string]interface{})
if ok {
for k, vv := range v {
result.AdditionalData[k] = vv
}
}
fallthrough
case 2:
// fill in the reasons
v, ok := t[1].([]interface{})
if ok {
for _, vv := range v {
result.Reasons.Add(criteria.Reason(fmt.Sprint(vv)))
}
}
fallthrough
case 1:
// fill in the value
v, ok := t[0].(bool)
if !ok {
return result
}
result.Value = v
}
}
return result
}