forked from coder/coder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpartial.go
More file actions
202 lines (177 loc) · 6.34 KB
/
partial.go
File metadata and controls
202 lines (177 loc) · 6.34 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
package rbac
import (
"context"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/rego"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"golang.org/x/xerrors"
"github.com/coder/coder/coderd/rbac/regosql"
"github.com/coder/coder/coderd/tracing"
)
type PartialAuthorizer struct {
// partialQueries is mainly used for unit testing to assert our rego policy
// can always be compressed into a set of queries.
partialQueries *rego.PartialQueries
// input is used purely for debugging and logging.
input map[string]interface{}
// preparedQueries are the compiled set of queries after partial evaluation.
// Cache these prepared queries to avoid re-compiling the queries.
// If alwaysTrue is true, then ignore these.
preparedQueries []rego.PreparedEvalQuery
// alwaysTrue is if the subject can always perform the action on the
// resource type, regardless of the unknown fields.
alwaysTrue bool
}
var _ PreparedAuthorized = (*PartialAuthorizer)(nil)
func (pa *PartialAuthorizer) CompileToSQL(ctx context.Context, cfg regosql.ConvertConfig) (string, error) {
_, span := tracing.StartSpan(ctx, trace.WithAttributes(
// Query count is a rough indicator of the complexity of the query
// that needs to be converted into SQL.
attribute.Int("query_count", len(pa.preparedQueries)),
attribute.Bool("always_true", pa.alwaysTrue),
))
defer span.End()
filter, err := Compile(cfg, pa)
if err != nil {
return "", xerrors.Errorf("compile: %w", err)
}
return filter.SQLString(), nil
}
func (pa *PartialAuthorizer) Authorize(ctx context.Context, object Object) error {
if pa.alwaysTrue {
return nil
}
// If we have no queries, then no queries can return 'true'.
// So the result is always 'false'.
if len(pa.preparedQueries) == 0 {
return ForbiddenWithInternal(xerrors.Errorf("policy disallows request"), pa.input, nil)
}
parsed, err := ast.InterfaceToValue(map[string]interface{}{
"object": object,
})
if err != nil {
return xerrors.Errorf("parse object: %w", err)
}
// How to interpret the results of the partial queries.
// We have a list of queries that are along the lines of:
// `input.object.org_owner = ""; "me" = input.object.owner`
// `input.object.org_owner in {"feda2e52-8bf1-42ce-ad75-6c5595cb297a"} `
// All these queries are joined by an 'OR'. So we need to run through each
// query, and evaluate it.
//
// In each query, we have a list of the expressions, which should be
// all boolean expressions. In the above 1st example, there are 2.
// These expressions within a single query are `AND` together by rego.
EachQueryLoop:
for _, q := range pa.preparedQueries {
// We need to eval each query with the newly known fields.
results, err := q.Eval(ctx, rego.EvalParsedInput(parsed))
if err != nil {
continue EachQueryLoop
}
// If there are no results, then the query is false. This is because rego
// treats false queries as "undefined". So if any expression is false, the
// result is an empty list.
if len(results) == 0 {
continue EachQueryLoop
}
// If there is more than 1 result, that means there is more than 1 rule.
// This should not happen, because our query should always be an expression.
// If this every occurs, it is likely the original query was not an expression.
if len(results) > 1 {
continue EachQueryLoop
}
// Our queries should be simple, and should not yield any bindings.
// A binding is something like 'x := 1'. This binding as an expression is
// 'true', but in our case is unhelpful. We are not analyzing this ast to
// map bindings. So just error out. Similar to above, our queries should
// always be boolean expressions.
if len(results[0].Bindings) > 0 {
continue EachQueryLoop
}
// We have a valid set of boolean expressions! All expressions are 'AND'd
// together. This is automatic by rego, so we should not actually need to
// inspect this any further. But just in case, we will verify each expression
// did resolve to 'true'. This is purely defensive programming.
for _, exp := range results[0].Expressions {
if v, ok := exp.Value.(bool); !ok || !v {
continue EachQueryLoop
}
}
return nil
}
return ForbiddenWithInternal(xerrors.Errorf("policy disallows request"), pa.input, nil)
}
func newPartialAuthorizer(ctx context.Context, subject Subject, action Action, objectType string) (*PartialAuthorizer, error) {
if subject.Roles == nil {
return nil, xerrors.Errorf("subject must have roles")
}
if subject.Scope == nil {
return nil, xerrors.Errorf("subject must have a scope")
}
roles, err := subject.Roles.Expand()
if err != nil {
return nil, xerrors.Errorf("expand roles: %w", err)
}
scope, err := subject.Scope.Expand()
if err != nil {
return nil, xerrors.Errorf("expand scope: %w", err)
}
input := map[string]interface{}{
"subject": authSubject{
ID: subject.ID,
Roles: roles,
Scope: scope,
Groups: subject.Groups,
},
"object": map[string]string{
"type": objectType,
},
"action": action,
}
// Run the rego policy with a few unknown fields. This should simplify our
// policy to a set of queries.
partialQueries, err := rego.New(
rego.Query("data.authz.allow = true"),
rego.Module("policy.rego", policy),
rego.Unknowns([]string{
"input.object.id",
"input.object.owner",
"input.object.org_owner",
"input.object.acl_user_list",
"input.object.acl_group_list",
}),
rego.Input(input),
).Partial(ctx)
if err != nil {
return nil, xerrors.Errorf("prepare: %w", err)
}
pAuth := &PartialAuthorizer{
partialQueries: partialQueries,
preparedQueries: []rego.PreparedEvalQuery{},
input: input,
}
// Prepare each query to optimize the runtime when we iterate over the objects.
preparedQueries := make([]rego.PreparedEvalQuery, 0, len(partialQueries.Queries))
for _, q := range partialQueries.Queries {
if q.String() == "" {
// No more work needed. An empty query is the same as
// 'WHERE true'
// This is likely an admin. We don't even need to use rego going
// forward.
pAuth.alwaysTrue = true
preparedQueries = []rego.PreparedEvalQuery{}
break
}
results, err := rego.New(
rego.ParsedQuery(q),
).PrepareForEval(ctx)
if err != nil {
return nil, xerrors.Errorf("prepare query %s: %w", q.String(), err)
}
preparedQueries = append(preparedQueries, results)
}
pAuth.preparedQueries = preparedQueries
return pAuth, nil
}