-
Notifications
You must be signed in to change notification settings - Fork 2
/
bundles.go
365 lines (291 loc) · 8.32 KB
/
bundles.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package runtime
import (
"context"
"encoding/base64"
"fmt"
"hash/adler32"
"sort"
"strings"
"github.com/google/uuid"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/server/types"
"github.com/open-policy-agent/opa/storage"
opaTopdown "github.com/open-policy-agent/opa/topdown"
"github.com/pkg/errors"
)
type PolicyItem struct {
Name string
ID string
}
type Bundle struct {
ID string
Name string
Path string
}
type Module struct {
ID string
Name string
Content string
Rules []string
}
func (r *Runtime) GetBundles(ctx context.Context) ([]*PolicyItem, error) {
results := make([]*PolicyItem, 0)
bundles, err := getBundles(ctx, r)
if err != nil {
if strings.Contains(err.Error(), opaTopdown.CancelErr) {
return results, nil
}
return results, errors.Wrapf(err, "get bundles")
}
for _, b := range bundles {
results = append(results, &PolicyItem{
ID: b.ID,
Name: b.Name,
})
}
return results, nil
}
func getBundles(ctx context.Context, r *Runtime) ([]*Bundle, error) {
const queryStmt = "data.system.bundles[x]"
queryResults, err := r.Query(ctx, queryStmt, nil, false, false, false, types.ExplainOffV1)
if err != nil {
return []*Bundle{}, errors.Wrapf(err, "query bundles")
}
results := make([]*Bundle, 0)
for _, rs := range queryResults.Result {
v, ok := rs.Bindings["x"].(string)
if !ok {
r.Logger.Error().Err(fmt.Errorf("expected binding [x] not found")) //nolint:goerr113
continue
}
path := strings.TrimPrefix(v, "./")
id := calcID(v)
name, err := r.GetPolicyRootForPath(ctx, path)
if err != nil {
return []*Bundle{}, errors.Wrapf(err, "get policy name")
}
results = append(results, &Bundle{
ID: id,
Name: name,
Path: path,
})
}
return results, nil
}
func (r *Runtime) GetBundleByID(ctx context.Context, id string) (*Bundle, error) {
bundles, err := getBundles(ctx, r)
if err != nil {
return &Bundle{}, err
}
for _, v := range bundles {
if v.ID == id {
return v, nil
}
}
return &Bundle{}, errors.Errorf("bundle for policy id not found [%s]", id)
}
func calcID(v string) string {
if _, err := uuid.Parse(v); err == nil {
return v
}
return fmt.Sprintf("%d", uint64(adler32.Checksum([]byte(v))))
}
func (r *Runtime) GetPolicies(ctx context.Context, id string) ([]*PolicyItem, error) {
policies := make([]*PolicyItem, 0)
policyList, err := r.GetPolicyList(ctx, id, NoFilter)
if err != nil {
return policies, err
}
for _, policy := range policyList {
policies = append(
policies,
&PolicyItem{
Name: policy.PackageName,
ID: encID(policy.Location),
},
)
}
// sort policies by their name.
sort.Slice(policies, func(i, j int) bool {
return policies[i].Name < policies[j].Name
})
return policies, nil
}
type Policy struct {
PackageName string
Location string
}
func (p Policy) Name() string {
s := strings.Split(p.PackageName, ".")
if len(s) >= 1 {
return s[0]
}
return ""
}
type PathFilterFn func(packageName string) bool
var NoFilter PathFilterFn = func(packageName string) bool { return true }
// GetPolicyList returns the list of policies loaded by the runtime for a given bundle, identified with the policy id.
func (r *Runtime) GetPolicyList(ctx context.Context, id string, fn PathFilterFn) ([]Policy, error) {
policyList := make([]Policy, 0)
if fn == nil {
return policyList, errors.Errorf("path filter is nil")
}
err := storage.Txn(ctx, r.pluginsManager.Store, storage.TransactionParams{}, func(txn storage.Transaction) error {
policiesList, errX := r.pluginsManager.Store.ListPolicies(ctx, txn)
if errX != nil {
return errors.Wrap(errX, "error listing policies from storage")
}
for _, v := range policiesList {
buf, errX := r.pluginsManager.Store.GetPolicy(ctx, txn, v)
if errX != nil {
return errors.Wrap(errX, "store.GetPolicy")
}
module, errY := ast.ParseModule("", string(buf))
if errY != nil {
return errors.Wrap(errY, "ast.ParseModule")
}
packageName := strings.TrimPrefix(module.Package.Path.String(), "data.")
// filter out entries which do prefix the path specified
if fn != nil && !fn(packageName) {
continue
}
policyList = append(policyList,
Policy{
PackageName: packageName,
Location: v,
},
)
}
return nil
})
if err != nil {
return []Policy{}, err
}
return policyList, nil
}
// GetPolicyRoot returns the package root name from the policy list (not from the .manifest file). If no policies exist, it will return an empty string as the policy root.
func (r *Runtime) GetPolicyRoot(ctx context.Context) (string, error) {
var policyRoot string
err := storage.Txn(ctx, r.pluginsManager.Store, storage.TransactionParams{}, func(txn storage.Transaction) error {
policiesList, err := r.pluginsManager.Store.ListPolicies(ctx, txn)
if err != nil {
return errors.Wrap(err, "error listing policies from storage")
}
if len(policiesList) == 0 {
return nil
}
for _, id := range policiesList {
root, err := r.getRootFromPolicyID(ctx, id, txn)
if err != nil {
return err
}
if root != "" {
policyRoot = root
break
}
}
return nil
})
return policyRoot, err
}
// GetPolicyRootForPath returns the package root name from the policy list (not from the .manifest file) based on the given path.
func (r *Runtime) GetPolicyRootForPath(ctx context.Context, path string) (string, error) {
var policyName string
err := storage.Txn(ctx, r.pluginsManager.Store, storage.TransactionParams{}, func(txn storage.Transaction) error {
policiesList, errX := r.pluginsManager.Store.ListPolicies(ctx, txn)
if errX != nil {
return errors.Wrap(errX, "error listing policies from storage")
}
for _, v := range policiesList {
// filter out entries which do not belong to policy.
trimmedPath := strings.TrimPrefix(v, "/")
trimmedRequestPath := strings.TrimPrefix(path, "/")
if !strings.HasPrefix(trimmedPath, trimmedRequestPath) {
continue
}
policyRoot, err := r.getRootFromPolicyID(ctx, v, txn)
if err != nil {
return err
}
if policyRoot != "" {
policyName = policyRoot
break
}
}
return nil
})
if err != nil {
return "", err
}
return policyName, nil
}
func (r *Runtime) getRootFromPolicyID(ctx context.Context, policyID string, txn storage.Transaction) (string, error) {
buf, err := r.pluginsManager.Store.GetPolicy(ctx, txn, policyID)
if err != nil {
return "", errors.Wrap(err, "store.GetPolicy")
}
module, err := ast.ParseModule("", string(buf))
if err != nil {
return "", errors.Wrap(err, "ast.ParseModule")
}
packageName := strings.TrimPrefix(module.Package.Path.String(), "data.")
s := strings.Split(packageName, ".")
if len(s) >= 1 {
return s[0], nil
}
return "", err
}
func policyExists(ctx context.Context, r *Runtime, id string) bool {
err := storage.Txn(ctx, r.pluginsManager.Store, storage.TransactionParams{}, func(txn storage.Transaction) error {
_, err := r.pluginsManager.Store.GetPolicy(ctx, txn, id)
return err
})
return err == nil
}
func (r *Runtime) GetModule(ctx context.Context, id string) (*Module, error) {
pid := decID(id)
if !policyExists(ctx, r, pid) {
return &Module{}, errors.Errorf("policy not found [%s]", pid)
}
module, err := getModule(ctx, r, pid)
if err != nil {
return &Module{}, err
}
return module, nil
}
func getModule(ctx context.Context, r *Runtime, id string) (*Module, error) {
mod := &Module{}
err := storage.Txn(ctx, r.pluginsManager.Store, storage.TransactionParams{}, func(txn storage.Transaction) error {
policy, err := r.pluginsManager.Store.GetPolicy(ctx, txn, id)
if err != nil {
return errors.Wrap(err, "failed to get policy")
}
module, err := ast.ParseModule("", string(policy))
if err != nil {
return errors.Wrap(err, "parse module")
}
name := strings.TrimPrefix(module.Package.Path.String(), "data.")
rules := []string{}
for _, rule := range module.Rules {
rules = append(rules, rule.Head.Name.String())
}
mod.ID = encID(id)
mod.Name = name
mod.Content = string(policy)
mod.Rules = rules
return nil
})
return mod, err
}
// decID decode policy ID (base64 -> string).
func decID(id string) string {
b, err := base64.URLEncoding.DecodeString(id)
if err != nil {
return ""
}
return string(b)
}
// encID encode policy ID (string -> base64).
func encID(id string) string {
return base64.URLEncoding.EncodeToString([]byte(id))
}