forked from coder/coder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthz.go
More file actions
322 lines (279 loc) · 9.12 KB
/
authz.go
File metadata and controls
322 lines (279 loc) · 9.12 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
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
package rbac
import (
"context"
_ "embed"
"sync"
"time"
"github.com/open-policy-agent/opa/rego"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"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"
"github.com/coder/coder/coderd/util/slice"
)
// Subject is a struct that contains all the elements of a subject in an rbac
// authorize.
type Subject struct {
ID string
Roles ExpandableRoles
Groups []string
Scope ExpandableScope
}
func (s Subject) Equal(b Subject) bool {
if s.ID != b.ID {
return false
}
if !slice.SameElements(s.Groups, b.Groups) {
return false
}
if !slice.SameElements(s.SafeRoleNames(), b.SafeRoleNames()) {
return false
}
if s.SafeScopeName() != b.SafeScopeName() {
return false
}
return true
}
// SafeScopeName prevent nil pointer dereference.
func (s Subject) SafeScopeName() string {
if s.Scope == nil {
return "no-scope"
}
return s.Scope.Name()
}
// SafeRoleNames prevent nil pointer dereference.
func (s Subject) SafeRoleNames() []string {
if s.Roles == nil {
return []string{}
}
return s.Roles.Names()
}
type Authorizer interface {
Authorize(ctx context.Context, subject Subject, action Action, object Object) error
Prepare(ctx context.Context, subject Subject, action Action, objectType string) (PreparedAuthorized, error)
}
type PreparedAuthorized interface {
Authorize(ctx context.Context, object Object) error
CompileToSQL(ctx context.Context, cfg regosql.ConvertConfig) (string, error)
}
// Filter takes in a list of objects, and will filter the list removing all
// the elements the subject does not have permission for. All objects must be
// of the same type.
//
// Ideally the 'CompileToSQL' is used instead for large sets. This cost scales
// linearly with the number of objects passed in.
func Filter[O Objecter](ctx context.Context, auth Authorizer, subject Subject, action Action, objects []O) ([]O, error) {
if len(objects) == 0 {
// Nothing to filter
return objects, nil
}
objectType := objects[0].RBACObject().Type
filtered := make([]O, 0)
// Start the span after the object type is detected. If we are filtering 0
// objects, then the span is not interesting. It would just add excessive
// 0 time spans that provide no insight.
ctx, span := tracing.StartSpan(ctx,
rbacTraceAttributes(subject, action, objectType,
// For filtering, we are only measuring the total time for the entire
// set of objects. This and the 'Prepare' span time
// is all that is required to measure the performance of this
// function on a per-object basis.
attribute.Int("num_objects", len(objects)),
),
)
defer span.End()
// Running benchmarks on this function, it is **always** faster to call
// auth.Authorize on <10 objects. This is because the overhead of
// 'Prepare'. Once we cross 10 objects, then it starts to become
// faster
if len(objects) < 10 {
for _, o := range objects {
rbacObj := o.RBACObject()
if rbacObj.Type != objectType {
return nil, xerrors.Errorf("object types must be uniform across the set (%s), found %s", objectType, rbacObj)
}
err := auth.Authorize(ctx, subject, action, o.RBACObject())
if err == nil {
filtered = append(filtered, o)
}
}
return filtered, nil
}
prepared, err := auth.Prepare(ctx, subject, action, objectType)
if err != nil {
return nil, xerrors.Errorf("prepare: %w", err)
}
for _, object := range objects {
rbacObj := object.RBACObject()
if rbacObj.Type != objectType {
return nil, xerrors.Errorf("object types must be uniform across the set (%s), found %s", objectType, object.RBACObject().Type)
}
err := prepared.Authorize(ctx, rbacObj)
if err == nil {
filtered = append(filtered, object)
}
}
return filtered, nil
}
// RegoAuthorizer will use a prepared rego query for performing authorize()
type RegoAuthorizer struct {
query rego.PreparedEvalQuery
authorizeHist *prometheus.HistogramVec
prepareHist prometheus.Histogram
}
var _ Authorizer = (*RegoAuthorizer)(nil)
var (
// Load the policy from policy.rego in this directory.
//
//go:embed policy.rego
policy string
queryOnce sync.Once
query rego.PreparedEvalQuery
)
func NewAuthorizer(registry prometheus.Registerer) *RegoAuthorizer {
queryOnce.Do(func() {
var err error
query, err = rego.New(
rego.Query("data.authz.allow"),
rego.Module("policy.rego", policy),
).PrepareForEval(context.Background())
if err != nil {
panic(xerrors.Errorf("compile rego: %w", err))
}
})
// Register metrics to prometheus.
// These bucket values are based on the average time it takes to run authz
// being around 1ms. Anything under ~2ms is OK and does not need to be
// analyzed any further.
buckets := []float64{
0.0005, // 0.5ms
0.001, // 1ms
0.002, // 2ms
0.003,
0.005,
0.01, // 10ms
0.02,
0.035, // 35ms
0.05,
0.075,
0.1, // 100ms
0.25, // 250ms
0.75, // 750ms
1, // 1s
}
factory := promauto.With(registry)
authorizeHistogram := factory.NewHistogramVec(prometheus.HistogramOpts{
Namespace: "coderd",
Subsystem: "authz",
Name: "authorize_duration_seconds",
Help: "Duration of the 'Authorize' call in seconds. Only counts calls that succeed.",
Buckets: buckets,
}, []string{"allowed"})
prepareHistogram := factory.NewHistogram(prometheus.HistogramOpts{
Namespace: "coderd",
Subsystem: "authz",
Name: "prepare_authorize_duration_seconds",
Help: "Duration of the 'PrepareAuthorize' call in seconds.",
Buckets: buckets,
})
return &RegoAuthorizer{
query: query,
authorizeHist: authorizeHistogram,
prepareHist: prepareHistogram,
}
}
type authSubject struct {
ID string `json:"id"`
Roles []Role `json:"roles"`
Groups []string `json:"groups"`
Scope Scope `json:"scope"`
}
// Authorize is the intended function to be used outside this package.
// It returns `nil` if the subject is authorized to perform the action on
// the object.
// If an error is returned, the authorization is denied.
func (a RegoAuthorizer) Authorize(ctx context.Context, subject Subject, action Action, object Object) error {
start := time.Now()
ctx, span := tracing.StartSpan(ctx,
trace.WithTimestamp(start), // Reuse the time.Now for metric and trace
rbacTraceAttributes(subject, action, object.Type,
// For authorizing a single object, this data is useful to know how
// complex our objects are getting.
attribute.Int("object_num_groups", len(object.ACLGroupList)),
attribute.Int("object_num_users", len(object.ACLUserList)),
),
)
defer span.End()
err := a.authorize(ctx, subject, action, object)
span.SetAttributes(attribute.Bool("authorized", err == nil))
dur := time.Since(start)
if err != nil {
a.authorizeHist.WithLabelValues("false").Observe(dur.Seconds())
return err
}
a.authorizeHist.WithLabelValues("true").Observe(dur.Seconds())
return nil
}
// authorize is the internal function that does the actual authorization.
// It is a different function so the exported one can add tracing + metrics.
// That code tends to clutter up the actual logic, so it's separated out.
// nolint:revive
func (a RegoAuthorizer) authorize(ctx context.Context, subject Subject, action Action, object Object) error {
if subject.Roles == nil {
return xerrors.Errorf("subject must have roles")
}
if subject.Scope == nil {
return xerrors.Errorf("subject must have a scope")
}
subjRoles, err := subject.Roles.Expand()
if err != nil {
return xerrors.Errorf("expand roles: %w", err)
}
subjScope, err := subject.Scope.Expand()
if err != nil {
return xerrors.Errorf("expand scope: %w", err)
}
input := map[string]interface{}{
"subject": authSubject{
ID: subject.ID,
Roles: subjRoles,
Groups: subject.Groups,
Scope: subjScope,
},
"object": object,
"action": action,
}
results, err := a.query.Eval(ctx, rego.EvalInput(input))
if err != nil {
return ForbiddenWithInternal(xerrors.Errorf("eval rego: %w", err), input, results)
}
if !results.Allowed() {
return ForbiddenWithInternal(xerrors.Errorf("policy disallows request"), input, results)
}
return nil
}
// Prepare will partially execute the rego policy leaving the object fields unknown (except for the type).
// This will vastly speed up performance if batch authorization on the same type of objects is needed.
func (a RegoAuthorizer) Prepare(ctx context.Context, subject Subject, action Action, objectType string) (PreparedAuthorized, error) {
start := time.Now()
ctx, span := tracing.StartSpan(ctx,
trace.WithTimestamp(start),
rbacTraceAttributes(subject, action, objectType),
)
defer span.End()
prepared, err := newPartialAuthorizer(ctx, subject, action, objectType)
if err != nil {
return nil, xerrors.Errorf("new partial authorizer: %w", err)
}
// Add attributes of the Prepare results. This will help understand the
// complexity of the roles and how it affects the time taken.
span.SetAttributes(
attribute.Int("num_queries", len(prepared.preparedQueries)),
attribute.Bool("always_true", prepared.alwaysTrue),
)
a.prepareHist.Observe(time.Since(start).Seconds())
return prepared, nil
}