-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathtest_push_security_scan.py
471 lines (419 loc) · 15.2 KB
/
test_push_security_scan.py
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
import os
from unittest import mock
import pytest
import yaml
from buildrunner.config.models import GlobalSecurityScanConfig
from buildrunner.errors import BuildRunnerProcessingError
from buildrunner.steprunner.tasks import push
@pytest.fixture(name="config_mock")
def fixture_config_mock():
with mock.patch(
"buildrunner.steprunner.tasks.push.BuildRunnerConfig"
) as buildrunner_config_mock:
config_mock = mock.MagicMock()
buildrunner_config_mock.get_instance.return_value = config_mock
yield config_mock
def _generate_built_image(num: int) -> mock.MagicMock():
image = mock.MagicMock()
image.repo = f"repo{num}"
image.tag = f"tag{num}"
image.platform = f"platform{num}"
return image
def test__security_scan_mp():
image_info = mock.MagicMock()
image_info.built_images = [_generate_built_image(num) for num in range(1, 4)]
self_mock = mock.MagicMock()
self_mock._security_scan.side_effect = (
lambda **kwargs: None
if kwargs["repository"] == "repo2"
else {"image": kwargs["repository"]}
)
push_security_scan = mock.MagicMock()
assert push.PushBuildStepRunnerTask._security_scan_mp(
self_mock,
image_info,
"image_ref1",
push_security_scan,
) == {
"docker:security-scan": {
"platform1": {"image": "repo1"},
"platform3": {"image": "repo3"},
}
}
assert self_mock._security_scan.call_args_list == [
mock.call(
repository="repo1",
tag="tag1",
log_image_ref="image_ref1:platform1",
pull=True,
push_security_scan=push_security_scan,
),
mock.call(
repository="repo2",
tag="tag2",
log_image_ref="image_ref1:platform2",
pull=True,
push_security_scan=push_security_scan,
),
mock.call(
repository="repo3",
tag="tag3",
log_image_ref="image_ref1:platform3",
pull=True,
push_security_scan=push_security_scan,
),
]
def test__security_scan_mp_empty():
image_info = mock.MagicMock()
image_info.built_images = [_generate_built_image(num) for num in range(1, 4)]
self_mock = mock.MagicMock()
self_mock._security_scan.return_value = None
assert not push.PushBuildStepRunnerTask._security_scan_mp(
self_mock,
image_info,
"image_ref1",
None,
)
@mock.patch(
"buildrunner.steprunner.tasks.push.MultiplatformImageBuilder.get_native_platform"
)
def test__security_scan_single(get_native_platform_mock):
get_native_platform_mock.return_value = "platform1"
self_mock = mock.MagicMock()
self_mock._security_scan.return_value = {"result": True}
push_security_scan = mock.MagicMock()
assert push.PushBuildStepRunnerTask._security_scan_single(
self_mock, "repo1", "abc123", push_security_scan
) == {"docker:security-scan": {"platform1": {"result": True}}}
self_mock._security_scan.assert_called_once_with(
repository="repo1",
tag="abc123",
log_image_ref="repo1:abc123",
pull=False,
push_security_scan=push_security_scan,
)
@mock.patch(
"buildrunner.steprunner.tasks.push.MultiplatformImageBuilder.get_native_platform"
)
def test__security_scan_single_empty(get_native_platform_mock):
get_native_platform_mock.return_value = "platform1"
self_mock = mock.MagicMock()
self_mock._security_scan.return_value = None
assert (
push.PushBuildStepRunnerTask._security_scan_single(
self_mock, "repo1", "abc123", None
)
== {}
)
self_mock._security_scan.assert_called_once()
def test__security_scan_scanner_disabled(config_mock):
config_mock.global_config.security_scan = GlobalSecurityScanConfig(enabled=False)
self_mock = mock.MagicMock()
assert not push.PushBuildStepRunnerTask._security_scan(
self_mock,
repository="repo1",
tag="tag1",
log_image_ref="image1",
pull=False,
push_security_scan=None,
)
self_mock._security_scan_trivy.assert_not_called()
def test__security_scan_scanner_trivy(config_mock):
security_scan_mock = mock.MagicMock()
merged_config_mock = mock.MagicMock()
config_mock.global_config.security_scan = security_scan_mock
security_scan_mock.merge_scan_config.return_value = merged_config_mock
merged_config_mock.enabled = True
merged_config_mock.scanner = "trivy"
push_security_scan = mock.MagicMock()
self_mock = mock.MagicMock()
self_mock._security_scan_trivy.return_value = {"result": True}
assert push.PushBuildStepRunnerTask._security_scan(
self_mock,
repository="repo1",
tag="tag1",
log_image_ref="image1",
pull=False,
push_security_scan=push_security_scan,
) == {"result": True}
self_mock._security_scan_trivy.assert_called_once_with(
security_scan_config=merged_config_mock,
repository="repo1",
tag="tag1",
log_image_ref="image1 (repo1:tag1)",
pull=False,
)
security_scan_mock.merge_scan_config.assert_called_once_with(push_security_scan)
def test__security_scan_scanner_unsupported(config_mock):
config_mock.global_config.security_scan = GlobalSecurityScanConfig(
enabled=True, scanner="bogus"
)
self_mock = mock.MagicMock()
with pytest.raises(Exception) as exc_info:
assert push.PushBuildStepRunnerTask._security_scan(
self_mock,
repository="repo1",
tag="tag1",
log_image_ref="image1",
pull=False,
push_security_scan=None,
) == {"result": True}
assert "Unsupported scanner" in str(exc_info.value)
self_mock._security_scan_trivy.assert_not_called()
@pytest.mark.parametrize(
"input_results, parsed_results",
[
({}, {"max_score": 0, "vulnerabilities": []}),
({"Results": []}, {"max_score": 0, "vulnerabilities": []}),
(
{"Results": [{"Vulnerabilities": [{}]}]},
{
"max_score": 0,
"vulnerabilities": [
{
"cvss_v3_score": None,
"severity": None,
"vulnerability_id": None,
"pkg_name": None,
"installed_version": None,
"primary_url": None,
}
],
},
),
(
{
"Results": [
{
"Vulnerabilities": [
{
"CVSS": {"nvd": {"V3Score": 1.0}},
"Severity": "HIGH",
"VulnerabilityID": "CVE1",
"PkgName": "pkg1",
"InstalledVersion": "v1",
"PrimaryURL": "url1",
}
]
}
]
},
{
"max_score": 1.0,
"vulnerabilities": [
{
"cvss_v3_score": 1.0,
"severity": "HIGH",
"vulnerability_id": "CVE1",
"pkg_name": "pkg1",
"installed_version": "v1",
"primary_url": "url1",
}
],
},
),
],
)
def test__security_scan_trivy_parse_results(input_results, parsed_results):
security_scan_config = GlobalSecurityScanConfig()
assert (
push.PushBuildStepRunnerTask._security_scan_trivy_parse_results(
security_scan_config, input_results
)
== parsed_results
)
@pytest.mark.parametrize(
"max_score_threshold, exception_raised",
[
(None, False),
(2.11, False),
(2.1, True),
],
)
def test__security_scan_trivy_parse_results_max_score_threshold(
max_score_threshold, exception_raised
):
security_scan_config = GlobalSecurityScanConfig(
**{"max-score-threshold": max_score_threshold}
)
input_results = {
"Results": [
{
"Vulnerabilities": [
{
"CVSS": {"nvd": {"V3Score": 1.0}},
},
{
"CVSS": {"nvd": {"V3Score": None}},
},
{
"CVSS": {"nvd": {"V3Score": 0}},
},
],
},
{
"Vulnerabilities": [
{
"CVSS": {"nvd": {"V3Score": 2.1}},
},
{
"CVSS": {"nvd": {"V3Score": 1.9}},
},
],
},
]
}
if exception_raised:
with pytest.raises(
BuildRunnerProcessingError, match="is above the configured threshold"
):
push.PushBuildStepRunnerTask._security_scan_trivy_parse_results(
security_scan_config,
input_results,
)
else:
push.PushBuildStepRunnerTask._security_scan_trivy_parse_results(
security_scan_config, input_results
)
@mock.patch("buildrunner.steprunner.tasks.push.DockerRunner")
@mock.patch("buildrunner.steprunner.tasks.push.tempfile")
@mock.patch("buildrunner.steprunner.tasks.push.os")
def test__security_scan_trivy(
os_mock, tempfile_mock, docker_runner_mock, config_mock, tmp_path
):
os_mock.makedirs = os.makedirs
os_mock.path = os.path
os_mock.getuid.return_value = "123"
os_mock.getgid.return_value = "234"
run_path = tmp_path / "run"
run_path.mkdir()
tempfile_mock.TemporaryDirectory.return_value.__enter__.return_value = str(run_path)
config_mock.global_config.docker_registry = "registry1"
security_scan_config = GlobalSecurityScanConfig()
self_mock = mock.MagicMock()
self_mock._security_scan_trivy_parse_results.return_value = {"parsed_results": True}
config_mock.global_config.temp_dir = str(tmp_path)
def _call_run(command, **kwargs):
_ = kwargs
if command.startswith("trivy --config"):
(run_path / "results.json").write_text('{"results": True}')
return 0
docker_runner_mock.return_value.run.side_effect = _call_run
assert push.PushBuildStepRunnerTask._security_scan_trivy(
self_mock,
security_scan_config=security_scan_config,
repository="repo1",
tag="tag1",
log_image_ref="image1",
pull=True,
) == {"parsed_results": True}
assert set(path.name for path in tmp_path.iterdir()) == {
"run",
"trivy-cache",
}
assert set(path.name for path in run_path.iterdir()) == {
"config.yaml",
"results.json",
}
assert yaml.safe_load((run_path / "config.yaml").read_text()) == {
"cache-dir": "/root/.cache/trivy",
**security_scan_config.config,
}
docker_runner_mock.ImageConfig.assert_called_once_with(
"registry1/aquasec/trivy:latest",
pull_image=False,
)
docker_runner_mock.assert_called_once_with(
docker_runner_mock.ImageConfig.return_value,
log=self_mock.step_runner.log,
)
docker_runner_mock().start.assert_called_once_with(
entrypoint="/bin/sh",
volumes={
str(run_path): "/trivy",
str(tmp_path / "trivy-cache"): "/root/.cache/trivy",
"/var/run/docker.sock": "/var/run/docker.sock",
},
)
assert docker_runner_mock().run.call_args_list == [
mock.call("trivy --version", console=self_mock.step_runner.log),
mock.call(
"trivy --config /trivy/config.yaml image -f json -o /trivy/results.json repo1:tag1",
console=self_mock.step_runner.log,
),
mock.call(
"chown -R 123:234 /trivy",
log=self_mock.step_runner.log,
),
]
docker_runner_mock().cleanup.assert_called_once_with()
self_mock._security_scan_trivy_parse_results.assert_called_once_with(
security_scan_config, {"results": True}
)
@mock.patch("buildrunner.steprunner.tasks.push.DockerRunner")
def test__security_scan_trivy_failure(docker_runner_mock, config_mock, tmp_path):
config_mock.global_config.docker_registry = "registry1"
security_scan_config = GlobalSecurityScanConfig()
self_mock = mock.MagicMock()
config_mock.global_config.temp_dir = str(tmp_path)
docker_runner_mock.return_value.run.return_value = 1
with pytest.raises(BuildRunnerProcessingError, match="Could not scan"):
push.PushBuildStepRunnerTask._security_scan_trivy(
self_mock,
security_scan_config=security_scan_config,
repository="repo1",
tag="tag1",
log_image_ref="image1",
pull=True,
)
docker_runner_mock.ImageConfig.assert_called_once()
docker_runner_mock.assert_called_once()
docker_runner_mock().start.assert_called_once()
assert docker_runner_mock().run.call_count == 3
docker_runner_mock().cleanup.assert_called_once()
self_mock._security_scan_trivy_parse_results.assert_not_called()
@mock.patch("buildrunner.steprunner.tasks.push.DockerRunner")
def test__security_scan_trivy_file_not_created(
docker_runner_mock, config_mock, tmp_path
):
config_mock.global_config.docker_registry = "registry1"
security_scan_config = GlobalSecurityScanConfig()
self_mock = mock.MagicMock()
config_mock.global_config.temp_dir = str(tmp_path)
docker_runner_mock.return_value.run.return_value = 0
with pytest.raises(BuildRunnerProcessingError, match="does not exist"):
push.PushBuildStepRunnerTask._security_scan_trivy(
self_mock,
security_scan_config=security_scan_config,
repository="repo1",
tag="tag1",
log_image_ref="image1",
pull=True,
)
@mock.patch("buildrunner.steprunner.tasks.push.DockerRunner")
@mock.patch("buildrunner.steprunner.tasks.push.tempfile")
def test__security_scan_trivy_empty_file(
tempfile_mock, docker_runner_mock, config_mock, tmp_path
):
run_path = tmp_path / "run"
run_path.mkdir()
tempfile_mock.TemporaryDirectory.return_value.__enter__.return_value = str(run_path)
config_mock.global_config.docker_registry = "registry1"
security_scan_config = GlobalSecurityScanConfig()
self_mock = mock.MagicMock()
config_mock.global_config.temp_dir = str(tmp_path)
def _call_run(command, **kwargs):
_ = kwargs
if command.startswith("trivy --config"):
(run_path / "results.json").write_text("{}")
return 0
docker_runner_mock.return_value.run.side_effect = _call_run
with pytest.raises(BuildRunnerProcessingError, match="Could not read results file"):
push.PushBuildStepRunnerTask._security_scan_trivy(
self_mock,
security_scan_config=security_scan_config,
repository="repo1",
tag="tag1",
log_image_ref="image1",
pull=True,
)