-
Notifications
You must be signed in to change notification settings - Fork 123
/
bundle.go
252 lines (205 loc) · 6.38 KB
/
bundle.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
// Copyright 2021-2023 Zenauth Ltd.
// SPDX-License-Identifier: Apache-2.0
package bundle
import (
"archive/zip"
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
"strings"
runtimev1 "github.com/cerbos/cerbos/api/genpb/cerbos/runtime/v1"
"github.com/cerbos/cerbos/internal/namer"
"github.com/cerbos/cerbos/internal/storage"
"github.com/cerbos/cloud-api/credentials"
bundlev1 "github.com/cerbos/cloud-api/genpb/cerbos/cloud/bundle/v1"
"github.com/spf13/afero"
"github.com/spf13/afero/zipfs"
"go.uber.org/zap"
)
const (
manifestFileName = "MANIFEST"
policyDir = "policies/"
schemaDir = "_schemas/"
)
type cleanupFn func() error
type OpenOpts struct {
Credentials *credentials.Credentials
ScratchFS afero.Fs
BundlePath string
}
type Bundle struct {
bundleFS afero.Fs
manifest *bundlev1.Manifest
cleanup cleanupFn
path string
}
func Open(opts OpenOpts) (*Bundle, error) {
logger := zap.L().Named("bundle").With(zap.String("path", opts.BundlePath))
logger.Info("Opening bundle")
decryptedPath, size, err := decryptBundle(opts, logger)
if err != nil {
return nil, err
}
zipFS, cleanup, err := archiveToFS(opts, decryptedPath, size, logger)
if err != nil {
return nil, err
}
logger.Debug("Reading manifest")
manifest, err := loadManifest(zipFS)
if err != nil {
_ = cleanup()
return nil, err
}
logger.Info("Bundle opened", zap.String("identifier", manifest.Meta.Identifier))
return &Bundle{
path: decryptedPath,
manifest: manifest,
bundleFS: zipFS,
cleanup: cleanup,
}, nil
}
func decryptBundle(opts OpenOpts, logger *zap.Logger) (string, int64, error) {
input, err := os.Open(opts.BundlePath)
if err != nil {
logger.Debug("Failed to open bundle", zap.Error(err))
return "", 0, fmt.Errorf("failed to open bundle at path %q: %w", opts.BundlePath, err)
}
defer input.Close()
var decrypted io.Reader
if opts.Credentials == nil {
decrypted = input
} else {
logger.Debug("Decrypting bundle")
decrypted, err = opts.Credentials.Decrypt(input)
if err != nil {
logger.Debug("Failed to decrypt bundle", zap.Error(err))
return "", 0, fmt.Errorf("failed to decrypt bundle: %w", err)
}
}
afs := &afero.Afero{Fs: opts.ScratchFS}
outFile, err := afs.TempFile(".", "bundle-*")
if err != nil {
logger.Debug("Failed to create temporary file", zap.Error(err))
return "", 0, fmt.Errorf("failed to create temporary file: %w", err)
}
defer outFile.Close()
fileName := outFile.Name()
logger.Debug("Writing bundle archive", zap.String("archive", fileName))
size, err := io.Copy(outFile, decrypted)
if err != nil {
logger.Debug("Failed to write bundle archive", zap.Error(err))
return "", 0, fmt.Errorf("failed to write bundle archive: %w", err)
}
return fileName, size, nil
}
func archiveToFS(opts OpenOpts, archivePath string, archiveSize int64, logger *zap.Logger) (afero.Fs, cleanupFn, error) {
log := logger.With(zap.String("archive", archivePath))
afs := &afero.Afero{Fs: opts.ScratchFS}
archiveIn, err := afs.Open(archivePath)
if err != nil {
log.Debug("Failed to open bundle archive", zap.Error(err))
return nil, nil, fmt.Errorf("failed to open bundle archive %q: %w", archivePath, err)
}
log.Debug("Reading bundle archive")
zipIn, err := zip.NewReader(archiveIn, archiveSize)
if err != nil {
_ = archiveIn.Close()
log.Debug("Failed to read bundle archive", zap.Error(err))
return nil, nil, fmt.Errorf("failed to open archive: %w", err)
}
cleanup := func() error {
log.Debug("Closing bundle archive", zap.Error(err))
if err := archiveIn.Close(); err != nil {
log.Debug("Failed to close bundle archive", zap.Error(err))
return err
}
// Because we use random strings to avoid a clash, clean up the file
log.Debug("Removing bundle archive", zap.Error(err))
if err := opts.ScratchFS.Remove(archivePath); err != nil {
log.Warn("Failed to remove temporary bundle archive "+archivePath, zap.Error(err))
return err
}
return nil
}
return zipfs.New(zipIn), cleanup, nil
}
func loadManifest(bundleFS afero.Fs) (*bundlev1.Manifest, error) {
mf, err := bundleFS.Open(manifestFileName)
if err != nil {
return nil, fmt.Errorf("failed to read manifest: %w", err)
}
defer mf.Close()
manifestBytes, err := io.ReadAll(mf)
if err != nil {
return nil, fmt.Errorf("failed to read manifest bytes: %w", err)
}
manifest := &bundlev1.Manifest{}
if err := manifest.UnmarshalVT(manifestBytes); err != nil {
return nil, fmt.Errorf("failed to unmarshal manifest: %w", err)
}
return manifest, nil
}
func (b *Bundle) GetFirstMatch(_ context.Context, candidates []namer.ModuleID) (*runtimev1.RunnablePolicySet, error) {
for _, id := range candidates {
idHex := id.HexStr()
fileName := policyDir + idHex
if _, err := b.bundleFS.Stat(fileName); err != nil {
if errors.Is(err, fs.ErrNotExist) {
continue
}
return nil, fmt.Errorf("failed to stat policy %s: %w", idHex, err)
}
return b.loadPolicySet(idHex, fileName)
}
return nil, nil
}
func (b *Bundle) loadPolicySet(idHex, fileName string) (*runtimev1.RunnablePolicySet, error) {
f, err := b.bundleFS.Open(fileName)
if err != nil {
return nil, fmt.Errorf("failed to open policy %s: %w", idHex, err)
}
defer f.Close()
policyBytes, err := io.ReadAll(f)
if err != nil {
return nil, fmt.Errorf("failed to read policy %s: %w", idHex, err)
}
rps := &runtimev1.RunnablePolicySet{}
if err := rps.UnmarshalVT(policyBytes); err != nil {
return nil, fmt.Errorf("failed to unmarshal %s: %w", idHex, err)
}
return rps, nil
}
func (b *Bundle) ListPolicyIDs(_ context.Context, _ storage.ListPolicyIDsParams) ([]string, error) {
output := make([]string, len(b.manifest.PolicyIndex))
i := 0
for fqn := range b.manifest.PolicyIndex {
output[i] = fqn
i++
}
return output, nil
}
func (b *Bundle) ListSchemaIDs(_ context.Context) ([]string, error) {
output := make([]string, len(b.manifest.Schemas))
for i, s := range b.manifest.Schemas {
output[i] = strings.TrimPrefix(s, schemaDir)
}
return output, nil
}
func (b *Bundle) LoadSchema(_ context.Context, path string) (io.ReadCloser, error) {
fullPath := schemaDir + path
f, err := b.bundleFS.Open(fullPath)
if err != nil {
return nil, fmt.Errorf("failed to load schema %s: %w", path, err)
}
// TODO(cell): Should we write the schema to scratch dir and create a reader for that instead?
return f, nil
}
func (b *Bundle) Release() error {
return b.Close()
}
func (b *Bundle) Close() error {
return b.cleanup()
}