/
test_monitoring.py
278 lines (238 loc) · 10.1 KB
/
test_monitoring.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
import json
import os
import pytest
import mock
from configman.config_exceptions import OptionError
from configman.dotdict import DotDict
from socorro.cron.jobs.monitoring import (
DependencySecurityCheckCronApp,
DependencySecurityCheckFailed,
Vulnerability,
)
@pytest.fixture
def app_config(tmpdir):
config = {}
for key in ('nsp_path', 'safety_path', 'package_json_path'):
path = tmpdir.join(key)
path.write('fake file', ensure=True)
config[key] = path.strpath
return config
@pytest.fixture
def mock_popen():
popen_patch = mock.patch('socorro.cron.jobs.monitoring.Popen')
popen = popen_patch.start()
def _mock_popen(return_code, output='', error_output=''):
process = popen.return_value
process.returncode = return_code
process.communicate.return_value = (output, error_output)
return popen
yield _mock_popen
popen_patch.stop()
# Mocking Popen for multiple calls in a row is kinda hairy, so instead
# we're testing the separate get_*_vulnerabilities methods and then
# mocking them to test the main command.
class TestDependencySecurityCheckCronApp(object):
def get_app(self, config=None):
config = DotDict(config or {})
return DependencySecurityCheckCronApp(config, None)
def test_get_python_vulnerabilities_none(self, mock_popen, app_config):
app = self.get_app(app_config)
popen = mock_popen(0)
assert app.get_python_vulnerabilities() == []
assert popen.call_args[0][0] == [app_config['safety_path'], 'check', '--json']
def test_get_python_vulnerabilities_failure(self, mock_popen, app_config):
"""Handle failures like being unable to connect to the network.
"""
app = self.get_app(app_config)
error_output = 'pretend-im-a-traceback'
mock_popen(1, error_output='pretend-im-a-traceback')
with pytest.raises(DependencySecurityCheckFailed) as err:
app.get_python_vulnerabilities()
assert err.value.args[0] == error_output
def test_get_python_vulnerabilities_found(self, mock_popen, app_config):
app = self.get_app(app_config)
# See https://github.com/pyupio/safety#--json for an example
# of safety's JSON output
output = json.dumps([
[
'mylibrary', # Dependency name
'<1.0.0', # Affected version
'0.9.0', # Installed version
'This is an error', # Vulnerability summary
'654', # Advisory ID
],
[
'otherlib',
'<2.0.0',
'1.4.0',
'This is also an error',
'123',
],
])
mock_popen(255, output=output)
assert set(app.get_python_vulnerabilities()) == set([
Vulnerability(
type='python',
dependency='mylibrary',
installed_version='0.9.0',
affected_versions='<1.0.0',
description='This is an error',
),
Vulnerability(
type='python',
dependency='otherlib',
installed_version='1.4.0',
affected_versions='<2.0.0',
description='This is also an error',
),
])
def test_get_python_vulnerabilities_cannot_parse_output(self, mock_popen, app_config):
app = self.get_app(app_config)
output = '{invalid5:52"json2'
mock_popen(255, output=output)
with pytest.raises(DependencySecurityCheckFailed) as err:
app.get_python_vulnerabilities()
assert err.value.args[0] == 'Could not parse pyup safety output'
def test_get_javascript_vulnerabilities_none(self, mock_popen, app_config):
app = self.get_app(app_config)
popen = mock_popen(0)
assert app.get_javascript_vulnerabilities() == []
assert popen.call_args[0][0] == [
app_config['nsp_path'],
'check',
'--reporter=json',
]
assert popen.call_args[1]['cwd'] == os.path.dirname(app_config['package_json_path'])
def test_get_javascript_vulnerabilities_failure(self, mock_popen, app_config):
"""Handle failures like being unable to connect to the network.
"""
app = self.get_app(app_config)
error_output = 'pretend-im-a-traceback'
mock_popen(5, error_output='pretend-im-a-traceback')
with pytest.raises(DependencySecurityCheckFailed) as err:
app.get_javascript_vulnerabilities()
assert err.value.args[0] == error_output
def test_get_javascript_vulnerabilities_found(self, mock_popen, app_config):
app = self.get_app(app_config)
# Adapated from nsp output for a jquery issue
output = json.dumps([
{
'id': 328,
'updated_at': '2017-04-20T04:19:42.040Z',
'created_at': '2017-03-20T21:50:28.000Z',
'publish_date': '2017-03-21T18:23:53.000Z',
'overview': 'This is an error',
'recommendation': 'Upgrade to v3.0.0 or greater.',
'cvss_vector': 'CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N',
'cvss_score': 7.2,
'module': 'mylibrary',
'version': '0.9.0',
'vulnerable_versions': '<1.0.0',
'patched_versions': '>=3.0.0',
'title': 'Cross-Site Scripting (XSS)',
'path': [
'socorro-webapp-django@0.0.0',
'jquery@2.1.0',
],
'advisory': 'https://nodesecurity.io/advisories/328',
},
{
'id': 327,
'updated_at': '2017-04-20T04:19:42.040Z',
'created_at': '2017-03-20T21:50:28.000Z',
'publish_date': '2017-03-21T18:23:53.000Z',
'overview': 'This is also an error',
'recommendation': 'Upgrade to v3.0.0 or greater.',
'cvss_vector': 'CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N',
'cvss_score': 7.2,
'module': 'otherlib',
'version': '1.4.0',
'vulnerable_versions': '<2.0.0',
'patched_versions': '>=3.0.0',
'title': 'Cross-Site Scripting (XSS)',
'path': [
'socorro-webapp-django@0.0.0',
'jquery@2.1.0',
],
'advisory': 'https://nodesecurity.io/advisories/327',
},
])
mock_popen(1, output=output)
assert set(app.get_javascript_vulnerabilities()) == set([
Vulnerability(
type='javascript',
dependency='mylibrary',
installed_version='0.9.0',
affected_versions='<1.0.0',
description='https://nodesecurity.io/advisories/328',
),
Vulnerability(
type='javascript',
dependency='otherlib',
installed_version='1.4.0',
affected_versions='<2.0.0',
description='https://nodesecurity.io/advisories/327',
),
])
def test_get_javascript_vulnerabilities_cannot_parse_output(self, mock_popen, app_config):
app = self.get_app(app_config)
output = '{invalid5:52"json2'
mock_popen(1, output=output)
with pytest.raises(DependencySecurityCheckFailed) as err:
app.get_javascript_vulnerabilities()
assert err.value.args[0] == 'Could not parse nsp output'
@pytest.mark.parametrize('option', ('nsp_path', 'safety_path', 'package_json_path'))
def test_run_option_validation(self, option, tmpdir, app_config):
# Error if the config option is missing
del app_config[option]
app = self.get_app(app_config)
with pytest.raises(OptionError):
app.validate_options()
# Error if the config option points to a nonexistant file
app_config[option] = tmpdir.join('does.not.exist').strpath
app = self.get_app(app_config)
with pytest.raises(OptionError):
app.validate_options()
# Error if the config option points to a directory
app_config[option] = tmpdir.join('directory').strpath
app = self.get_app(app_config)
with pytest.raises(OptionError):
app.validate_options()
# No error if the config option points to an existing file
tmpdir.join('directory').mkdir()
tmpdir.join('binary').write('fake binary')
app_config[option] = tmpdir.join('binary').strpath
app = self.get_app(app_config)
app.validate_options()
def test_run_log(self, app_config):
"""Alert via logging if there's no Sentry DSN configured."""
app = self.get_app(app_config)
vuln = Vulnerability(
type='python',
dependency='mylibrary',
installed_version='0.9.0',
affected_versions='<1.0.0',
description='This is an error',
)
with mock.patch.object(app, 'get_python_vulnerabilities', return_value=[vuln]):
with mock.patch.object(app, 'get_javascript_vulnerabilities', return_value=[]):
with mock.patch.object(app, 'alert_log'):
app.run()
app.alert_log.assert_called_with([vuln])
def test_run_raven(self, app_config):
"""Alert via Raven if there's a Sentry DSN configured."""
dsn = 'https://foo:bar@example.com/123456'
app_config['sentry.dsn'] = dsn
app = self.get_app(app_config)
vuln = Vulnerability(
type='python',
dependency='mylibrary',
installed_version='0.9.0',
affected_versions='<1.0.0',
description='This is an error',
)
with mock.patch.object(app, 'get_python_vulnerabilities', return_value=[vuln]):
with mock.patch.object(app, 'get_javascript_vulnerabilities', return_value=[]):
with mock.patch.object(app, 'alert_sentry'):
app.run()
app.alert_sentry.assert_called_with(dsn, [vuln])