Exemple #1
0
    def test_secret_at_top_of_file(self, mock_printer):
        with self.mock_open(
                start_line=1,
                secret_line=1,
                end_line=6,
                line_containing_secret='-----BEGIN PRIVATE KEY-----',
        ):
            self.run_logic(secret_lineno=1, )

        test = textwrap.dedent("""
            Secret:      1 of 2
            Filename:    filenameA
            Secret Type: Private Key
            ----------
            1:-----BEGIN PRIVATE KEY-----
            2:e
            3:d
            4:c
            5:b
            6:a
            ----------
            {}
            ----------

        """).format(POTENTIAL_SECRET_DETECTED_NOTE)[1:-1]

        print(mock_printer.message)
        print(test)
        assert uncolor(mock_printer.message) == textwrap.dedent("""
            Secret:      1 of 2
            Filename:    filenameA
            Secret Type: Private Key
            ----------
            1:-----BEGIN PRIVATE KEY-----
            2:e
            3:d
            4:c
            5:b
            6:a
            ----------
            {}
            ----------

        """).format(POTENTIAL_SECRET_DETECTED_NOTE)[1:-1]
Exemple #2
0
def test_version_check_out_of_date():
    responses.add(
        responses.GET,
        (
            'https://detect-secrets-client-version.s3.us-south.'
            'cloud-object-storage.appdomain.cloud/version'
        ),
        status=200,
        body='1000000.0.0+ibm.0',
    )
    with mock.patch('detect_secrets.util.sys.stderr', new=StringIO()) as fakeErr:
        util.version_check()
        stderr = fakeErr.getvalue().strip()
    expected_error_msg = 'WARNING: You are running an outdated version of detect-secrets.\n' + \
        ' Your version: %s\n' % VERSION + \
        ' Latest version: 1000000.0.0+ibm.0\n' + \
        ' See upgrade guide at ' + \
        'https://ibm.biz/detect-secrets-how-to-upgrade\n'
    assert expected_error_msg == uncolor(stderr)
    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()
Exemple #4
0
    def test_secret_not_found(self, mock_printer):
        with self.mock_open(), pytest.raises(
                audit.SecretNotFoundOnSpecifiedLineError, ):
            self.run_logic(secret=potential_secret_factory(
                type_='Private Key',
                filename='filenameA',
                secret='BEGIN RSA PRIVATE KEY',
                lineno=15,
            ).json(), )

        assert uncolor(mock_printer.message) == textwrap.dedent("""
            Secret:      1 of 2
            Filename:    filenameA
            Secret Type: Private Key
            ----------
            ERROR: Secret not found on line 15!
            Try recreating your baseline to fix this issue.
            ----------

        """)[1:-1]
 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_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,
            )
 def test_multiple_failures(self, mock_client):
     with nicer_output():
         assert uncolor(
             formatter.format_results([
                 self.mock_result(
                     {
                         'operation_id': 'post_one',
                         'id': 1,
                     },
                     test_results={
                         'IDORPlugin': True,
                     },
                     client=mock_client,
                 ),
                 self.mock_result(
                     {
                         'operation_id': 'get_two',
                     },
                     {
                         'operation_id': 'post_one',
                         'id': 2,
                     },
                     test_results={
                         'IDORPlugin': True,
                     },
                     client=mock_client,
                 ),
             ]), ) == textwrap.dedent("""
             Test Failures
             test.post_one [IDORPlugin]
             Request Sequence:
             [
               "curl -X POST http://localhost:80/test/post_one --data 'id=1'"
             ]
             test.post_one [IDORPlugin]
             Request Sequence:
             [
               "curl -X GET http://localhost:80/test/get_two",
               "curl -X POST http://localhost:80/test/post_one --data 'id=2'"
             ]
         """)[1:]
 def test_basic(self, mock_client):
     with nicer_output():
         assert uncolor(
             formatter.format_results([
                 self.mock_result(
                     {
                         'operation_id': 'get_one',
                         'id': 1,
                     },
                     test_results={
                         'IDORPlugin': True,
                     },
                     client=mock_client,
                 ),
             ]), ) == textwrap.dedent("""
             Test Failures
             test.get_one [IDORPlugin]
             Request Sequence:
             [
               "curl -X GET http://localhost:80/test/get_one?id=1"
             ]
         """)[1:]
Exemple #9
0
    def test_hex_high_entropy_secret_in_yaml_file(self, mock_printer):
        with self.mock_open(
            line_containing_secret='api key: 123456789a',
        ):
            self.run_logic(
                secret=potential_secret_factory(
                    type_='Hex High Entropy String',
                    filename='filenameB',
                    secret='123456789a',
                    lineno=15,
                ),
                settings=[
                    {
                        'name': 'HexHighEntropyString',
                        'hex_limit': 3,
                    },
                ],
            )

        assert uncolor(mock_printer.message) == textwrap.dedent("""
            Secret:      1 of 2
            Filename:    filenameB
            Secret Type: Hex High Entropy String
            ----------
            10:a
            11:b
            12:c
            13:d
            14:e
            15:api key: 123456789a
            16:e
            17:d
            18:c
            19:b
            20:a
            ----------

        """)[1:-1]
    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
                Base64HighEntropyString: {}
                BasicAuthDetector      : False
                HexHighEntropyString   : {}
                KeywordDetector        : False
                PrivateKeyDetector     : False
                SlackDetector          : False
            """.format(
                expected_base64_result,
                expected_hex_result,
            ))[1:]

        mock_baseline_initialize.assert_not_called()
Exemple #11
0
    def test_keyword_secret_in_yaml_file(self, mock_printer):
        with self.mock_open(
            line_containing_secret='api_key: yerba',
        ):
            self.run_logic(
                secret=potential_secret_factory(
                    type_='Secret Keyword',
                    filename='filenameB',
                    secret='yerba',
                    lineno=15,
                ),
                settings=[
                    {
                        'name': 'KeywordDetector',
                    },
                ],
            )

        assert uncolor(mock_printer.message) == textwrap.dedent("""
            Secret:      1 of 2
            Filename:    filenameB
            Secret Type: Secret Keyword
            ----------
            10:a
            11:b
            12:c
            13:d
            14:e
            15:api_key: yerba
            16:e
            17:d
            18:c
            19:b
            20:a
            ----------

        """)[1:-1]
    def test_logging_output(self, mock_client):
        result = self.mock_result(
            {
                'operation_id': 'get_one',
            },
            test_results={
                'IDORPlugin': True,
            },
            client=mock_client,
        )
        result.log_output = 'hello'

        with nicer_output():
            assert uncolor(formatter.format_results([result
                                                     ])) == textwrap.dedent("""
                Test Failures
                test.get_one [IDORPlugin]
                Request Sequence:
                [
                  "curl -X GET http://localhost:80/test/get_one"
                ]
                Captured log calls
                hello
            """)[1:]
def test_format_summary(args, expected):
    with nicer_output():
        assert uncolor(formatter.format_summary(*args), ) == expected