-
Notifications
You must be signed in to change notification settings - Fork 547
Expand file tree
/
Copy pathapi.py
More file actions
180 lines (150 loc) · 5.84 KB
/
api.py
File metadata and controls
180 lines (150 loc) · 5.84 KB
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
import os
from typing import Dict
from typing import List
from git import Repo
from detect_secrets import SecretsCollection
from detect_secrets.settings import default_settings
from detect_secrets.settings import transient_settings
def get_settings(filters: list = None, plugins: list = None) -> Dict[str, List]:
"""
Return used plugins and filters to be used to scan with provided params
"""
if filters and not isinstance(filters, list):
raise ValueError(f"Error: '{filters}' must be List object")
if plugins and not isinstance(plugins, list):
raise ValueError(f"Error: '{plugins}' must be List object")
if filters:
filters_used = filters
else:
filters_used = []
with default_settings() as settings:
for key in settings.filters:
filters_used.append({'path': key})
if plugins:
plugins_used = plugins
else:
plugins_used = []
with default_settings() as settings:
for key in settings.plugins:
plugins_used.append({'name': key})
return {'plugins': plugins_used, 'filters': filters_used}
def scan_string(
string: str, filters: list = None, plugins: list = None,
) -> Dict[str, List]:
"""
Scan a string for secrets using detect-secrets with custom filters and plugins
:param string: String to scan
:param filters: Custom filters for detect-secrets
:param plugins: Custom plugins for detect-secrets
:return: Detected secrets in str format
"""
if not isinstance(string, str):
raise ValueError(f"Error: '{string}' must be 'string' object")
if filters and not isinstance(filters, list):
raise ValueError(f"Error: '{filters}' must be List object")
if plugins and not isinstance(plugins, list):
raise ValueError(f"Error: '{plugins}' must be List object")
# Initialize a SecretsCollection
secrets = SecretsCollection()
# Load default settings if no filters and plugins provided:
if not filters and not plugins:
settings = default_settings()
# Scan the string
with settings:
secrets.scan_string(string)
return secrets.json()
elif filters and not plugins:
plugins = get_settings(plugins=plugins).get('plugins')
elif not filters and plugins:
filters = get_settings(filters=filters).get('filters')
# Scan the string
settings = transient_settings({'plugins_used': plugins, 'filters_used': filters})
with settings:
secrets.scan_string(string)
return secrets.json()
def scan_file(
filepath: str, filters: list = None, plugins: list = None,
) -> Dict[str, List]:
"""
Scan a file for secrets using detect-secrets with custom filters and plugins
:param filepath: Path to the file to scan
:param filters: Custom filters for detect-secrets
:param plugins: Custom plugins for detect-secrets
:return: Detected secrets in str format
"""
if not isinstance(filepath, str):
raise ValueError(
f"Error: '{filepath}' must be 'string' formatted path to a file",
)
if filters and not isinstance(filters, list):
raise ValueError(f"Error: '{filters}' must be List object")
if plugins and not isinstance(plugins, list):
raise ValueError(f"Error: '{plugins}' must be List object")
try:
with open(filepath, 'r') as f:
f.read()
except Exception:
raise ValueError(f"Error: Cannot read '{filepath}'")
# Initialize a SecretsCollection
secrets = SecretsCollection()
# Load default settings if no filters and plugins provided:
if not filters and not plugins:
settings = default_settings()
# Scan the file
with settings:
secrets.scan_file(filepath)
return secrets.json()
elif filters and not plugins:
plugins = get_settings(plugins=plugins).get('plugins')
elif not filters and plugins:
filters = get_settings(filters=filters).get('filters')
# Scan a file
settings = transient_settings(
{'plugins_used': plugins, 'filters_used': filters},
)
with settings:
secrets.scan_file(filepath)
return secrets.json()
def scan_git_repository(
repo_path: str,
plugins: list = None,
filters: list = None,
scan_all_files: bool = False,
) -> List[Dict]:
"""
Scan a local Git repository for secrets using the specified plugins and filters
Args:
:param repo_path: Path to the local Git repository
:param filters: Custom filters for detect-secrets
:param plugins: Custom plugins for detect-secrets
:param scan_all_files (bool): Scan all files or only Git-tracked files.
:return: Detected secrets in List format
"""
if not isinstance(scan_all_files, bool):
raise ValueError(f"Error: '{scan_all_files}' must be 'bool' type")
if not isinstance(repo_path, str):
raise ValueError(f"Error: '{repo_path}' must be 'str' type path to repository")
try:
repo = Repo(repo_path)
files_to_scan = []
if scan_all_files:
for root, _, files in os.walk(repo_path):
if '.git' in root:
continue
for file in files:
files_to_scan.append(os.path.join(root, file))
else:
files_to_scan = [
os.path.join(repo_path, item.a_path) for item in repo.index.diff(None)
]
files_to_scan.extend(
[os.path.join(repo_path, item) for item in repo.untracked_files],
)
results = []
for filepath in files_to_scan:
secrets = scan_file(filepath, plugins=plugins, filters=filters)
if secrets != {}:
results.append(secrets)
return results
except Exception:
raise ValueError(f"Error: '{repo_path}' is not a valid Git repository")