-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
policy.go
238 lines (195 loc) · 5.96 KB
/
policy.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
package policy
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"time"
"github.com/open-policy-agent/opa/bundle"
"golang.org/x/xerrors"
"k8s.io/utils/clock"
"github.com/aquasecurity/trivy/pkg/fanal/types"
"github.com/aquasecurity/trivy/pkg/log"
"github.com/aquasecurity/trivy/pkg/oci"
)
const (
BundleVersion = 1 // Latest released MAJOR version for trivy-checks
BundleRepository = "mirror.gcr.io/aquasec/trivy-checks"
policyMediaType = "application/vnd.cncf.openpolicyagent.layer.v1.tar+gzip"
updateInterval = 24 * time.Hour
)
type options struct {
artifact *oci.Artifact
clock clock.Clock
}
// WithOCIArtifact takes an OCI artifact
func WithOCIArtifact(art *oci.Artifact) Option {
return func(opts *options) {
opts.artifact = art
}
}
// WithClock takes a clock
func WithClock(c clock.Clock) Option {
return func(opts *options) {
opts.clock = c
}
}
// Option is a functional option
type Option func(*options)
// Client implements check operations
type Client struct {
*options
policyDir string
checkBundleRepo string
quiet bool
}
// Metadata holds default check metadata
type Metadata struct {
Digest string
DownloadedAt time.Time
}
func (m Metadata) String() string {
return fmt.Sprintf(`Check Bundle:
Digest: %s
DownloadedAt: %s
`, m.Digest, m.DownloadedAt.UTC())
}
// NewClient is the factory method for check client
func NewClient(cacheDir string, quiet bool, checkBundleRepo string, opts ...Option) (*Client, error) {
o := &options{
clock: clock.RealClock{},
}
for _, opt := range opts {
opt(o)
}
if checkBundleRepo == "" {
checkBundleRepo = fmt.Sprintf("%s:%d", BundleRepository, BundleVersion)
}
return &Client{
options: o,
policyDir: filepath.Join(cacheDir, "policy"),
checkBundleRepo: checkBundleRepo,
quiet: quiet,
}, nil
}
func (c *Client) populateOCIArtifact(ctx context.Context, registryOpts types.RegistryOptions) {
if c.artifact == nil {
log.DebugContext(ctx, "Loading check bundle", log.String("repository", c.checkBundleRepo))
c.artifact = oci.NewArtifact(c.checkBundleRepo, registryOpts)
}
}
// DownloadBuiltinChecks download default policies from GitHub Pages
func (c *Client) DownloadBuiltinChecks(ctx context.Context, registryOpts types.RegistryOptions) error {
c.populateOCIArtifact(ctx, registryOpts)
dst := c.contentDir()
if err := c.artifact.Download(ctx, dst, oci.DownloadOption{
MediaType: policyMediaType,
Quiet: c.quiet,
},
); err != nil {
return xerrors.Errorf("download error: %w", err)
}
digest, err := c.artifact.Digest(ctx)
if err != nil {
return xerrors.Errorf("digest error: %w", err)
}
log.DebugContext(ctx, "Digest of the built-in checks", log.String("digest", digest))
// Update metadata.json with the new digest and the current date
if err = c.updateMetadata(digest, c.clock.Now()); err != nil {
return xerrors.Errorf("unable to update the check metadata: %w", err)
}
return nil
}
// LoadBuiltinChecks loads default policies
func (c *Client) LoadBuiltinChecks() ([]string, error) {
f, err := os.Open(c.manifestPath())
if err != nil {
return nil, xerrors.Errorf("manifest file open error (%s): %w", c.manifestPath(), err)
}
defer f.Close()
var manifest bundle.Manifest
if err = json.NewDecoder(f).Decode(&manifest); err != nil {
return nil, xerrors.Errorf("json decode error (%s): %w", c.manifestPath(), err)
}
// If the "roots" field is not included in the manifest it defaults to [""]
// which means that ALL data and check must come from the bundle.
if manifest.Roots == nil || len(*manifest.Roots) == 0 {
return []string{c.contentDir()}, nil
}
var policyPaths []string
for _, root := range *manifest.Roots {
policyPaths = append(policyPaths, filepath.Join(c.contentDir(), root))
}
return policyPaths, nil
}
// NeedsUpdate returns if the default check should be updated
func (c *Client) NeedsUpdate(ctx context.Context, registryOpts types.RegistryOptions) (bool, error) {
meta, err := c.GetMetadata(ctx)
if err != nil {
return true, nil
}
// No need to update if it's been within a day since the last update.
if c.clock.Now().Before(meta.DownloadedAt.Add(updateInterval)) {
return false, nil
}
c.populateOCIArtifact(ctx, registryOpts)
digest, err := c.artifact.Digest(ctx)
if err != nil {
return false, xerrors.Errorf("digest error: %w", err)
}
if meta.Digest != digest {
return true, nil
}
// Update DownloadedAt with the current time.
// Otherwise, if there are no updates in the remote registry,
// the digest will be fetched every time even after this.
if err = c.updateMetadata(meta.Digest, time.Now()); err != nil {
return false, xerrors.Errorf("unable to update the check metadata: %w", err)
}
return false, nil
}
func (c *Client) contentDir() string {
return filepath.Join(c.policyDir, "content")
}
func (c *Client) metadataPath() string {
return filepath.Join(c.policyDir, "metadata.json")
}
func (c *Client) manifestPath() string {
return filepath.Join(c.contentDir(), bundle.ManifestExt)
}
func (c *Client) updateMetadata(digest string, now time.Time) error {
f, err := os.Create(c.metadataPath())
if err != nil {
return xerrors.Errorf("failed to open a check manifest: %w", err)
}
defer f.Close()
meta := Metadata{
Digest: digest,
DownloadedAt: now,
}
if err = json.NewEncoder(f).Encode(meta); err != nil {
return xerrors.Errorf("json encode error: %w", err)
}
return nil
}
func (c *Client) GetMetadata(ctx context.Context) (*Metadata, error) {
f, err := os.Open(c.metadataPath())
if err != nil {
log.DebugContext(ctx, "Failed to open the check metadata", log.Err(err))
return nil, err
}
defer f.Close()
var meta Metadata
if err = json.NewDecoder(f).Decode(&meta); err != nil {
log.WarnContext(ctx, "Check metadata decode error", log.Err(err))
return nil, err
}
return &meta, nil
}
func (c *Client) Clear() error {
if err := os.RemoveAll(c.policyDir); err != nil {
return xerrors.Errorf("failed to remove check bundle: %w", err)
}
return nil
}