forked from Yelp/detect-secrets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.py
653 lines (613 loc) · 21 KB
/
main_test.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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
import json
import shlex
import textwrap
from contextlib import contextmanager
import mock
import pytest
from detect_secrets import main as main_module
from detect_secrets import VERSION
from detect_secrets.core import audit as audit_module
from detect_secrets.main import main
from testing.factories import secrets_collection_factory
from testing.mocks import Any
from testing.mocks import mock_printer
from testing.util import uncolor
class TestMain(object):
"""These are smoke tests for the console usage of detect_secrets.
Most of the functional test cases should be within their own module tests.
"""
def test_scan_basic(self, mock_baseline_initialize):
with mock_stdin():
assert main(['scan']) == 0
mock_baseline_initialize.assert_called_once_with(
plugins=Any(tuple),
exclude_files_regex=None,
exclude_lines_regex=None,
path='.',
should_scan_all_files=False,
)
def test_scan_with_rootdir(self, mock_baseline_initialize):
with mock_stdin():
assert main('scan test_data'.split()) == 0
mock_baseline_initialize.assert_called_once_with(
plugins=Any(tuple),
exclude_files_regex=None,
exclude_lines_regex=None,
path=['test_data'],
should_scan_all_files=False,
)
def test_scan_with_exclude_args(self, mock_baseline_initialize):
with mock_stdin():
assert main(
'scan --exclude-files some_pattern_here --exclude-lines other_patt'.split(),
) == 0
mock_baseline_initialize.assert_called_once_with(
plugins=Any(tuple),
exclude_files_regex='some_pattern_here',
exclude_lines_regex='other_patt',
path='.',
should_scan_all_files=False,
)
@pytest.mark.parametrize(
'string, expected_base64_result, expected_hex_result',
[
(
'012345678ab',
'False (3.459)',
'True (3.459)',
),
(
'Benign',
'False (2.252)',
'False',
),
],
)
def test_scan_string_basic(
self,
mock_baseline_initialize,
string,
expected_base64_result,
expected_hex_result,
):
with mock_stdin(
string,
), mock_printer(
main_module,
) as printer_shim:
assert main('scan --string'.split()) == 0
assert uncolor(printer_shim.message) == textwrap.dedent(
"""
AWSKeyDetector : False
ArtifactoryDetector : False
Base64HighEntropyString: {}
BasicAuthDetector : False
HexHighEntropyString : {}
JwtTokenDetector : False
KeywordDetector : False
MailchimpDetector : False
PrivateKeyDetector : False
SlackDetector : False
StripeDetector : False
""".format(
expected_base64_result,
expected_hex_result,
),
)[1:]
mock_baseline_initialize.assert_not_called()
def test_scan_string_cli_overrides_stdin(self):
with mock_stdin(
'012345678ab',
), mock_printer(
main_module,
) as printer_shim:
assert main('scan --string 012345'.split()) == 0
assert uncolor(printer_shim.message) == textwrap.dedent("""
AWSKeyDetector : False
ArtifactoryDetector : False
Base64HighEntropyString: False (2.585)
BasicAuthDetector : False
HexHighEntropyString : False (2.121)
JwtTokenDetector : False
KeywordDetector : False
MailchimpDetector : False
PrivateKeyDetector : False
SlackDetector : False
StripeDetector : False
""")[1:]
def test_scan_with_all_files_flag(self, mock_baseline_initialize):
with mock_stdin():
assert main('scan --all-files'.split()) == 0
mock_baseline_initialize.assert_called_once_with(
plugins=Any(tuple),
exclude_files_regex=None,
exclude_lines_regex=None,
path='.',
should_scan_all_files=True,
)
def test_reads_from_stdin(self, mock_merge_baseline):
with mock_stdin(json.dumps({'key': 'value'})):
assert main(['scan']) == 0
mock_merge_baseline.assert_called_once_with(
{'key': 'value'},
Any(dict),
)
def test_reads_old_baseline_from_file(self, mock_merge_baseline):
with mock_stdin(), mock.patch(
'detect_secrets.main._read_from_file',
return_value={'key': 'value'},
) as m_read, mock.patch(
'detect_secrets.main.write_baseline_to_file',
) as m_write:
assert main('scan --update old_baseline_file'.split()) == 0
assert m_read.call_args[0][0] == 'old_baseline_file'
assert m_write.call_args[1]['filename'] == 'old_baseline_file'
assert m_write.call_args[1]['data'] == Any(dict)
mock_merge_baseline.assert_called_once_with(
{'key': 'value'},
Any(dict),
)
@pytest.mark.parametrize(
'exclude_files_arg, expected_regex',
[
(
'',
'^old_baseline_file$',
),
(
'--exclude-files "secrets/.*"',
'secrets/.*|^old_baseline_file$',
),
(
'--exclude-files "^old_baseline_file$"',
'^old_baseline_file$',
),
],
)
def test_old_baseline_ignored_with_update_flag(
self,
mock_baseline_initialize,
exclude_files_arg,
expected_regex,
):
with mock_stdin(), mock.patch(
'detect_secrets.main._read_from_file',
return_value={},
), mock.patch(
# We don't want to be creating a file during test
'detect_secrets.main.write_baseline_to_file',
) as file_writer:
assert main(
shlex.split(
'scan --update old_baseline_file {}'.format(
exclude_files_arg,
),
),
) == 0
assert (
file_writer.call_args[1]['data']['exclude']['files']
== expected_regex
)
@pytest.mark.parametrize(
'plugins_used, plugins_overwriten, plugins_wrote',
[
( # remove some plugins from baseline
[
{
'base64_limit': 4.5,
'name': 'Base64HighEntropyString',
},
{
'name': 'PrivateKeyDetector',
},
],
'--no-base64-string-scan --no-keyword-scan',
[
{
'name': 'PrivateKeyDetector',
},
],
),
( # all plugins
[
{
'base64_limit': 1.5,
'name': 'Base64HighEntropyString',
},
],
'--use-all-plugins',
[
{
'name': 'AWSKeyDetector',
},
{
'name': 'ArtifactoryDetector',
},
{
'base64_limit': 1.5,
'name': 'Base64HighEntropyString',
},
{
'name': 'BasicAuthDetector',
},
{
'hex_limit': 3,
'name': 'HexHighEntropyString',
},
{
'name': 'JwtTokenDetector',
},
{
'name': 'KeywordDetector',
},
{
'name': 'MailchimpDetector',
},
{
'name': 'PrivateKeyDetector',
},
{
'name': 'SlackDetector',
},
{
'name': 'StripeDetector',
},
],
),
( # remove some plugins from all plugins
[
{
'base64_limit': 4.5,
'name': 'Base64HighEntropyString',
},
],
'--use-all-plugins --no-base64-string-scan --no-private-key-scan',
[
{
'name': 'AWSKeyDetector',
},
{
'name': 'ArtifactoryDetector',
},
{
'name': 'BasicAuthDetector',
},
{
'hex_limit': 3,
'name': 'HexHighEntropyString',
},
{
'name': 'JwtTokenDetector',
},
{
'name': 'KeywordDetector',
},
{
'name': 'MailchimpDetector',
},
{
'name': 'SlackDetector',
},
{
'name': 'StripeDetector',
},
],
),
( # use same plugin list from baseline
[
{
'base64_limit': 3.5,
'name': 'Base64HighEntropyString',
},
{
'name': 'PrivateKeyDetector',
},
],
'',
[
{
'base64_limit': 3.5,
'name': 'Base64HighEntropyString',
},
{
'name': 'PrivateKeyDetector',
},
],
),
( # overwrite base limit from CLI
[
{
'base64_limit': 3.5,
'name': 'Base64HighEntropyString',
}, {
'name': 'PrivateKeyDetector',
},
],
'--base64-limit=5.5',
[
{
'base64_limit': 5.5,
'name': 'Base64HighEntropyString',
},
{
'name': 'PrivateKeyDetector',
},
],
),
( # does not overwrite base limit from CLI if baseline not using the plugin
[
{
'name': 'PrivateKeyDetector',
},
],
'--base64-limit=4.5',
[
{
'name': 'PrivateKeyDetector',
},
],
),
( # use overwriten option from CLI only when using --use-all-plugins
[
{
'base64_limit': 3.5,
'name': 'Base64HighEntropyString',
},
{
'name': 'PrivateKeyDetector',
},
],
'--use-all-plugins --base64-limit=5.5 --no-hex-string-scan --no-keyword-scan',
[
{
'name': 'AWSKeyDetector',
},
{
'name': 'ArtifactoryDetector',
},
{
'base64_limit': 5.5,
'name': 'Base64HighEntropyString',
},
{
'name': 'BasicAuthDetector',
},
{
'name': 'JwtTokenDetector',
},
{
'name': 'MailchimpDetector',
},
{
'name': 'PrivateKeyDetector',
},
{
'name': 'SlackDetector',
},
{
'name': 'StripeDetector',
},
],
),
( # use plugin limit from baseline when using --use-all-plugins and no input limit
[
{
'base64_limit': 2.5,
'name': 'Base64HighEntropyString',
},
{
'name': 'PrivateKeyDetector',
},
],
'--use-all-plugins --no-hex-string-scan --no-keyword-scan',
[
{
'name': 'AWSKeyDetector',
},
{
'name': 'ArtifactoryDetector',
},
{
'base64_limit': 2.5,
'name': 'Base64HighEntropyString',
},
{
'name': 'BasicAuthDetector',
},
{
'name': 'JwtTokenDetector',
},
{
'name': 'MailchimpDetector',
},
{
'name': 'PrivateKeyDetector',
},
{
'name': 'SlackDetector',
},
{
'name': 'StripeDetector',
},
],
),
],
)
def test_plugin_from_old_baseline_respected_with_update_flag(
self,
mock_baseline_initialize,
plugins_used, plugins_overwriten, plugins_wrote,
):
with mock_stdin(), mock.patch(
'detect_secrets.main._read_from_file',
return_value={
'plugins_used': plugins_used,
'results': {},
'version': VERSION,
'exclude': {
'files': '',
'lines': '',
},
},
), mock.patch(
# We don't want to be creating a file during test
'detect_secrets.main.write_baseline_to_file',
) as file_writer:
assert main(
shlex.split(
'scan --update old_baseline_file {}'.format(
plugins_overwriten,
),
),
) == 0
assert file_writer.call_args[1]['data']['plugins_used'] == \
plugins_wrote
@pytest.mark.parametrize(
'filename, expected_output',
[
(
'test_data/short_files/first_line.php',
textwrap.dedent("""
1:secret = 'notHighEnoughEntropy'
2:skipped_sequential_false_positive = '0123456789a'
3:print('second line')
4:var = 'third line'
""")[1:-1],
),
(
'test_data/short_files/middle_line.yml',
textwrap.dedent("""
1:deploy:
2: user: aaronloo
3: password:
4: secure: thequickbrownfoxjumpsoverthelazydog
5: on:
6: repo: Yelp/detect-secrets
""")[1:-1],
),
(
'test_data/short_files/last_line.ini',
textwrap.dedent("""
1:[some section]
2:secrets_for_no_one_to_find =
3: hunter2
4: password123
5: BEEF0123456789a
""")[1:-1],
),
],
)
def test_audit_short_file(self, filename, expected_output):
with mock_stdin(), mock_printer(
# To extract the baseline output
main_module,
) as printer_shim:
main(['scan', filename])
baseline = printer_shim.message
baseline_dict = json.loads(baseline)
with mock_stdin(), mock.patch(
# To pipe in printer_shim
'detect_secrets.core.audit._get_baseline_from_file',
return_value=baseline_dict,
), mock.patch(
# We don't want to clear the pytest testing screen
'detect_secrets.core.audit._clear_screen',
), mock.patch(
# Gotta mock it, because tests aren't interactive
'detect_secrets.core.audit._get_user_decision',
return_value='s',
), mock.patch(
# We don't want to write an actual file
'detect_secrets.core.audit.write_baseline_to_file',
), mock_printer(
audit_module,
) as printer_shim:
main('audit will_be_mocked'.split())
assert uncolor(printer_shim.message) == textwrap.dedent("""
Secret: 1 of 1
Filename: {}
Secret Type: {}
----------
{}
----------
Saving progress...
""")[1:].format(
filename,
baseline_dict['results'][filename][0]['type'],
expected_output,
)
@pytest.mark.parametrize(
'filename, expected_output',
[
(
'test_data/short_files/first_line.php',
{
'KeywordDetector': {
'config': {
'name': 'KeywordDetector',
},
'results': {
'negative': [],
'positive': [],
'unknown': ['nothighenoughentropy'],
},
},
},
),
],
)
def test_audit_display_results(self, filename, expected_output):
with mock_stdin(), mock_printer(
main_module,
) as printer_shim:
main(['scan', filename])
baseline = printer_shim.message
baseline_dict = json.loads(baseline)
with mock.patch(
'detect_secrets.core.audit._get_baseline_from_file',
return_value=baseline_dict,
), mock_printer(
audit_module,
) as printer_shim:
main(['audit', '--display-results', 'MOCKED'])
assert json.loads(uncolor(printer_shim.message))['results'] == expected_output
def test_audit_diff_not_enough_files(self):
assert main('audit --diff fileA'.split()) == 1
def test_audit_same_file(self):
with mock_printer(main_module) as printer_shim:
assert main('audit --diff .secrets.baseline .secrets.baseline'.split()) == 0
assert printer_shim.message.strip() == (
'No difference, because it\'s the same file!'
)
@contextmanager
def mock_stdin(response=None):
if not response:
with mock.patch('detect_secrets.main.sys') as m:
m.stdin.isatty.return_value = True
yield
else:
with mock.patch('detect_secrets.main.sys') as m:
m.stdin.isatty.return_value = False
m.stdin.read.return_value = response
yield
@pytest.fixture
def mock_baseline_initialize():
def mock_initialize_function(plugins, exclude_files_regex, *args, **kwargs):
return secrets_collection_factory(
plugins=plugins,
exclude_files_regex=exclude_files_regex,
)
with mock.patch(
'detect_secrets.main.baseline.initialize',
side_effect=mock_initialize_function,
) as mock_initialize:
yield mock_initialize
@pytest.fixture
def mock_merge_baseline():
with mock.patch(
'detect_secrets.main.baseline.merge_baseline',
) as m:
# This return value needs to have the `results` key, so that it can
# formatted appropriately for output.
m.return_value = {'results': {}}
yield m