forked from aquasecurity/trivy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregistry_test.go
353 lines (302 loc) · 8.8 KB
/
registry_test.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
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
// +build integration
package integration
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"testing"
"github.com/docker/go-connections/nat"
"github.com/google/go-containerregistry/pkg/name"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
testcontainers "github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
_ "github.com/aquasecurity/fanal/analyzer"
testdocker "github.com/aquasecurity/trivy/integration/docker"
"github.com/aquasecurity/trivy/internal"
"github.com/aquasecurity/trivy/pkg/report"
)
const (
registryImage = "registry:2"
registryPort = "5443/tcp"
authImage = "cesanta/docker_auth:1"
authPort = "5001/tcp"
authUsername = "admin"
authPassword = "badmin"
)
func setupRegistry(ctx context.Context, baseDir string, authURL *url.URL) (testcontainers.Container, error) {
req := testcontainers.ContainerRequest{
Name: "registry",
Image: registryImage,
ExposedPorts: []string{registryPort},
Env: map[string]string{
"REGISTRY_HTTP_ADDR": "0.0.0.0:5443",
"REGISTRY_HTTP_TLS_CERTIFICATE": "/certs/cert.pem",
"REGISTRY_HTTP_TLS_KEY": "/certs/key.pem",
"REGISTRY_AUTH": "token",
"REGISTRY_AUTH_TOKEN_REALM": fmt.Sprintf("%s/auth", authURL),
"REGISTRY_AUTH_TOKEN_SERVICE": "registry.docker.io",
"REGISTRY_AUTH_TOKEN_ISSUER": "Trivy auth server",
"REGISTRY_AUTH_TOKEN_ROOTCERTBUNDLE": "/certs/cert.pem",
},
BindMounts: map[string]string{
filepath.Join(baseDir, "data", "certs"): "/certs",
},
WaitingFor: wait.ForLog("listening on [::]:5443"),
}
registryC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
return registryC, err
}
func setupAuthServer(ctx context.Context, baseDir string) (testcontainers.Container, error) {
req := testcontainers.ContainerRequest{
Name: "docker_auth",
Image: authImage,
ExposedPorts: []string{authPort},
BindMounts: map[string]string{
filepath.Join(baseDir, "data", "auth_config"): "/config",
filepath.Join(baseDir, "data", "certs"): "/certs",
},
Cmd: []string{"/config/config.yml"},
}
authC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
return authC, err
}
func getURL(ctx context.Context, container testcontainers.Container, exposedPort nat.Port) (*url.URL, error) {
ip, err := container.Host(ctx)
if err != nil {
return nil, err
}
port, err := container.MappedPort(ctx, exposedPort)
if err != nil {
return nil, err
}
urlStr := fmt.Sprintf("https://%s:%s", ip, port.Port())
return url.Parse(urlStr)
}
type registryOption struct {
AuthURL *url.URL
Username string
Password string
RegistryToken bool
}
func TestRegistry(t *testing.T) {
ctx := context.Background()
baseDir, err := filepath.Abs(".")
require.NoError(t, err)
// set up auth server
authC, err := setupAuthServer(ctx, baseDir)
require.NoError(t, err)
defer authC.Terminate(ctx)
authURL, err := getURL(ctx, authC, authPort)
require.NoError(t, err)
// set up registry
registryC, err := setupRegistry(ctx, baseDir, authURL)
require.NoError(t, err)
defer registryC.Terminate(ctx)
registryURL, err := getURL(ctx, registryC, registryPort)
require.NoError(t, err)
config := testdocker.RegistryConfig{
URL: registryURL,
Username: authUsername,
Password: authPassword,
}
testCases := []struct {
name string
imageName string
imageFile string
option registryOption
golden string
wantErr string
}{
{
name: "happy path with username/password",
imageName: "alpine:3.10",
imageFile: "testdata/fixtures/alpine-310.tar.gz",
option: registryOption{
AuthURL: authURL,
Username: authUsername,
Password: authPassword,
},
golden: "testdata/alpine-310-registry.json.golden",
},
{
name: "happy path with registry token",
imageName: "alpine:3.10",
imageFile: "testdata/fixtures/alpine-310.tar.gz",
option: registryOption{
AuthURL: authURL,
Username: authUsername,
Password: authPassword,
RegistryToken: true,
},
golden: "testdata/alpine-310-registry.json.golden",
},
{
name: "sad path",
imageName: "alpine:3.10",
imageFile: "testdata/fixtures/alpine-310.tar.gz",
wantErr: "unsupported status code 401; body: Auth failed",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
d, err := testdocker.New()
require.NoError(t, err)
s := fmt.Sprintf("%s/%s", registryURL.Host, tc.imageName)
imageRef, err := name.ParseReference(s)
require.NoError(t, err)
// 1. Load a test image from the tar file, tag it and push to the test registry.
err = d.ReplicateImage(ctx, tc.imageName, tc.imageFile, config)
require.NoError(t, err)
// 2. Scan it
resultFile, cleanup, err := scan(imageRef, baseDir, tc.golden, tc.option)
if tc.wantErr != "" {
require.NotNil(t, err)
require.Contains(t, err.Error(), tc.wantErr, err)
return
} else {
require.NoError(t, err)
}
defer cleanup()
// 3. Compare want and got
golden, err := os.Open(tc.golden)
assert.NoError(t, err)
var want report.Results
err = json.NewDecoder(golden).Decode(&want)
require.NoError(t, err)
result, err := os.Open(resultFile)
assert.NoError(t, err)
var got report.Results
err = json.NewDecoder(result).Decode(&got)
require.NoError(t, err)
assert.Equal(t, want[0].Vulnerabilities, got[0].Vulnerabilities)
assert.Equal(t, want[0].Vulnerabilities, got[0].Vulnerabilities)
})
}
}
func scan(imageRef name.Reference, baseDir, goldenFile string, opt registryOption) (string, func(), error) {
cleanup := func() {}
// Copy DB file
cacheDir, err := gunzipDB()
if err != nil {
return "", cleanup, err
}
defer os.RemoveAll(cacheDir)
// Setup the output file
var outputFile string
if *update && goldenFile != "" {
outputFile = goldenFile
} else {
output, err := ioutil.TempFile("", "integration")
if err != nil {
return "", cleanup, err
}
defer output.Close()
outputFile = output.Name()
cleanup = func() {
os.Remove(outputFile)
}
}
// Setup env
if err = setupEnv(imageRef, baseDir, opt); err != nil {
return "", cleanup, err
}
defer unsetEnv()
// Setup CLI App
app := internal.NewApp("dev")
app.Writer = ioutil.Discard
osArgs := []string{"trivy", "--cache-dir", cacheDir, "--format", "json", "--skip-update", "--output", outputFile, imageRef.Name()}
// Run Trivy
if err = app.Run(osArgs); err != nil {
return "", cleanup, err
}
return outputFile, cleanup, nil
}
func setupEnv(imageRef name.Reference, baseDir string, opt registryOption) error {
if err := os.Setenv("TRIVY_INSECURE", "true"); err != nil {
return err
}
if opt.Username != "" && opt.Password != "" {
if opt.RegistryToken {
// Get a registry token in advance
token, err := requestRegistryToken(imageRef, baseDir, opt)
if err != nil {
return err
}
if err := os.Setenv("TRIVY_REGISTRY_TOKEN", token); err != nil {
return err
}
} else {
if err := os.Setenv("TRIVY_USERNAME", opt.Username); err != nil {
return err
}
if err := os.Setenv("TRIVY_PASSWORD", opt.Password); err != nil {
return err
}
}
}
return nil
}
func unsetEnv() error {
envs := []string{"TRIVY_INSECURE", "TRIVY_USERNAME", "TRIVY_PASSWORD", "TRIVY_REGISTRY_TOKEN"}
for _, e := range envs {
if err := os.Unsetenv(e); err != nil {
return err
}
}
return nil
}
func requestRegistryToken(imageRef name.Reference, baseDir string, opt registryOption) (string, error) {
// Create a CA certificate pool and add cert.pem to it
caCert, err := ioutil.ReadFile(filepath.Join(baseDir, "data", "certs", "cert.pem"))
if err != nil {
return "", err
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
// Create a HTTPS client and supply the created CA pool
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: caCertPool,
},
},
}
// Get a registry token
req, err := http.NewRequest("GET", fmt.Sprintf("%s/auth", opt.AuthURL), nil)
if err != nil {
return "", err
}
// Set query parameters
values := req.URL.Query()
values.Set("service", "registry.docker.io")
values.Set("scope", imageRef.Scope("pull"))
req.URL.RawQuery = values.Encode()
req.SetBasicAuth(opt.Username, opt.Password)
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
type res struct {
AccessToken string `json:"access_token"`
}
var r res
if err = json.NewDecoder(resp.Body).Decode(&r); err != nil {
return "", err
}
return r.AccessToken, nil
}