-
Notifications
You must be signed in to change notification settings - Fork 2
/
build.go
305 lines (259 loc) · 7.95 KB
/
build.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
package runtime
import (
"bytes"
"context"
"encoding/json"
"io"
"os"
"path/filepath"
"strings"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/bundle"
"github.com/open-policy-agent/opa/compile"
"github.com/open-policy-agent/opa/rego"
"github.com/open-policy-agent/opa/topdown"
"github.com/open-policy-agent/opa/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
type fakeBuiltin2 fakeBuiltin
type fakeBuiltin3 fakeBuiltin
type fakeBuiltin4 fakeBuiltin
type 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",
}
// 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
RegoV1 bool
}
// Build builds a bundle using the Aserto OPA Runtime.
func (r *Runtime) Build(params *BuildParams, paths []string) error {
buf := bytes.NewBuffer(nil)
err := r.generateAllFakeBuiltins(paths)
if err != nil {
return err
}
// generate the bundle verification and signing config.
var bvc *bundle.VerificationConfig
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.NewBufferString(string(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)
if params.RegoV1 {
compiler = compiler.WithRegoVersion(ast.RegoV1)
}
if params.ClaimsFile == "" {
compiler = compiler.WithBundleVerificationKeyID(params.PubKeyID)
}
err = compiler.Build(context.Background())
if err != nil {
return err
}
out, err := os.Create(params.OutputFile)
if err != nil {
return err
}
_, err = io.Copy(out, buf)
if 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 nil, 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 nil, 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 nil, 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 nil, 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 nil, nil
})
}
}
func fileExists(path string) (bool, error) {
if _, err := os.Stat(path); err == nil {
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)
if err != nil {
return errors.Wrapf(err, "failed to read manifest [%s]", manifestPath)
}
manifest := struct {
Metadata struct {
RequiredBuiltins *fakeBuiltinDefs `json:"required_builtins"`
} `json:"metadata,omitempty"`
}{}
err = json.Unmarshal(manifestBytes, &manifest)
if 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
}