-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbuild.go
More file actions
369 lines (308 loc) · 9.31 KB
/
build.go
File metadata and controls
369 lines (308 loc) · 9.31 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
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
366
367
368
369
package runtime
import (
"bytes"
"context"
"encoding/json"
"io"
"os"
"path/filepath"
"strings"
"github.com/open-policy-agent/opa/v1/ast"
"github.com/open-policy-agent/opa/v1/bundle"
"github.com/open-policy-agent/opa/v1/compile"
"github.com/open-policy-agent/opa/v1/rego"
"github.com/open-policy-agent/opa/v1/topdown"
"github.com/open-policy-agent/opa/v1/types"
"github.com/pkg/errors"
)
// BuildTargetType represents the type of build target.
type BuildTargetType int
const (
Rego BuildTargetType = iota
Wasm
)
type fakeBuiltin struct {
Name string `json:"name"`
Decl types.Function `json:"decl"`
}
type (
fakeBuiltin1 fakeBuiltin
fakeBuiltin2 fakeBuiltin
fakeBuiltin3 fakeBuiltin
fakeBuiltin4 fakeBuiltin
fakeBuiltinDyn fakeBuiltin
)
type fakeBuiltinDefs struct {
Builtin1 []fakeBuiltin1 `json:"builtin1,omitempty"`
Builtin2 []fakeBuiltin2 `json:"builtin2,omitempty"`
Builtin3 []fakeBuiltin3 `json:"builtin3,omitempty"`
Builtin4 []fakeBuiltin4 `json:"builtin4,omitempty"`
BuiltinDyn []fakeBuiltinDyn `json:"builtinDyn,omitempty"`
}
func (t BuildTargetType) String() string {
return buildTargetTypeToString[t]
}
var buildTargetTypeToString = map[BuildTargetType]string{
Rego: "rego",
Wasm: "wasm",
}
type RegoVersion int
const DefaultRegoVersion = RegoV1
const (
RegoUndefined RegoVersion = iota
// RegoV0 is the default, original Rego syntax.
RegoV0
// RegoV0CompatV1 requires modules to comply with both the RegoV0 and RegoV1 syntax (as when 'rego.v1' is imported in a module).
// Shortly, RegoV1 compatibility is required, but 'rego.v1' or 'future.keywords' must also be imported.
RegoV0CompatV1
// RegoV1 is the Rego syntax enforced by OPA 1.0; e.g.:
// future.keywords part of default keyword set, and don't require imports;
// 'if' and 'contains' required in rule heads;
// (some) strict checks on by default.
RegoV1
)
const (
regoUndefined string = "undefined"
regoV0 string = "rego.v0"
regoV0V1 string = "rego.v0v1"
regoV1 string = "rego.v1"
)
func (v RegoVersion) ToAstRegoVersion() ast.RegoVersion {
return ast.RegoVersionFromInt(int(v))
}
func (v RegoVersion) String() string {
switch v {
case RegoUndefined:
return regoUndefined
case RegoV0:
return regoV0
case RegoV0CompatV1:
return regoV0V1
case RegoV1:
return regoV1
default:
return regoUndefined
}
}
func RegoVersionFromString(v string) RegoVersion {
switch v {
case regoV0:
return RegoV0
case regoV0V1:
return RegoV0CompatV1
case regoV1:
return RegoV1
default:
return RegoV1
}
}
// BuildParams contains all parameters used for doing a build.
type BuildParams struct {
CapabilitiesJSONFile string
Target BuildTargetType
OptimizationLevel int
Entrypoints []string
OutputFile string
Revision string
Ignore []string
Debug bool
Algorithm string
Key string
Scope string
PubKey string
PubKeyID string
ClaimsFile string
ExcludeVerifyFiles []string
RegoVersion RegoVersion
}
// Build builds a bundle using the Aserto OPA Runtime.
func (r *Runtime) Build(params *BuildParams, paths []string) error {
buf := bytes.NewBuffer(nil)
if err := r.generateAllFakeBuiltins(paths); err != nil {
return err
}
// generate the bundle verification and signing config.
var (
bvc *bundle.VerificationConfig
err error
)
if params.PubKey != "" {
bvc, err = buildVerificationConfig(params.PubKey, params.PubKeyID, params.Algorithm, params.Scope, params.ExcludeVerifyFiles)
if err != nil {
return err
}
}
bsc := buildSigningConfig(params.Key, params.Algorithm, params.ClaimsFile)
var capabilities *ast.Capabilities
// if capabilities are not provided then ast.CapabilitiesForThisVersion must be used.
if params.CapabilitiesJSONFile == "" {
capabilities = ast.CapabilitiesForThisVersion()
} else {
capabilitiesJSON, err := os.ReadFile(params.CapabilitiesJSONFile)
if err != nil {
return errors.Wrapf(err, "couldn't read capabilities JSON file [%s]", params.CapabilitiesJSONFile)
}
capabilities, err = ast.LoadCapabilitiesJSON(bytes.NewBuffer(capabilitiesJSON))
if err != nil {
return errors.Wrapf(err, "failed to load capabilities file [%s]", params.CapabilitiesJSONFile)
}
}
compiler := compile.New().
WithCapabilities(capabilities).
WithTarget(params.Target.String()).
WithAsBundle(true).
WithOptimizationLevel(params.OptimizationLevel).
WithOutput(buf).
WithEntrypoints(params.Entrypoints...).
WithPaths(paths...).
WithFilter(buildCommandLoaderFilter(true, params.Ignore)).
WithRevision(params.Revision).
WithBundleVerificationConfig(bvc).
WithBundleSigningConfig(bsc).
WithRegoVersion(params.RegoVersion.ToAstRegoVersion())
if params.ClaimsFile == "" {
compiler = compiler.WithBundleVerificationKeyID(params.PubKeyID)
}
if err := compiler.Build(context.Background()); err != nil {
return err
}
out, err := os.Create(params.OutputFile)
if err != nil {
return err
}
if _, err := io.Copy(out, buf); err != nil {
return err
}
return out.Close()
}
func buildCommandLoaderFilter(bundleMode bool, ignore []string) func(string, os.FileInfo, int) bool {
return func(absPath string, info os.FileInfo, depth int) bool {
if !bundleMode {
if !info.IsDir() && strings.HasSuffix(absPath, ".tar.gz") {
return true
}
}
return loaderFilter{Ignore: ignore}.Apply(absPath, info, depth)
}
}
func buildVerificationConfig(pubKey, pubKeyID, alg, scope string, excludeFiles []string) (*bundle.VerificationConfig, error) {
if pubKey == "" {
return nil, errors.New("pubKey is empty")
}
keyConfig := &bundle.KeyConfig{
Key: pubKey,
Algorithm: alg,
Scope: scope,
}
return bundle.NewVerificationConfig(map[string]*bundle.KeyConfig{pubKeyID: keyConfig}, pubKeyID, scope, excludeFiles), nil
}
func buildSigningConfig(key, alg, claimsFile string) *bundle.SigningConfig {
if key == "" {
return nil
}
return bundle.NewSigningConfig(key, alg, claimsFile)
}
func (r *Runtime) registerFakeBuiltins(defs *fakeBuiltinDefs) {
for _, b := range defs.Builtin1 {
builtin := b
if topdown.GetBuiltin(b.Name) != nil {
r.Logger.Info().Str("builtin", b.Name).Msg("Builtin already declared, skipping fake declaration.")
}
rego.RegisterBuiltin1(®o.Function{
Name: builtin.Name,
Memoize: false,
Decl: &builtin.Decl,
}, func(rego.BuiltinContext, *ast.Term) (*ast.Term, error) {
return &ast.Term{}, nil
})
}
for _, b := range defs.Builtin2 {
builtin := b
if topdown.GetBuiltin(b.Name) != nil {
r.Logger.Info().Str("builtin", b.Name).Msg("Builtin already declared, skipping fake declaration.")
}
rego.RegisterBuiltin2(®o.Function{
Name: builtin.Name,
Memoize: false,
Decl: &builtin.Decl,
}, func(bctx rego.BuiltinContext, op1, op2 *ast.Term) (*ast.Term, error) {
return &ast.Term{}, nil
})
}
for _, b := range defs.Builtin3 {
builtin := b
if topdown.GetBuiltin(b.Name) != nil {
r.Logger.Info().Str("builtin", b.Name).Msg("Builtin already declared, skipping fake declaration.")
}
rego.RegisterBuiltin3(®o.Function{
Name: builtin.Name,
Memoize: false,
Decl: &builtin.Decl,
}, func(bctx rego.BuiltinContext, op1, op2, op3 *ast.Term) (*ast.Term, error) {
return &ast.Term{}, nil
})
}
for _, b := range defs.Builtin4 {
builtin := b
if topdown.GetBuiltin(b.Name) != nil {
r.Logger.Info().Str("builtin", b.Name).Msg("Builtin already declared, skipping fake declaration.")
}
rego.RegisterBuiltin4(®o.Function{
Name: builtin.Name,
Memoize: false,
Decl: &builtin.Decl,
}, func(bctx rego.BuiltinContext, op1, op2, op3, op4 *ast.Term) (*ast.Term, error) {
return &ast.Term{}, nil
})
}
for _, b := range defs.BuiltinDyn {
builtin := b
if topdown.GetBuiltin(b.Name) != nil {
r.Logger.Info().Str("builtin", b.Name).Msg("Builtin already declared, skipping fake declaration.")
}
rego.RegisterBuiltinDyn(®o.Function{
Name: builtin.Name,
Memoize: false,
Decl: &builtin.Decl,
}, func(bctx rego.BuiltinContext, terms []*ast.Term) (*ast.Term, error) {
return &ast.Term{}, nil
})
}
}
func fileExists(path string) (bool, error) {
if fi, err := os.Stat(path); err == nil && !fi.IsDir() {
return true, nil
} else if os.IsNotExist(err) {
return false, nil
} else {
return false, errors.Wrapf(err, "failed to stat file '%s'", path)
}
}
func (r *Runtime) generateAllFakeBuiltins(paths []string) error {
for _, path := range paths {
manifestPath := filepath.Join(path, ".manifest")
manifestExists, err := fileExists(manifestPath)
if err != nil {
return errors.Wrapf(err, "failed to determine if file [%s] exists", manifestPath)
}
if !manifestExists {
continue
}
manifestBytes, err := os.ReadFile(manifestPath) //nolint:gosec
if err != nil {
return errors.Wrapf(err, "failed to read manifest [%s]", manifestPath)
}
manifest := struct {
Metadata struct {
RequiredBuiltins *fakeBuiltinDefs `json:"required_builtins"`
} `json:"metadata"`
}{}
if err := json.Unmarshal(manifestBytes, &manifest); err != nil {
return errors.Wrapf(err, "failed to unmarshal json from manifest [%s]", manifestPath)
}
if manifest.Metadata.RequiredBuiltins != nil {
r.registerFakeBuiltins(manifest.Metadata.RequiredBuiltins)
}
}
return nil
}