Exemplo n.º 1
0
    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))['plugins'] == expected_output
    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()
Exemplo n.º 3
0
    def test_saves_to_baseline():
        # We create an empty baseline, with customized settings.
        # This way, we expect the engine to use the settings configured by the baseline,
        # but have the results replaced by the new scan.
        with transient_settings({
                'plugins_used': [
                    {
                        'name': 'Base64HighEntropyString',
                        'limit': 4.5,
                    },
                ],
        }):
            secrets = SecretsCollection()
            old_secrets = baseline.format_for_output(secrets)

        with mock_printer(
                main_module) as printer, tempfile.NamedTemporaryFile() as f:
            baseline.save_to_file(old_secrets, f.name)
            f.seek(0)

            # We also test setting the root directory through this test.
            main_module.main(['scan', 'test_data', '--baseline', f.name])

            f.seek(0)
            new_secrets = json.loads(f.read())
            assert not secrets.exactly_equals(
                baseline.load(new_secrets, f.name))
            assert new_secrets['plugins_used'] == [
                {
                    'name': 'Base64HighEntropyString',
                    'limit': 4.5,
                },
            ]
            assert not printer.message
Exemplo n.º 4
0
    def test_audit_display_results(self, filename, expected_output):
        with mock_stdin(), mock_printer(main_module, ) as printer_shim:
            wrap_detect_secrets_main('scan ' + filename)
            baseline = printer_shim.message

        baseline_dict = json.loads(baseline)
        baseline_dict['custom_plugin_paths'] = tuple(
            baseline_dict['custom_plugin_paths'])
        with mock.patch(
                'detect_secrets.core.audit._get_baseline_from_file',
                return_value=baseline_dict,
        ), mock_printer(audit_module, ) as printer_shim:
            wrap_detect_secrets_main('audit --display-results MOCKED')

            assert json.loads(uncolor(
                printer_shim.message))['plugins'] == expected_output
Exemplo n.º 5
0
 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 printer_shim.message == textwrap.dedent("""
             Base64HighEntropyString: False (2.585)
             BasicAuthDetector      : False
             HexHighEntropyString   : False (2.121)
             PrivateKeyDetector     : False
         """)[1:]
Exemplo n.º 6
0
 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) == get_plugin_report({
             'Base64HighEntropyString':
             'False (2.585)',
             'HexHighEntropyString':
             'False (2.121)',
         })
    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,
            )
Exemplo n.º 8
0
    def test_scan_string_basic(self, mock_baseline_initialize):
        with mock_stdin('012345678ab', ), mock_printer(
                main_module, ) as printer_shim:
            assert main('scan --string'.split()) == 0
            assert printer_shim.message == textwrap.dedent("""
                Base64HighEntropyString: False (3.459)
                BasicAuthDetector      : False
                HexHighEntropyString   : True  (3.459)
                PrivateKeyDetector     : False
            """)[1:]

        mock_baseline_initialize.assert_not_called()
Exemplo n.º 9
0
    def test_cli_overrides_stdin():
        with transient_settings({
                'plugins_used': [
                    {
                        'name': 'AWSKeyDetector',
                    },
                ],
        }), mock_stdin('AKIATESTTESTTESTTEST', ), mock_printer(
                main_module) as printer:
            assert main_module.main(['scan', '--string', 'blah']) == 0

            assert printer.message.strip() == 'AWSKeyDetector: False'
Exemplo n.º 10
0
    def test_adheres_to_verification_policies(args, verified_result,
                                              should_be_present):
        with register_plugin(MockPlugin(verified_result=verified_result),
                             ), mock_printer(main_module) as printer:
            main_module.main(['scan', '--string', 'fake-secret', *args])

        for line in printer.message.splitlines():
            plugin_name, result = [x.strip() for x in line.split(':')]
            if plugin_name != 'MockPlugin':
                continue

            assert should_be_present == result.startswith('True')
Exemplo n.º 11
0
    def test_works_from_different_directory():
        with tempfile.TemporaryDirectory() as d:
            subprocess.call(['git', '-C', d, 'init'])
            with open(os.path.join(d, 'credentials.yaml'), 'w') as f:
                f.write('secret: asxeqFLAGMEfxuwma!')
            subprocess.check_output(
                ['git', '-C', d, 'add', 'credentials.yaml'])

            with mock_printer(main_module) as printer:
                assert main_module.main(['-C', d, 'scan']) == 0

            results = json.loads(printer.message)['results']
            assert results
Exemplo n.º 12
0
    def test_supports_stdin():
        with transient_settings({
                'plugins_used': [
                    {
                        'name': 'AWSKeyDetector',
                    },
                ],
        }), mock_stdin('AKIATESTTESTTESTTEST', ), mock_printer(
                main_module) as printer, disable_gibberish_filter():
            assert main_module.main(['scan', '--string']) == 0

            assert printer.message.strip(
            ) == 'AWSKeyDetector: True  (unverified)'
Exemplo n.º 13
0
    def test_audit_first_line(self, filename, expected_output):
        BashColor.disable_color()

        with mock_stdin(), mock_printer(
                # To extract the baseline output
                main_module, ) as printer_shim:
            main(['--scan', filename])
            baseline = printer_shim.message

        with mock_stdin(), mock.patch(
                # To pipe in printer_shim
                'detect_secrets.core.audit._get_baseline_from_file',
                return_value=json.loads(baseline),
        ), 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._save_baseline_to_file',
                ), mock_printer(audit_module, ) as printer_shim:
            main('--audit will_be_mocked'.split())

            assert printer_shim.message == textwrap.dedent("""
                Secrets Left: 1/1
                Filename:     {}
                ----------
                {}
                ----------
                Saving progress...
            """)[1:].format(
                filename,
                expected_output,
            )

        BashColor.enable_color()
Exemplo n.º 14
0
    def test_only_displays_result_if_actual_secret():
        with mock_printer(main_module) as printer:
            main_module.main([
                'scan',
                '--only-allowlisted',
                '--disable-plugin', 'KeywordDetector',
                'test_data/config.ini',
            ])

        output = json.loads(printer.message)

        # The only allowlisted item in this is an entirely numerical string, so this
        # should not be detected.
        assert not output['results']
Exemplo n.º 15
0
 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)
             KeywordDetector        : False
             PrivateKeyDetector     : False
             SlackDetector          : False
             StripeDetector         : False
         """)[1:]
Exemplo n.º 16
0
    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) == get_plugin_report({
                'Base64HighEntropyString':
                expected_base64_result,
                'HexHighEntropyString':
                expected_hex_result,
            })

        mock_baseline_initialize.assert_not_called()
Exemplo n.º 17
0
    def test_basic(mock_log):
        with mock_printer(main_module) as printer:
            main_module.main(['scan', '--only-allowlisted', 'test_data/config.yaml'])

        output = json.loads(printer.message)
        assert len(output['results']) == 1

        # Baseline carries this configuration.
        assert 'detect_secrets.filters.allowlist.is_line_allowlisted' not in {
            item['path']
            for item in output['filters_used']
        }

        with tempfile.NamedTemporaryFile() as f, mock.patch(
            'detect_secrets.audit.io.get_user_decision',
            return_value='s',
        ):
            f.write(printer.message.encode())
            f.seek(0)

            main_module.main(['audit', f.name])

        assert 'Nothing to audit' not in mock_log.info_messages
Exemplo n.º 18
0
    def test_basic():
        with mock_printer(main_module) as printer:
            main_module.main(['scan', '--slim', 'test_data'])

            assert 'generated_at' not in printer.message
            assert 'line_number' not in printer.message
Exemplo n.º 19
0
def test_list_all_plugins():
    with mock_printer(main_module) as printer:
        assert main_module.main(['scan', '--list-all-plugins']) == 0

    assert printer.message
Exemplo n.º 20
0
    def test_outputs_baseline_if_none_supplied():
        with mock_printer(main_module) as printer:
            main_module.main(['scan'])

        assert printer.message
Exemplo n.º 21
0
 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!')
Exemplo n.º 22
0
def printer():
    printer = PrinterShim()
    with mock_printer(main_module, shim=printer), mock_printer(io,
                                                               shim=printer):
        yield printer