scanoss 1.30.0__py3-none-any.whl → 1.31.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- scanoss/__init__.py +1 -1
- scanoss/cli.py +573 -188
- scanoss/data/build_date.txt +1 -1
- scanoss/export/dependency_track.py +101 -100
- scanoss/file_filters.py +1 -5
- scanoss/inspection/dependency_track/project_violation.py +443 -0
- scanoss/inspection/policy_check.py +54 -23
- scanoss/inspection/{component_summary.py → raw/component_summary.py} +3 -3
- scanoss/inspection/{copyleft.py → raw/copyleft.py} +63 -54
- scanoss/inspection/{license_summary.py → raw/license_summary.py} +5 -4
- scanoss/inspection/{inspect_base.py → raw/raw_base.py} +9 -6
- scanoss/inspection/{undeclared_component.py → raw/undeclared_component.py} +29 -25
- scanoss/services/dependency_track_service.py +131 -0
- {scanoss-1.30.0.dist-info → scanoss-1.31.0.dist-info}/METADATA +1 -1
- {scanoss-1.30.0.dist-info → scanoss-1.31.0.dist-info}/RECORD +19 -17
- {scanoss-1.30.0.dist-info → scanoss-1.31.0.dist-info}/WHEEL +0 -0
- {scanoss-1.30.0.dist-info → scanoss-1.31.0.dist-info}/entry_points.txt +0 -0
- {scanoss-1.30.0.dist-info → scanoss-1.31.0.dist-info}/licenses/LICENSE +0 -0
- {scanoss-1.30.0.dist-info → scanoss-1.31.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
Copyright (c) 2025, SCANOSS
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in
|
|
14
|
+
all copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
22
|
+
THE SOFTWARE.
|
|
23
|
+
"""
|
|
24
|
+
import json
|
|
25
|
+
import time
|
|
26
|
+
from datetime import datetime
|
|
27
|
+
from typing import Any, Dict, List, Optional, TypedDict
|
|
28
|
+
|
|
29
|
+
from ...services.dependency_track_service import DependencyTrackService
|
|
30
|
+
from ..policy_check import PolicyCheck, PolicyStatus
|
|
31
|
+
|
|
32
|
+
# Constants
|
|
33
|
+
PROCESSING_RETRY_DELAY = 5 # seconds
|
|
34
|
+
DEFAULT_TIME_OUT = 300
|
|
35
|
+
MILLISECONDS_TO_SECONDS = 1000
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
"""
|
|
39
|
+
Dependency Track project violation policy check implementation.
|
|
40
|
+
|
|
41
|
+
This module provides policy checking functionality for Dependency Track project violations.
|
|
42
|
+
It retrieves, processes, and formats policy violations from a Dependency Track instance
|
|
43
|
+
for a specific project.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
class ResolvedLicenseDict(TypedDict):
|
|
47
|
+
"""TypedDict for resolved license information from Dependency Track."""
|
|
48
|
+
uuid: str
|
|
49
|
+
name: str
|
|
50
|
+
licenseId: str
|
|
51
|
+
isOsiApproved: bool
|
|
52
|
+
isFsfLibre: bool
|
|
53
|
+
isDeprecatedLicenseId: bool
|
|
54
|
+
isCustomLicense: bool
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ProjectDict(TypedDict):
|
|
58
|
+
"""TypedDict for project information from Dependency Track."""
|
|
59
|
+
authors: List[str]
|
|
60
|
+
name: str
|
|
61
|
+
version: str
|
|
62
|
+
classifier: str
|
|
63
|
+
collectionLogic: str
|
|
64
|
+
uuid: str
|
|
65
|
+
properties: List[Any]
|
|
66
|
+
tags: List[str]
|
|
67
|
+
lastBomImport: int
|
|
68
|
+
lastBomImportFormat: str
|
|
69
|
+
lastInheritedRiskScore: float
|
|
70
|
+
lastVulnerabilityAnalysis: int
|
|
71
|
+
active: bool
|
|
72
|
+
isLatest: bool
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ComponentDict(TypedDict):
|
|
76
|
+
"""TypedDict for component information from Dependency Track."""
|
|
77
|
+
authors: List[str]
|
|
78
|
+
name: str
|
|
79
|
+
version: str
|
|
80
|
+
classifier: str
|
|
81
|
+
purl: str
|
|
82
|
+
purlCoordinates: str
|
|
83
|
+
resolvedLicense: ResolvedLicenseDict
|
|
84
|
+
project: ProjectDict
|
|
85
|
+
lastInheritedRiskScore: float
|
|
86
|
+
uuid: str
|
|
87
|
+
expandDependencyGraph: bool
|
|
88
|
+
isInternal: bool
|
|
89
|
+
cpe: Optional[str]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class PolicyDict(TypedDict):
|
|
93
|
+
"""TypedDict for policy information from Dependency Track."""
|
|
94
|
+
name: str
|
|
95
|
+
operator: str
|
|
96
|
+
violationState: str
|
|
97
|
+
uuid: str
|
|
98
|
+
includeChildren: bool
|
|
99
|
+
onlyLatestProjectVersion: bool
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class PolicyConditionDict(TypedDict):
|
|
103
|
+
"""TypedDict for policy condition information from Dependency Track."""
|
|
104
|
+
policy: PolicyDict
|
|
105
|
+
operator: str
|
|
106
|
+
subject: str
|
|
107
|
+
value: str
|
|
108
|
+
uuid: str
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class PolicyViolationDict(TypedDict):
|
|
112
|
+
"""TypedDict for policy violation information from Dependency Track."""
|
|
113
|
+
type: str
|
|
114
|
+
project: ProjectDict
|
|
115
|
+
component: ComponentDict
|
|
116
|
+
policyCondition: PolicyConditionDict
|
|
117
|
+
timestamp: int
|
|
118
|
+
uuid: str
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class DependencyTrackProjectViolationPolicyCheck(PolicyCheck[PolicyViolationDict]):
|
|
122
|
+
"""
|
|
123
|
+
Policy check implementation for Dependency Track project violations.
|
|
124
|
+
|
|
125
|
+
This class handles retrieving, processing, and formatting policy violations
|
|
126
|
+
from a Dependency Track instance for a specific project.
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
def __init__( # noqa: PLR0913
|
|
130
|
+
self,
|
|
131
|
+
debug: bool = False,
|
|
132
|
+
trace: bool = False,
|
|
133
|
+
quiet: bool = False,
|
|
134
|
+
project_id: str = None,
|
|
135
|
+
project_name: str = None,
|
|
136
|
+
project_version: str = None,
|
|
137
|
+
api_key: str = None,
|
|
138
|
+
url: str = None,
|
|
139
|
+
upload_token: str = None,
|
|
140
|
+
timeout: float = DEFAULT_TIME_OUT,
|
|
141
|
+
format_type: str = None,
|
|
142
|
+
status: str = None,
|
|
143
|
+
output: str = None,
|
|
144
|
+
):
|
|
145
|
+
"""
|
|
146
|
+
Initialise the Dependency Track project violation policy checker.
|
|
147
|
+
|
|
148
|
+
Args:
|
|
149
|
+
debug: Enable debug output
|
|
150
|
+
trace: Enable trace output
|
|
151
|
+
quiet: Enable quiet mode
|
|
152
|
+
project_id: UUID of the project in Dependency Track
|
|
153
|
+
project_name: Name of the project in Dependency Track
|
|
154
|
+
project_version: Version of the project in Dependency Track
|
|
155
|
+
api_key: API key for Dependency Track authentication
|
|
156
|
+
url: Base URL of the Dependency Track instance
|
|
157
|
+
upload_token: Upload token for uploading BOMs to Dependency Track
|
|
158
|
+
format_type: Output format type (json, markdown, etc.)
|
|
159
|
+
status: Status output destination
|
|
160
|
+
output: Results output destination
|
|
161
|
+
timeout: Timeout for processing in seconds (default: 300)
|
|
162
|
+
"""
|
|
163
|
+
super().__init__(debug, trace, quiet, format_type, status, 'dependency-track', output)
|
|
164
|
+
self.url = url
|
|
165
|
+
self.api_key = api_key
|
|
166
|
+
self.project_id = project_id
|
|
167
|
+
self.project_name = project_name
|
|
168
|
+
self.project_version = project_version
|
|
169
|
+
self.upload_token = upload_token
|
|
170
|
+
self.timeout = timeout
|
|
171
|
+
self.dep_track_service = DependencyTrackService(self.api_key, self.url, debug=debug, trace=trace, quiet=quiet)
|
|
172
|
+
|
|
173
|
+
def _json(self, project_violations: list[PolicyViolationDict]) -> Dict[str, Any]:
|
|
174
|
+
"""
|
|
175
|
+
Format project violations as JSON.
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
project_violations: List of policy violations from Dependency Track
|
|
179
|
+
|
|
180
|
+
Returns:
|
|
181
|
+
Dictionary containing JSON formatted results and summary
|
|
182
|
+
"""
|
|
183
|
+
return {
|
|
184
|
+
"details": json.dumps(project_violations, indent=2),
|
|
185
|
+
"summary": f'{len(project_violations)} policy violations were found.\n',
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
def _markdown(self, project_violations: list[PolicyViolationDict]) -> Dict[str, Any]:
|
|
189
|
+
"""
|
|
190
|
+
Format Dependency Track violations to Markdown format.
|
|
191
|
+
|
|
192
|
+
Args:
|
|
193
|
+
project_violations: List of policy violations from Dependency Track
|
|
194
|
+
|
|
195
|
+
Returns:
|
|
196
|
+
Dictionary with formatted Markdown details and summary
|
|
197
|
+
"""
|
|
198
|
+
return self._md_summary_generator(project_violations, self.generate_table)
|
|
199
|
+
|
|
200
|
+
def _jira_markdown(self, data: list[PolicyViolationDict]) -> Dict[str, Any]:
|
|
201
|
+
"""
|
|
202
|
+
Format project violations for Jira Markdown.
|
|
203
|
+
|
|
204
|
+
Args:
|
|
205
|
+
data: List of policy violations from Dependency Track
|
|
206
|
+
|
|
207
|
+
Returns:
|
|
208
|
+
Dictionary containing Jira markdown formatted results and summary
|
|
209
|
+
"""
|
|
210
|
+
return self._md_summary_generator(data, self.generate_jira_table)
|
|
211
|
+
|
|
212
|
+
def is_project_updated(self, dt_project: Dict[str, Any]) -> bool:
|
|
213
|
+
"""
|
|
214
|
+
Check if a Dependency Track project has completed processing.
|
|
215
|
+
|
|
216
|
+
This method determines if a project has finished processing by comparing
|
|
217
|
+
the timestamps of the last BOM import, vulnerability analysis, and last
|
|
218
|
+
occurrence metrics. A project is considered updated when either the
|
|
219
|
+
vulnerability analysis or the metrics' last occurrence timestamp is greater
|
|
220
|
+
than or equal to the last BOM import timestamp.
|
|
221
|
+
|
|
222
|
+
Args:
|
|
223
|
+
dt_project: Project dictionary from Dependency Track containing
|
|
224
|
+
project metadata and timestamps
|
|
225
|
+
|
|
226
|
+
Returns:
|
|
227
|
+
True if the project has completed processing (vulnerability analysis
|
|
228
|
+
or metrics are up to date with the last BOM import), False otherwise
|
|
229
|
+
"""
|
|
230
|
+
if not dt_project:
|
|
231
|
+
self.print_stderr('Warning: No project details supplied. Returning False.')
|
|
232
|
+
return False
|
|
233
|
+
last_import = dt_project.get('lastBomImport', 0)
|
|
234
|
+
last_vulnerability_analysis = dt_project.get('lastVulnerabilityAnalysis', 0)
|
|
235
|
+
metrics = dt_project.get('metrics', {})
|
|
236
|
+
last_occurrence = metrics.get('lastOccurrence', 0) if isinstance(metrics, dict) else 0
|
|
237
|
+
if self.debug:
|
|
238
|
+
self.print_msg(f'last_import: {last_import}')
|
|
239
|
+
self.print_msg(f'last_vulnerability_analysis: {last_vulnerability_analysis}')
|
|
240
|
+
self.print_msg(f'last_occurrence: {last_occurrence}')
|
|
241
|
+
self.print_msg(f'last_vulnerability_analysis is updated: {last_vulnerability_analysis >= last_import}')
|
|
242
|
+
self.print_msg(f'last_occurrence is updated: {last_occurrence >= last_import}')
|
|
243
|
+
if last_vulnerability_analysis == 0 or last_occurrence == 0 or last_import == 0:
|
|
244
|
+
self.print_stderr(f'Warning: Some project data appears to be unset. Returning False: {dt_project}')
|
|
245
|
+
return False
|
|
246
|
+
# True if: Both vulnerability analysis and metrics calculation newer than last BOM upload
|
|
247
|
+
return last_vulnerability_analysis >= last_import and last_occurrence >= last_import
|
|
248
|
+
|
|
249
|
+
def _wait_processing_by_project_id(self) -> Optional[Any] or None:
|
|
250
|
+
"""
|
|
251
|
+
Wait for project processing to complete in Dependency Track.
|
|
252
|
+
|
|
253
|
+
Returns:
|
|
254
|
+
Return the project or None if processing fails or times out
|
|
255
|
+
"""
|
|
256
|
+
start_time = time.time()
|
|
257
|
+
while True:
|
|
258
|
+
self.print_debug('Starting...')
|
|
259
|
+
dt_project = self.dep_track_service.get_project_by_id(self.project_id)
|
|
260
|
+
if not dt_project:
|
|
261
|
+
self.print_stderr(f'Failed to get project by id: {self.project_id}')
|
|
262
|
+
return None
|
|
263
|
+
is_project_updated = self.is_project_updated(dt_project)
|
|
264
|
+
if is_project_updated: # Project updated, return it
|
|
265
|
+
return dt_project
|
|
266
|
+
# Check timeout
|
|
267
|
+
if time.time() - start_time > self.timeout:
|
|
268
|
+
self.print_msg(f'Warning: Timeout reached ({self.timeout}s) while waiting for project processing')
|
|
269
|
+
return dt_project
|
|
270
|
+
time.sleep(PROCESSING_RETRY_DELAY)
|
|
271
|
+
self.print_debug('Checking if complete...')
|
|
272
|
+
# End while loop
|
|
273
|
+
|
|
274
|
+
def _wait_processing_by_project_status(self):
|
|
275
|
+
"""
|
|
276
|
+
Wait for project processing to complete in Dependency Track.
|
|
277
|
+
|
|
278
|
+
Returns:
|
|
279
|
+
Project status dictionary or None if processing fails or times out
|
|
280
|
+
"""
|
|
281
|
+
start_time = time.time()
|
|
282
|
+
while True:
|
|
283
|
+
status = self.dep_track_service.get_project_status(self.upload_token)
|
|
284
|
+
if status is None:
|
|
285
|
+
self.print_stderr(f'Error getting project status for upload token: {self.upload_token}')
|
|
286
|
+
break
|
|
287
|
+
if status and not status.get('processing'):
|
|
288
|
+
self.print_debug(f'Project Status: {status}')
|
|
289
|
+
break
|
|
290
|
+
if time.time() - start_time > self.timeout:
|
|
291
|
+
self.print_msg(f'Timeout reached ({self.timeout}s) while waiting for project processing')
|
|
292
|
+
break
|
|
293
|
+
time.sleep(PROCESSING_RETRY_DELAY)
|
|
294
|
+
self.print_debug('Checking if complete...')
|
|
295
|
+
# End while loop
|
|
296
|
+
|
|
297
|
+
def _wait_project_processing(self):
|
|
298
|
+
"""
|
|
299
|
+
Wait for project processing to complete in Dependency Track.
|
|
300
|
+
|
|
301
|
+
Returns:
|
|
302
|
+
Project status dictionary or None if processing fails
|
|
303
|
+
"""
|
|
304
|
+
if self.upload_token:
|
|
305
|
+
self.print_debug("Using upload token to check project status")
|
|
306
|
+
self._wait_processing_by_project_status()
|
|
307
|
+
self.print_debug("Using project id to get project status")
|
|
308
|
+
return self._wait_processing_by_project_id()
|
|
309
|
+
|
|
310
|
+
def _set_project_id(self) -> None:
|
|
311
|
+
"""
|
|
312
|
+
Set the project ID based on the project name and version if not already set.
|
|
313
|
+
If no project id is specified, this method will attempt to retrieve the project based on name/version.
|
|
314
|
+
|
|
315
|
+
Raises:
|
|
316
|
+
ValueError: If the project name/version is missing or the project is not found.
|
|
317
|
+
RuntimeError: If there's an error communicating with Dependency Track.
|
|
318
|
+
"""
|
|
319
|
+
if self.project_id is not None:
|
|
320
|
+
return
|
|
321
|
+
if self.project_name is None or self.project_version is None:
|
|
322
|
+
raise ValueError(
|
|
323
|
+
"Error: Project name and version must be specified when not using project ID"
|
|
324
|
+
)
|
|
325
|
+
self.print_debug(f'Searching for project id by name and version: {self.project_name}@{self.project_version}')
|
|
326
|
+
dt_project = self.dep_track_service.get_project_by_name_version(self.project_name, self.project_version)
|
|
327
|
+
self.print_debug(f'dt_project: {dt_project}')
|
|
328
|
+
if dt_project is None:
|
|
329
|
+
raise ValueError(f'Error: Project {self.project_name}@{self.project_version} not found in Dependency Track')
|
|
330
|
+
self.project_id = dt_project.get('uuid')
|
|
331
|
+
if not self.project_id:
|
|
332
|
+
self.print_stderr(f'Error: Failed to get project uuid from: {dt_project}')
|
|
333
|
+
raise ValueError(f'Error: Project {self.project_name}@{self.project_version} does not have a valid UUID')
|
|
334
|
+
|
|
335
|
+
@staticmethod
|
|
336
|
+
def _sort_project_violations(violations: List[PolicyViolationDict]) -> List[PolicyViolationDict]:
|
|
337
|
+
"""
|
|
338
|
+
Sort project violations by priority.
|
|
339
|
+
|
|
340
|
+
Sorts violations with SECURITY issues first, followed by LICENSE,
|
|
341
|
+
then OTHER types.
|
|
342
|
+
|
|
343
|
+
Args:
|
|
344
|
+
violations: List of policy violation dictionaries
|
|
345
|
+
|
|
346
|
+
Returns:
|
|
347
|
+
Sorted list of policy violations
|
|
348
|
+
"""
|
|
349
|
+
type_priority = {'SECURITY': 3, 'LICENSE': 2, 'OTHER': 1}
|
|
350
|
+
return sorted(
|
|
351
|
+
violations,
|
|
352
|
+
key=lambda x: -type_priority.get(x.get('type', 'OTHER'), 1)
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
def _md_summary_generator(self, project_violations: list[PolicyViolationDict], table_generator):
|
|
356
|
+
"""
|
|
357
|
+
Generates a Markdown summary of project policy violations.
|
|
358
|
+
|
|
359
|
+
Args:
|
|
360
|
+
project_violations (list[PolicyViolationDict]): A list of dictionaries containing details of
|
|
361
|
+
project policy violations, including violation state, risk type, policy name, component details,
|
|
362
|
+
and timestamp.
|
|
363
|
+
table_generator (function): A callable function responsible for generating the Markdown table
|
|
364
|
+
using headers, rows, and optionally highlighted columns.
|
|
365
|
+
|
|
366
|
+
Returns:
|
|
367
|
+
dict: A dictionary with two keys:
|
|
368
|
+
- "details" containing a Markdown-compatible string with detailed project violations
|
|
369
|
+
rendered as a table
|
|
370
|
+
- "summary" summarising the number of violations found
|
|
371
|
+
"""
|
|
372
|
+
if project_violations is None:
|
|
373
|
+
self.print_stderr('Warning: No project violations found. Returning empty results.')
|
|
374
|
+
return {
|
|
375
|
+
"details": "h3. Dependency Track Project Violations\n\nNo policy violations found.\n",
|
|
376
|
+
"summary": "0 policy violations were found.\n",
|
|
377
|
+
}
|
|
378
|
+
headers = ['State', 'Risk Type', 'Policy Name', 'Component', 'Date']
|
|
379
|
+
c_cols = [0, 1]
|
|
380
|
+
rows: List[List[str]] = []
|
|
381
|
+
|
|
382
|
+
for project_violation in project_violations:
|
|
383
|
+
timestamp = project_violation['timestamp']
|
|
384
|
+
timestamp_seconds = timestamp / MILLISECONDS_TO_SECONDS
|
|
385
|
+
formatted_date = datetime.fromtimestamp(timestamp_seconds).strftime("%d %b %Y at %H:%M:%S")
|
|
386
|
+
|
|
387
|
+
row = [
|
|
388
|
+
project_violation['policyCondition']["policy"]["violationState"],
|
|
389
|
+
project_violation['type'],
|
|
390
|
+
project_violation['policyCondition']["policy"]["name"],
|
|
391
|
+
f'{project_violation["component"]["purl"]}@{project_violation["component"]["version"]}',
|
|
392
|
+
formatted_date,
|
|
393
|
+
]
|
|
394
|
+
rows.append(row)
|
|
395
|
+
|
|
396
|
+
return {
|
|
397
|
+
"details": f'### Dependency Track Project Violations\n{table_generator(headers, rows, c_cols)}\n',
|
|
398
|
+
"summary": f'{len(project_violations)} policy violations were found.\n',
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
def run(self) -> int:
|
|
402
|
+
"""
|
|
403
|
+
Runs the primary execution logic of the instance.
|
|
404
|
+
|
|
405
|
+
Returns:
|
|
406
|
+
int: Status code indicating the result of the run process. Possible
|
|
407
|
+
values are derived from the PolicyStatus enumeration.
|
|
408
|
+
FAIL if violations are found, SUCCESS if no violations are found, ERROR if an error occurs.
|
|
409
|
+
|
|
410
|
+
Raises:
|
|
411
|
+
ValueError: If an invalid format is specified during the execution.
|
|
412
|
+
"""
|
|
413
|
+
# Set project ID based on name/version if needed
|
|
414
|
+
self._set_project_id()
|
|
415
|
+
if self.debug:
|
|
416
|
+
self.print_msg(f'URL: {self.url}')
|
|
417
|
+
self.print_msg(f'Project Id: {self.project_id}')
|
|
418
|
+
self.print_msg(f'Project Name: {self.project_name}')
|
|
419
|
+
self.print_msg(f'Project Version: {self.project_version}')
|
|
420
|
+
self.print_msg(f'API Key: {"*" * len(self.api_key)}')
|
|
421
|
+
self.print_msg(f'Format: {self.format_type}')
|
|
422
|
+
self.print_msg(f'Status: {self.status}')
|
|
423
|
+
self.print_msg(f'Output: {self.output}')
|
|
424
|
+
self.print_msg(f'Timeout: {self.timeout}')
|
|
425
|
+
# Confirm processing is complete before returning project violations
|
|
426
|
+
dt_project = self._wait_project_processing()
|
|
427
|
+
if not dt_project:
|
|
428
|
+
return PolicyStatus.ERROR.value
|
|
429
|
+
# Get project violations from Dependency Track
|
|
430
|
+
dt_project_violations = self.dep_track_service.get_project_violations(self.project_id)
|
|
431
|
+
# Sort violations by priority and format output
|
|
432
|
+
formatter = self._get_formatter()
|
|
433
|
+
if formatter is None:
|
|
434
|
+
self.print_stderr('Error: Invalid format specified.')
|
|
435
|
+
return PolicyStatus.ERROR.value
|
|
436
|
+
# Format and output data
|
|
437
|
+
data = formatter(self._sort_project_violations(dt_project_violations))
|
|
438
|
+
self.print_to_file_or_stdout(data['details'], self.output)
|
|
439
|
+
self.print_to_file_or_stderr(data['summary'], self.status)
|
|
440
|
+
# Return appropriate status based on violation count
|
|
441
|
+
if len(dt_project_violations) > 0:
|
|
442
|
+
return PolicyStatus.POLICY_FAIL.value
|
|
443
|
+
return PolicyStatus.POLICY_SUCCESS.value
|
|
@@ -24,9 +24,9 @@ SPDX-License-Identifier: MIT
|
|
|
24
24
|
|
|
25
25
|
from abc import abstractmethod
|
|
26
26
|
from enum import Enum
|
|
27
|
-
from typing import Any, Callable, Dict, List
|
|
27
|
+
from typing import Any, Callable, Dict, Generic, List, TypeVar
|
|
28
28
|
|
|
29
|
-
from
|
|
29
|
+
from ..scanossbase import ScanossBase
|
|
30
30
|
from .utils.license_utils import LicenseUtil
|
|
31
31
|
|
|
32
32
|
|
|
@@ -35,19 +35,20 @@ class PolicyStatus(Enum):
|
|
|
35
35
|
Enumeration representing the status of a policy check.
|
|
36
36
|
|
|
37
37
|
Attributes:
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
ERROR (int): Indicates that an error occurred during the policy check (value:
|
|
38
|
+
POLICY_SUCCESS (int): Indicates that the policy check passed successfully (value: 0).
|
|
39
|
+
POLICY_FAIL (int): Indicates that the policy check failed (value: 2).
|
|
40
|
+
ERROR (int): Indicates that an error occurred during the policy check (value: 1).
|
|
41
41
|
"""
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
ERROR = 2
|
|
42
|
+
POLICY_SUCCESS = 0
|
|
43
|
+
POLICY_FAIL = 2
|
|
44
|
+
ERROR = 1
|
|
46
45
|
#
|
|
47
46
|
# End of PolicyStatus Class
|
|
48
47
|
#
|
|
49
48
|
|
|
50
|
-
|
|
49
|
+
T = TypeVar('T')
|
|
50
|
+
|
|
51
|
+
class PolicyCheck(ScanossBase, Generic[T]):
|
|
51
52
|
"""
|
|
52
53
|
A base class for implementing various software policy checks.
|
|
53
54
|
|
|
@@ -66,19 +67,17 @@ class PolicyCheck(InspectBase):
|
|
|
66
67
|
debug: bool = False,
|
|
67
68
|
trace: bool = False,
|
|
68
69
|
quiet: bool = False,
|
|
69
|
-
filepath: str = None,
|
|
70
70
|
format_type: str = None,
|
|
71
71
|
status: str = None,
|
|
72
|
-
output: str = None,
|
|
73
72
|
name: str = None,
|
|
73
|
+
output: str = None,
|
|
74
74
|
):
|
|
75
|
-
super().__init__(debug, trace, quiet
|
|
75
|
+
super().__init__(debug, trace, quiet)
|
|
76
76
|
self.license_util = LicenseUtil()
|
|
77
|
-
self.filepath = filepath
|
|
78
77
|
self.name = name
|
|
79
78
|
self.format_type = format_type
|
|
80
79
|
self.status = status
|
|
81
|
-
self.
|
|
80
|
+
self.output = output
|
|
82
81
|
|
|
83
82
|
@abstractmethod
|
|
84
83
|
def run(self):
|
|
@@ -99,41 +98,41 @@ class PolicyCheck(InspectBase):
|
|
|
99
98
|
pass
|
|
100
99
|
|
|
101
100
|
@abstractmethod
|
|
102
|
-
def _json(self,
|
|
101
|
+
def _json(self, data: list[T]) -> Dict[str, Any]:
|
|
103
102
|
"""
|
|
104
103
|
Format the policy checks results as JSON.
|
|
105
104
|
This method should be implemented by subclasses to create a Markdown representation
|
|
106
105
|
of the policy check results.
|
|
107
106
|
|
|
108
|
-
:param
|
|
107
|
+
:param data: List of data to be formatted.
|
|
109
108
|
:return: A dictionary containing two keys:
|
|
110
|
-
- '
|
|
109
|
+
- 'results': A JSON-formatted string with the full list of components
|
|
111
110
|
- 'summary': A string summarizing the number of components found
|
|
112
111
|
"""
|
|
113
112
|
pass
|
|
114
113
|
|
|
115
114
|
@abstractmethod
|
|
116
|
-
def _markdown(self,
|
|
115
|
+
def _markdown(self, data: list[T]) -> Dict[str, Any]:
|
|
117
116
|
"""
|
|
118
117
|
Generate Markdown output for the policy check results.
|
|
119
118
|
|
|
120
119
|
This method should be implemented by subclasses to create a Markdown representation
|
|
121
120
|
of the policy check results.
|
|
122
121
|
|
|
123
|
-
:param
|
|
122
|
+
:param data: List of data to be included in the output.
|
|
124
123
|
:return: A dictionary representing the Markdown output.
|
|
125
124
|
"""
|
|
126
125
|
pass
|
|
127
126
|
|
|
128
127
|
@abstractmethod
|
|
129
|
-
def _jira_markdown(self,
|
|
128
|
+
def _jira_markdown(self, data: list[T]) -> Dict[str, Any]:
|
|
130
129
|
"""
|
|
131
130
|
Generate Markdown output for the policy check results.
|
|
132
131
|
|
|
133
132
|
This method should be implemented by subclasses to create a Markdown representation
|
|
134
133
|
of the policy check results.
|
|
135
134
|
|
|
136
|
-
:param
|
|
135
|
+
:param data: List of data to be included in the output.
|
|
137
136
|
:return: A dictionary representing the Markdown output.
|
|
138
137
|
"""
|
|
139
138
|
pass
|
|
@@ -208,7 +207,6 @@ class PolicyCheck(InspectBase):
|
|
|
208
207
|
self.print_stderr(f'Format: {self.format_type}')
|
|
209
208
|
self.print_stderr(f'Status: {self.status}')
|
|
210
209
|
self.print_stderr(f'Output: {self.output}')
|
|
211
|
-
self.print_stderr(f'Input: {self.filepath}')
|
|
212
210
|
|
|
213
211
|
def _is_valid_format(self) -> bool:
|
|
214
212
|
"""
|
|
@@ -224,6 +222,39 @@ class PolicyCheck(InspectBase):
|
|
|
224
222
|
self.print_stderr(f'ERROR: Invalid format "{self.format_type}". Valid formats are: {valid_formats_str}')
|
|
225
223
|
return False
|
|
226
224
|
return True
|
|
225
|
+
|
|
226
|
+
def _generate_formatter_report(self, components: list[Dict]):
|
|
227
|
+
"""
|
|
228
|
+
Generates a formatted report for a given component based on the defined formatter.
|
|
229
|
+
|
|
230
|
+
Parameters:
|
|
231
|
+
components (List[dict]): A list of dictionaries representing the components to be
|
|
232
|
+
processed and formatted. Each dictionary contains detailed information that adheres
|
|
233
|
+
to the format requirements for the specified formatter.
|
|
234
|
+
|
|
235
|
+
Returns:
|
|
236
|
+
Tuple[int, dict]: A tuple where the first element represents the policy status code
|
|
237
|
+
and the second element is a dictionary containing formatted results information,
|
|
238
|
+
typically with keys 'details' and 'summary'.
|
|
239
|
+
|
|
240
|
+
Raises:
|
|
241
|
+
KeyError: When a required key is missing from the provided component, causing the
|
|
242
|
+
formatter to fail.
|
|
243
|
+
ValueError: If an invalid component is passed and renders unable to process.
|
|
244
|
+
"""
|
|
245
|
+
# Get a formatter for the output results
|
|
246
|
+
formatter = self._get_formatter()
|
|
247
|
+
if formatter is None:
|
|
248
|
+
return PolicyStatus.ERROR.value, {}
|
|
249
|
+
# Format the results
|
|
250
|
+
data = formatter(components)
|
|
251
|
+
## Save outputs if required
|
|
252
|
+
self.print_to_file_or_stdout(data['details'], self.output)
|
|
253
|
+
self.print_to_file_or_stderr(data['summary'], self.status)
|
|
254
|
+
# Check to see if we have policy violations
|
|
255
|
+
if len(components) > 0:
|
|
256
|
+
return PolicyStatus.POLICY_FAIL.value, data
|
|
257
|
+
return PolicyStatus.POLICY_SUCCESS.value, data
|
|
227
258
|
#
|
|
228
259
|
# End of PolicyCheck Class
|
|
229
260
|
#
|
|
@@ -24,10 +24,10 @@ SPDX-License-Identifier: MIT
|
|
|
24
24
|
|
|
25
25
|
import json
|
|
26
26
|
|
|
27
|
-
from .
|
|
27
|
+
from .raw_base import RawBase
|
|
28
28
|
|
|
29
29
|
|
|
30
|
-
class ComponentSummary(
|
|
30
|
+
class ComponentSummary(RawBase):
|
|
31
31
|
def _get_component_summary_from_components(self, scan_components: list)-> dict:
|
|
32
32
|
"""
|
|
33
33
|
Get a component summary from detected components.
|
|
@@ -77,7 +77,7 @@ class ComponentSummary(InspectBase):
|
|
|
77
77
|
:return: A list of processed components with license data, or `None` if `self.results` is not set.
|
|
78
78
|
"""
|
|
79
79
|
if self.results is None:
|
|
80
|
-
|
|
80
|
+
raise ValueError(f'Error: No results found in ${self.filepath}')
|
|
81
81
|
|
|
82
82
|
components: dict = {}
|
|
83
83
|
# Extract component and license data from file and dependency results. Both helpers mutate `components`
|