/
opa.go
350 lines (276 loc) · 8.31 KB
/
opa.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package opa
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"sync"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/open-policy-agent/opa/rego"
"github.com/open-policy-agent/opa/server/types"
"github.com/prometheus/client_golang/prometheus"
"github.com/observatorium/api/rbac"
)
const (
contentTypeHeader = "Content-Type"
xForwardedAccessTokenHeader = "X-Forwarded-Access-Token" //nolint:gosec
)
// regoFunctions map is used for the providers' self-registration.
var regoFunctions map[string]func(log.Logger) func(*rego.Rego)
// regoFunctionsMtx is used to protect the providerFactories.
var regoFunctionsMtx sync.RWMutex
func init() {
regoFunctions = make(map[string]func(log.Logger) func(*rego.Rego))
}
// onboardNewFunction is used by pluggable custom functions to register theirself.
func onboardNewFunction(regoFunctionName string, regoFunction func(log.Logger) func(*rego.Rego)) {
regoFunctionsMtx.Lock()
defer regoFunctionsMtx.Unlock()
regoFunctions[regoFunctionName] = regoFunction
}
// Input models the data that is used for OPA input documents.
type Input struct {
Groups []string `json:"groups"`
Permission rbac.Permission `json:"permission"`
Resource string `json:"resource"`
Subject string `json:"subject"`
Tenant string `json:"tenant"`
TenantID string `json:"tenantID"`
Token string `json:"token"`
Extras *rbac.ExtraAttributes `json:"extras,omitempty"`
}
type config struct {
logger log.Logger
registerer prometheus.Registerer
withAccessToken bool
}
// Option modifies the configuration of an OPA authorizer.
type Option func(c *config)
// LoggerOption sets a custom logger for the authorizer.
func LoggerOption(logger log.Logger) Option {
return func(c *config) {
c.logger = logger
}
}
// AccessTokenOptions sets the flag for the access token requirement.
func AccessTokenOption(f bool) Option {
return func(c *config) {
c.withAccessToken = f
}
}
// RegistererOption sets a Prometheus registerer for the authorizer.
func RegistererOption(r prometheus.Registerer) Option {
return func(c *config) {
c.registerer = r
}
}
type restAuthorizer struct {
client *http.Client
url *url.URL
logger log.Logger
registerer prometheus.Registerer
withAccessToken bool
}
// Authorize implements the rbac.Authorizer interface.
func (a *restAuthorizer) Authorize(
subject string,
groups []string,
permission rbac.Permission,
resource, tenant, tenantID, token string,
extras *rbac.ExtraAttributes,
) (int, bool, string) {
var i interface{} = Input{
Groups: groups,
Permission: permission,
Resource: resource,
Subject: subject,
Tenant: tenant,
TenantID: tenantID,
Extras: extras,
}
dreq := types.DataRequestV1{
Input: &i,
}
j, err := json.Marshal(dreq)
if err != nil {
level.Error(a.logger).Log("msg", "failed to marshal OPA input to JSON", "err", err.Error())
return http.StatusForbidden, false, ""
}
req, err := http.NewRequest(http.MethodPost, a.url.String(), bytes.NewBuffer(j))
if err != nil {
level.Error(a.logger).Log("msg", "failed to build authorization request", "err", err.Error())
return http.StatusInternalServerError, false, ""
}
req.Header.Set(contentTypeHeader, "application/json")
if a.withAccessToken {
if token == "" {
level.Error(a.logger).Log("msg", "failed to forward access token to authorization request")
return http.StatusInternalServerError, false, ""
}
req.Header.Set(xForwardedAccessTokenHeader, token)
}
res, err := a.client.Do(req)
if err != nil {
level.Error(a.logger).Log("msg", "make request to OPA endpoint", "URL", a.url.String(), "err", err.Error())
if res == nil {
return http.StatusInternalServerError, false, ""
}
return res.StatusCode, false, ""
}
if res.StatusCode/100 != 2 {
body, _ := io.ReadAll(res.Body)
res.Body.Close()
level.Error(a.logger).Log(
"msg", "received non-200 status code from OPA endpoint",
"URL", a.url.String(),
"body", body,
"status", res.Status,
)
return res.StatusCode, false, ""
}
dres := types.DataResponseV1{}
if err := json.NewDecoder(res.Body).Decode(&dres); err != nil {
level.Error(a.logger).Log("msg", "failed to unmarshal OPA response", "err", err.Error())
return http.StatusForbidden, false, ""
}
if dres.Result == nil {
level.Error(a.logger).Log("msg", "received an empty OPA response")
return http.StatusForbidden, false, ""
}
var (
allowed bool
data string
)
switch res := (*dres.Result).(type) {
case bool:
allowed = res
case map[string]interface{}:
allow, ok := res["allowed"]
if !ok {
level.Error(a.logger).Log("msg", "received a malformed OPA response")
return http.StatusForbidden, false, ""
}
allowed, err = strconv.ParseBool(allow.(string))
if err != nil {
level.Error(a.logger).Log("msg", "received a malformed OPA response")
return http.StatusForbidden, false, ""
}
data = res["data"].(string)
default:
level.Error(a.logger).Log("msg", "received a malformed OPA response")
return http.StatusForbidden, false, ""
}
if !allowed {
return http.StatusForbidden, allowed, data
}
return http.StatusOK, allowed, data
}
// NewRESTAuthorizer creates a new rbac.Authorizer that works against an OPA endpoint.
func NewRESTAuthorizer(u *url.URL, opts ...Option) rbac.Authorizer {
c := &config{
logger: log.NewNopLogger(),
registerer: prometheus.NewRegistry(),
}
for _, o := range opts {
o(c)
}
return &restAuthorizer{
client: http.DefaultClient,
logger: c.logger,
registerer: c.registerer,
url: u,
withAccessToken: c.withAccessToken,
}
}
type inProcessAuthorizer struct {
query *rego.PreparedEvalQuery
logger log.Logger
registerer prometheus.Registerer
}
// Authorize implements the rbac.Authorizer interface.
func (a *inProcessAuthorizer) Authorize(
subject string,
groups []string,
permission rbac.Permission,
resource, tenant, tenantID, token string,
extras *rbac.ExtraAttributes,
) (int, bool, string) {
var i interface{} = Input{
Groups: groups,
Permission: permission,
Resource: resource,
Subject: subject,
Tenant: tenant,
TenantID: tenantID,
Token: token,
Extras: extras,
}
res, err := a.query.Eval(context.Background(), rego.EvalInput(i))
if err != nil {
level.Error(a.logger).Log("msg", "failed to evaluate OPA query", "err", err.Error())
return http.StatusForbidden, false, ""
}
if len(res) == 0 || len(res[0].Expressions) == 0 || res[0].Expressions[0] == nil {
level.Error(a.logger).Log("msg", "received a empty OPA response")
return http.StatusForbidden, false, ""
}
var (
allowed bool
data string
)
switch res := (res[0].Expressions[0].Value).(type) {
case bool:
allowed = res
case map[string]string:
allow, ok := res["allowed"]
if !ok {
level.Error(a.logger).Log("msg", "received a malformed OPA response")
return http.StatusForbidden, false, ""
}
allowed, err = strconv.ParseBool(allow)
if err != nil {
level.Error(a.logger).Log("msg", "received a malformed OPA response")
return http.StatusForbidden, false, ""
}
data = res["data"]
default:
level.Error(a.logger).Log("msg", "received a malformed OPA response")
return http.StatusForbidden, false, ""
}
if !allowed {
return http.StatusForbidden, allowed, data
}
return http.StatusOK, allowed, data
}
// NewInProcessAuthorizer creates a new rbac.Authorizer that works in-process.
func NewInProcessAuthorizer(query string, paths []string, opts ...Option) (rbac.Authorizer, error) {
c := &config{
logger: log.NewNopLogger(),
registerer: prometheus.NewRegistry(),
}
for _, o := range opts {
o(c)
}
var r *rego.Rego
regoArgs := make([]func(*rego.Rego), 0, len(regoFunctions)+2)
for _, regoFunction := range regoFunctions {
regoArgs = append(regoArgs, regoFunction(c.logger))
}
// Register all provided custom built-in functions
regoArgs = append(regoArgs, rego.Query(query), rego.Load(paths, nil))
r = rego.New(regoArgs...)
q, err := r.PrepareForEval(context.Background())
if err != nil {
return nil, fmt.Errorf("failed to prepare OPA query: %w", err)
}
return &inProcessAuthorizer{
logger: c.logger,
query: &q,
registerer: c.registerer,
}, nil
}