Skip to content

Commit fe5652b

Browse files
authored
Fix private key line number (#251)
1 parent d2d7533 commit fe5652b

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

detect_secrets/plugins/private_key.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,9 +135,12 @@ def _get_updated_secrets(
135135
updated_secrets: Set[PotentialSecret] = set()
136136
for sec in found_secrets:
137137
secret_val = sec.secret_value.strip() or '' # type: ignore
138-
if split_by_newline and '\n' in secret_val:
139-
secret_val = secret_val.split('\n')[0]
140-
line_number = self.find_line_number(file_content, secret_val)
138+
pos = file_content.find(secret_val)
139+
if pos == -1:
140+
line_number = 1
141+
else:
142+
founded_secret = file_content.split(secret_val)
143+
line_number = founded_secret[0].count('\n')
141144
updated_secrets.add(
142145
PotentialSecret(
143146
type=self.secret_type,

tests/plugins/private_key_test.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,37 @@ def test_basic(file_content, secrets_amount, expected_secret):
9090
assert list(secrets.data[temp_file])[0].secret_value == expected_secret
9191

9292

93+
def test_private_key_line_number():
94+
file_content = '\n'.join([
95+
'Irrelevant line 1',
96+
'Irrelevant line 2',
97+
'Irrelevant line 3',
98+
'Irrelevant line 4',
99+
'Irrelevant line 5',
100+
'-----BEGIN RSA PRIVATE KEY-----',
101+
'MIIBVwIBADANBgkqhkiG9w0BAQEFAASC',
102+
'-----END RSA PRIVATE KEY-----',
103+
'Some trailing text',
104+
])
105+
106+
with mock_named_temporary_file() as f:
107+
f.write(file_content.encode())
108+
f.seek(0)
109+
110+
secrets = SecretsCollection()
111+
secrets.scan_file(f.name)
112+
113+
assert len(list(secrets)) == 1
114+
115+
temp_file = list(secrets.files)[0]
116+
secret_obj = list(secrets.data[temp_file])[0]
117+
118+
assert secret_obj.line_number == 6, (
119+
f'Expected the private key header to be detected at line 6, '
120+
f'but got {secret_obj.line_number} instead.'
121+
)
122+
123+
93124
@pytest.fixture(autouse=True)
94125
def configure_plugins():
95126
with transient_settings({

0 commit comments

Comments
 (0)