-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
artifact.go
280 lines (231 loc) · 7.26 KB
/
artifact.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
package oci
import (
"context"
"errors"
"io"
"os"
"path/filepath"
"sync"
"github.com/cheggaaa/pb/v3"
"github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/remote/transport"
"github.com/hashicorp/go-multierror"
"github.com/samber/lo"
"golang.org/x/xerrors"
"github.com/aquasecurity/trivy/pkg/downloader"
"github.com/aquasecurity/trivy/pkg/fanal/types"
"github.com/aquasecurity/trivy/pkg/log"
"github.com/aquasecurity/trivy/pkg/remote"
"github.com/aquasecurity/trivy/pkg/version/doc"
)
const (
// Artifact types
CycloneDXArtifactType = "application/vnd.cyclonedx+json"
SPDXArtifactType = "application/spdx+json"
// Media types
OCIImageManifest = "application/vnd.oci.image.manifest.v1+json"
// Annotations
titleAnnotation = "org.opencontainers.image.title"
)
var SupportedSBOMArtifactTypes = []string{
CycloneDXArtifactType,
SPDXArtifactType,
}
// Option is a functional option
type Option func(*Artifact)
// WithImage takes an OCI v1 Image
func WithImage(img v1.Image) Option {
return func(a *Artifact) {
a.image = img
}
}
// Artifact is used to download artifacts such as vulnerability database and policies from OCI registries.
type Artifact struct {
m sync.Mutex
repository string
// For OCI registries
types.RegistryOptions
image v1.Image // For testing
}
// NewArtifact returns a new artifact
func NewArtifact(repo string, registryOpt types.RegistryOptions, opts ...Option) *Artifact {
art := &Artifact{
repository: repo,
RegistryOptions: registryOpt,
}
for _, o := range opts {
o(art)
}
return art
}
func (a *Artifact) populate(ctx context.Context, opt types.RegistryOptions) error {
if a.image != nil {
return nil
}
a.m.Lock()
defer a.m.Unlock()
var nameOpts []name.Option
if opt.Insecure {
nameOpts = append(nameOpts, name.Insecure)
}
ref, err := name.ParseReference(a.repository, nameOpts...)
if err != nil {
return xerrors.Errorf("repository name error (%s): %w", a.repository, err)
}
a.image, err = remote.Image(ctx, ref, opt)
if err != nil {
return xerrors.Errorf("OCI repository error: %w", err)
}
return nil
}
type DownloadOption struct {
MediaType string // Accept any media type if not specified
Filename string // Use the annotation if not specified
Quiet bool
}
func (a *Artifact) Download(ctx context.Context, dir string, opt DownloadOption) error {
if err := a.populate(ctx, a.RegistryOptions); err != nil {
return err
}
layers, err := a.image.Layers()
if err != nil {
return xerrors.Errorf("OCI layer error: %w", err)
}
manifest, err := a.image.Manifest()
if err != nil {
return xerrors.Errorf("OCI manifest error: %w", err)
}
// A single layer is only supported now.
if len(layers) != 1 || len(manifest.Layers) != 1 {
return xerrors.Errorf("OCI artifact must be a single layer")
}
// Take the first layer
layer := layers[0]
// Take the file name of the first layer if not specified
fileName := opt.Filename
if fileName == "" {
if v, ok := manifest.Layers[0].Annotations[titleAnnotation]; !ok {
return xerrors.Errorf("annotation %s is missing", titleAnnotation)
} else {
fileName = v
}
}
layerMediaType, err := layer.MediaType()
if err != nil {
return xerrors.Errorf("media type error: %w", err)
} else if opt.MediaType != "" && opt.MediaType != string(layerMediaType) {
return xerrors.Errorf("unacceptable media type: %s", string(layerMediaType))
}
if err = a.download(ctx, layer, fileName, dir, opt.Quiet); err != nil {
return xerrors.Errorf("oci download error: %w", err)
}
return nil
}
func (a *Artifact) download(ctx context.Context, layer v1.Layer, fileName, dir string, quiet bool) error {
size, err := layer.Size()
if err != nil {
return xerrors.Errorf("size error: %w", err)
}
rc, err := layer.Compressed()
if err != nil {
return xerrors.Errorf("failed to fetch the layer: %w", err)
}
defer rc.Close()
// Show progress bar
bar := pb.Full.Start64(size)
if quiet {
bar.SetWriter(io.Discard)
}
pr := bar.NewProxyReader(rc)
defer bar.Finish()
// https://github.com/hashicorp/go-getter/issues/326
tempDir, err := os.MkdirTemp("", "trivy")
if err != nil {
return xerrors.Errorf("failed to create a temp dir: %w", err)
}
f, err := os.Create(filepath.Join(tempDir, fileName))
if err != nil {
return xerrors.Errorf("failed to create a temp file: %w", err)
}
defer func() {
_ = f.Close()
_ = os.RemoveAll(tempDir)
}()
// Download the layer content into a temporal file
if _, err = io.Copy(f, pr); err != nil {
return xerrors.Errorf("copy error: %w", err)
}
// Decompress the downloaded file if it is compressed and copy it into the dst
// NOTE: it's local copying, the insecure option doesn't matter.
if _, err = downloader.Download(ctx, f.Name(), dir, dir, downloader.Options{}); err != nil {
return xerrors.Errorf("download error: %w", err)
}
return nil
}
func (a *Artifact) Digest(ctx context.Context) (string, error) {
if err := a.populate(ctx, a.RegistryOptions); err != nil {
return "", err
}
digest, err := a.image.Digest()
if err != nil {
return "", xerrors.Errorf("digest error: %w", err)
}
return digest.String(), nil
}
type Artifacts []*Artifact
// NewArtifacts returns a slice of artifacts.
func NewArtifacts(repos []name.Reference, opt types.RegistryOptions, opts ...Option) Artifacts {
return lo.Map(repos, func(r name.Reference, _ int) *Artifact {
return NewArtifact(r.String(), opt, opts...)
})
}
// Download downloads artifacts until one of them succeeds.
// Attempts to download next artifact if the first one fails due to a temporary error.
func (a Artifacts) Download(ctx context.Context, dst string, opt DownloadOption) error {
var errs error
for i, art := range a {
log.InfoContext(ctx, "Downloading artifact...", log.String("repo", art.repository))
err := art.Download(ctx, dst, opt)
if err == nil {
log.InfoContext(ctx, "Artifact successfully downloaded", log.String("repo", art.repository))
return nil
}
if !shouldTryOtherRepo(err) {
return xerrors.Errorf("failed to download artifact from %s: %w", art.repository, err)
}
log.ErrorContext(ctx, "Failed to download artifact", log.String("repo", art.repository), log.Err(err))
if i < len(a)-1 {
log.InfoContext(ctx, "Trying to download artifact from other repository...")
}
errs = multierror.Append(errs, err)
}
return xerrors.Errorf("failed to download artifact from any source: %w", errs)
}
func shouldTryOtherRepo(err error) bool {
var terr *transport.Error
if !errors.As(err, &terr) {
return false
}
for _, diagnostic := range terr.Errors {
// For better user experience
if diagnostic.Code == transport.DeniedErrorCode || diagnostic.Code == transport.UnauthorizedErrorCode {
// e.g. https://aquasecurity.github.io/trivy/latest/docs/references/troubleshooting/#db
log.Warnf("See %s", doc.URL("/docs/references/troubleshooting/", "db"))
break
}
}
// try the following artifact if a temporary error occurs
if terr.Temporary() {
return true
}
// `GCR` periodically returns `BLOB_UNKNOWN` error.
// cf. https://github.com/aquasecurity/trivy/discussions/8020
// In this case we need to check other repositories.
for _, e := range terr.Errors {
if e.Code == transport.BlobUnknownErrorCode {
return true
}
}
return false
}