CheckmarxPythonSDK 1.9.2__py3-none-any.whl → 1.9.4__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.
Files changed (45) hide show
  1. CheckmarxPythonSDK/CxOne/__init__.py +43 -0
  2. CheckmarxPythonSDK/CxOne/apisecAPI.py +184 -7
  3. CheckmarxPythonSDK/CxOne/dto/BreakBuildExemptStateDto.py +28 -0
  4. CheckmarxPythonSDK/CxOne/dto/EnhancedIncidentsPaginationDTO.py +27 -0
  5. CheckmarxPythonSDK/CxOne/dto/EnhancedIncidentsWebDTO.py +52 -0
  6. CheckmarxPythonSDK/CxOne/dto/EvaluatedPolicyWebDto.py +34 -0
  7. CheckmarxPythonSDK/CxOne/dto/ExportParametersSbom.py +10 -0
  8. CheckmarxPythonSDK/CxOne/dto/ExportParametersScanReport.py +15 -0
  9. CheckmarxPythonSDK/CxOne/dto/FindingsWebDto.py +46 -0
  10. CheckmarxPythonSDK/CxOne/dto/IncidentResultWebDTO.py +64 -0
  11. CheckmarxPythonSDK/CxOne/dto/IncidentResultsDTO.py +36 -0
  12. CheckmarxPythonSDK/CxOne/dto/IncidentWebDto.py +47 -0
  13. CheckmarxPythonSDK/CxOne/dto/IncidentsPaginationDto.py +26 -0
  14. CheckmarxPythonSDK/CxOne/dto/PackageWebDto.py +45 -0
  15. CheckmarxPythonSDK/CxOne/dto/PoliciesPaginationDto.py +26 -0
  16. CheckmarxPythonSDK/CxOne/dto/PoliciesResultWebDto.py +31 -0
  17. CheckmarxPythonSDK/CxOne/dto/PolicyShortWebDto.py +21 -0
  18. CheckmarxPythonSDK/CxOne/dto/PolicyViolationWebDto.py +36 -0
  19. CheckmarxPythonSDK/CxOne/dto/PolicyWebDto.py +104 -0
  20. CheckmarxPythonSDK/CxOne/dto/ProjectWebDto.py +25 -0
  21. CheckmarxPythonSDK/CxOne/dto/ProjectsInPolicyDto.py +38 -0
  22. CheckmarxPythonSDK/CxOne/dto/RuleViolatedWebDto.py +35 -0
  23. CheckmarxPythonSDK/CxOne/dto/ScaExportFileFormats.py +18 -0
  24. CheckmarxPythonSDK/CxOne/dto/ScaExportStatus.py +23 -0
  25. CheckmarxPythonSDK/CxOne/dto/ViolatedPolicyWebDto.py +36 -0
  26. CheckmarxPythonSDK/CxOne/dto/ViolatingAssocProjectsWebDto.py +22 -0
  27. CheckmarxPythonSDK/CxOne/dto/ViolationDetailsDTO.py +31 -0
  28. CheckmarxPythonSDK/CxOne/dto/VulnerabilityWebDto.py +31 -0
  29. CheckmarxPythonSDK/CxOne/dto/__init__.py +26 -0
  30. CheckmarxPythonSDK/CxOne/policyManagerAPI.py +765 -0
  31. CheckmarxPythonSDK/CxOne/projectsAPI.py +14 -15
  32. CheckmarxPythonSDK/CxOne/repoManagerAPI.py +12 -2
  33. CheckmarxPythonSDK/CxOne/reportAPI.py +362 -58
  34. CheckmarxPythonSDK/CxOne/scansAPI.py +33 -11
  35. CheckmarxPythonSDK/CxReporting/api.py +82 -10
  36. CheckmarxPythonSDK/CxRestAPISDK/ScansAPI.py +40 -2
  37. CheckmarxPythonSDK/CxScaApiSDK/__init__.py +1 -0
  38. CheckmarxPythonSDK/CxScaApiSDK/api.py +148 -30
  39. CheckmarxPythonSDK/__version__.py +1 -1
  40. CheckmarxPythonSDK/api_client.py +140 -5
  41. {checkmarxpythonsdk-1.9.2.dist-info → checkmarxpythonsdk-1.9.4.dist-info}/METADATA +1 -1
  42. {checkmarxpythonsdk-1.9.2.dist-info → checkmarxpythonsdk-1.9.4.dist-info}/RECORD +45 -18
  43. {checkmarxpythonsdk-1.9.2.dist-info → checkmarxpythonsdk-1.9.4.dist-info}/WHEEL +0 -0
  44. {checkmarxpythonsdk-1.9.2.dist-info → checkmarxpythonsdk-1.9.4.dist-info}/licenses/LICENSE +0 -0
  45. {checkmarxpythonsdk-1.9.2.dist-info → checkmarxpythonsdk-1.9.4.dist-info}/top_level.txt +0 -0
@@ -37,21 +37,20 @@ class ProjectsAPI(object):
37
37
  projects = []
38
38
  offset = 0
39
39
  limit = 500
40
- try:
41
- while True:
42
- project_collection = self.get_a_list_of_projects(
43
- offset=offset,
44
- limit=limit,
45
- )
46
- total_count = int(project_collection.total_count)
47
- projects.extend(project_collection.projects)
48
- if len(projects) >= total_count:
49
- break
50
- offset += limit
51
- if offset > total_count:
52
- break
53
- except Exception as e:
54
- logger.error(f"Error in get_all_projects: {str(e)}")
40
+ # Errors propagate: returning a partial list would silently hide that
41
+ # some projects were never fetched.
42
+ while True:
43
+ project_collection = self.get_a_list_of_projects(
44
+ offset=offset,
45
+ limit=limit,
46
+ )
47
+ total_count = int(project_collection.total_count)
48
+ projects.extend(project_collection.projects)
49
+ if len(projects) >= total_count:
50
+ break
51
+ offset += limit
52
+ if offset > total_count:
53
+ break
55
54
  return projects
56
55
 
57
56
  def create_a_project(self, project_input: ProjectInput) -> Project:
@@ -660,6 +660,7 @@ class RepoManagerAPI(object):
660
660
  tags: dict = None,
661
661
  is_repo_admin: bool = False,
662
662
  delay_request_timeout: int = 30,
663
+ max_wait_per_round: int = 7200,
663
664
  ) -> None:
664
665
  """
665
666
 
@@ -688,6 +689,8 @@ class RepoManagerAPI(object):
688
689
  private_repository_scan (bool):
689
690
  tags (dict):
690
691
  is_repo_admin (bool):
692
+ max_wait_per_round (int): maximum seconds to wait for each import
693
+ round to reach 100% before raising TimeoutError.
691
694
  delay_request_timeout (int):
692
695
 
693
696
  Returns:
@@ -767,14 +770,19 @@ class RepoManagerAPI(object):
767
770
  scan_ast_project=scan_ast_project,
768
771
  )
769
772
  percentage = 0
773
+ deadline = time.monotonic() + max_wait_per_round
770
774
  while percentage < 100:
775
+ if time.monotonic() >= deadline:
776
+ raise TimeoutError(
777
+ f"repo import round {round_i} did not finish within "
778
+ f"{max_wait_per_round}s, last percent: {percentage}"
779
+ )
771
780
  try:
772
781
  percentage = self.get_job_status()
773
782
  logger.info(f"import percent: {percentage}")
774
- time.sleep(delay_request_timeout)
775
783
  except httpx.RemoteProtocolError as e:
776
784
  logger.info(f"ChunkedEncodingError: {e}")
777
- continue
785
+ time.sleep(delay_request_timeout)
778
786
  time.sleep(delay_request_timeout)
779
787
 
780
788
  def get_repo_by_id(self, repo_id: int) -> dict:
@@ -1145,6 +1153,7 @@ def batch_import_repo(
1145
1153
  tags: dict = None,
1146
1154
  is_repo_admin: bool = False,
1147
1155
  delay_request_timeout: int = 30,
1156
+ max_wait_per_round: int = 7200,
1148
1157
  ) -> None:
1149
1158
  return RepoManagerAPI().batch_import_repo(
1150
1159
  repos=repos,
@@ -1172,6 +1181,7 @@ def batch_import_repo(
1172
1181
  tags=tags,
1173
1182
  is_repo_admin=is_repo_admin,
1174
1183
  delay_request_timeout=delay_request_timeout,
1184
+ max_wait_per_round=max_wait_per_round,
1175
1185
  )
1176
1186
 
1177
1187
 
@@ -1,10 +1,34 @@
1
1
  import time
2
+ from dataclasses import asdict, is_dataclass
2
3
  from CheckmarxPythonSDK.api_client import ApiClient
3
4
  from CheckmarxPythonSDK.CxOne.config import construct_configuration
4
- from typing import List
5
+ from typing import List, Union
6
+ from .dto import (
7
+ ExportParametersSbom,
8
+ ExportParametersScanReport,
9
+ ScaExportFileFormats,
10
+ ScaExportStatus,
11
+ )
5
12
  import logging
6
13
  logger = logging.getLogger(__name__)
7
14
 
15
+ # POST /api/sca/export/requests fileFormat values, grouped by which
16
+ # exportParameters shape they expect. RemediatedPackagesJson/
17
+ # RemediatedPackages's shape isn't documented by Checkmarx -- callers
18
+ # needing specific flags there should pass a plain dict. The full set
19
+ # (including RemediatedPackages, undocumented but live-confirmed via
20
+ # GET /api/sca/export/file-formats) is cross-checked against that
21
+ # endpoint's actual output in get_sca_export_file_formats's test.
22
+ SCA_EXPORT_SBOM_FILE_FORMATS = {"CycloneDxJson", "CycloneDxXml", "SpdxJson"}
23
+ SCA_EXPORT_SCAN_REPORT_FILE_FORMATS = {
24
+ "ScanReportJson", "ScanReportXml", "ScanReportCsv", "ScanReportPdf",
25
+ }
26
+ SCA_EXPORT_FILE_FORMATS = (
27
+ SCA_EXPORT_SBOM_FILE_FORMATS
28
+ | SCA_EXPORT_SCAN_REPORT_FILE_FORMATS
29
+ | {"RemediatedPackagesJson", "RemediatedPackages"}
30
+ )
31
+
8
32
 
9
33
  class ReportAPI(object):
10
34
 
@@ -22,22 +46,62 @@ class ReportAPI(object):
22
46
  file_format: str,
23
47
  scan_engines: List[str],
24
48
  scan_id: str,
49
+ severities: List[str] = None,
50
+ states: List[str] = None,
51
+ status: List[str] = None,
52
+ sections: List[str] = None,
53
+ report_type: str = "ui",
54
+ emails: List[str] = None,
55
+ report_filename: str = None,
56
+ timezone: str = None,
57
+ max_wait: int = 3600,
25
58
  ) -> str:
26
- """
59
+ """POST /reports/v2 (reportName=improved-scan-report) — generate
60
+ an Improved Scan Report and poll until it's ready.
61
+
62
+ Confirmed live: the hardcoded severities filter previously sent
63
+ here -- ["high", "medium", "low", "information"] -- silently
64
+ excludes Critical, the single most severe category. The
65
+ generated report's own reportFilters section confirmed this
66
+ ("excluded": ["Critical"]) against a real scan with Critical
67
+ findings. Fixed by including "critical" in the default.
68
+
27
69
  Args:
28
- file_format (str):
29
- scan_engines (List[str]):
30
- scan_id (str):
70
+ file_format (str): pdf, json, or csv. Required.
71
+ scan_engines (List[str]): Scanners to include: sast, sca,
72
+ iac, containers, microengines, apisec, byor. Required.
73
+ scan_id (str): The scan to report on. Required.
74
+ severities (List[str], optional): critical, high, medium,
75
+ low, information. Defaults to all five.
76
+ states (List[str], optional): to-verify, not-exploitable,
77
+ proposed-not-exploitable, urgent, confirmed. Defaults
78
+ to all five.
79
+ status (List[str], optional): new, recurrent. Defaults to
80
+ both.
81
+ sections (List[str], optional): scan-information,
82
+ results-overview, scan-results, resolved-results,
83
+ categories, vulnerability-details, scs-vulnerabilities.
84
+ Defaults to every section except scs-vulnerabilities
85
+ (SCS isn't one of this method's scan_engines options).
86
+ report_type (str, optional): cli, ui, or email. Defaults
87
+ to "ui".
88
+ emails (List[str], optional): Recipients; required by the
89
+ API when report_type is "email".
90
+ report_filename (str, optional): Defaults to the server's
91
+ own "Cx_ScanReport_{Scan_Date}" naming when omitted
92
+ (previously this sent an explicit empty string instead
93
+ of omitting the field).
94
+ timezone (str, optional): Applied to "overtime" KPIs.
95
+ Defaults to UTC.
31
96
 
32
97
  Returns:
33
- str
98
+ str: the generated report's id.
34
99
  """
35
100
  url = f"{self.base_url}/v2"
36
101
  payload = {
37
102
  "fileFormat": file_format,
38
103
  "reportName": "improved-scan-report",
39
- "reportFilename": "",
40
- "sections": [
104
+ "sections": sections or [
41
105
  "scan-information",
42
106
  "results-overview",
43
107
  "scan-results",
@@ -50,24 +114,31 @@ class ReportAPI(object):
50
114
  ],
51
115
  "filters": {
52
116
  "scanners": scan_engines,
53
- "severities": ["high", "medium", "low", "information"],
54
- "states": [
117
+ "severities": severities or [
118
+ "critical", "high", "medium", "low", "information",
119
+ ],
120
+ "states": states or [
55
121
  "to-verify",
56
122
  "confirmed",
57
123
  "urgent",
58
124
  "not-exploitable",
59
125
  "proposed-not-exploitable",
60
126
  ],
61
- "status": ["new", "recurrent"],
127
+ "status": status or ["new", "recurrent"],
62
128
  },
63
- "reportType": "ui",
64
- "emails": [],
129
+ "reportType": report_type,
130
+ "emails": emails or [],
65
131
  }
132
+ if report_filename is not None:
133
+ payload["reportFilename"] = report_filename
134
+ if timezone is not None:
135
+ payload["timezone"] = timezone
66
136
  response = self.api_client.call_api(
67
137
  method="POST", url=url, json=payload
68
138
  )
69
139
  report_id = response.json().get("reportId")
70
140
  status_url = f"{self.base_url}/{report_id}"
141
+ deadline = time.monotonic() + max_wait
71
142
  while True:
72
143
  response = self.api_client.call_api(
73
144
  method="GET",
@@ -78,13 +149,25 @@ class ReportAPI(object):
78
149
  if status == "completed":
79
150
  logger.info("Report has been generated successfully!")
80
151
  break
81
- else:
82
- logger.info("Generating report, please wait...")
83
- time.sleep(2)
152
+ if status in ("failed", "error"):
153
+ raise RuntimeError(
154
+ f"Report {report_id} generation failed, status: {status}"
155
+ )
156
+ if time.monotonic() >= deadline:
157
+ raise TimeoutError(
158
+ f"Report {report_id} not completed within {max_wait}s, "
159
+ f"last status: {status}"
160
+ )
161
+ logger.info("Generating report, please wait...")
162
+ time.sleep(2)
84
163
  return report_id
85
164
 
86
165
  def create_scan_report(
87
- self, file_format: str, scan_id: str, project_id: str
166
+ self,
167
+ file_format: str,
168
+ scan_id: str,
169
+ project_id: str,
170
+ max_wait: int = 3600,
88
171
  ) -> str:
89
172
  """
90
173
  Args:
@@ -117,6 +200,7 @@ class ReportAPI(object):
117
200
  )
118
201
  report_id = response.json().get("reportId")
119
202
  status_url = f"{self.base_url}/{report_id}"
203
+ deadline = time.monotonic() + max_wait
120
204
  while True:
121
205
  response = self.api_client.call_api(
122
206
  method="GET",
@@ -127,9 +211,17 @@ class ReportAPI(object):
127
211
  if status == "completed":
128
212
  logger.info("Report has been generated successfully!")
129
213
  break
130
- else:
131
- logger.info("Generating report, please wait...")
132
- time.sleep(2)
214
+ if status in ("failed", "error"):
215
+ raise RuntimeError(
216
+ f"Report {report_id} generation failed, status: {status}"
217
+ )
218
+ if time.monotonic() >= deadline:
219
+ raise TimeoutError(
220
+ f"Report {report_id} not completed within {max_wait}s, "
221
+ f"last status: {status}"
222
+ )
223
+ logger.info("Generating report, please wait...")
224
+ time.sleep(2)
133
225
  return report_id
134
226
 
135
227
  def get_report_status(self, report_id: str, return_url: bool = True) -> dict:
@@ -151,18 +243,42 @@ class ReportAPI(object):
151
243
  )
152
244
  return response.json()
153
245
 
154
- def get_scan_report(self, report_id: str) -> dict:
246
+ def get_scan_report(
247
+ self, report_id: str, timeout: float = None
248
+ ) -> dict:
155
249
  """
156
250
  Args:
157
251
  report_id (str):
252
+ timeout (float): per-call timeout in seconds for the download;
253
+ defaults to the configured timeout.
158
254
 
159
255
  Returns:
160
256
  dict
161
257
  """
162
258
  url = f"{self.base_url}/{report_id}/download"
163
- response = self.api_client.call_api(method="GET", url=url)
259
+ response = self.api_client.call_api(
260
+ method="GET", url=url, timeout=timeout
261
+ )
164
262
  return response.json()
165
263
 
264
+ def download_scan_report(
265
+ self, report_id: str, path: str, timeout: float = None
266
+ ) -> str:
267
+ """Stream a generated report to ``path`` instead of loading it in memory.
268
+
269
+ Use for large reports or non-JSON formats (pdf, csv, ...).
270
+
271
+ Args:
272
+ report_id (str):
273
+ path (str): destination file path.
274
+ timeout (float): per-call timeout in seconds.
275
+
276
+ Returns:
277
+ str: ``path``
278
+ """
279
+ url = f"{self.base_url}/{report_id}/download"
280
+ return self.api_client.download_to("GET", url, path, timeout=timeout)
281
+
166
282
  def get_risk_scan_report(
167
283
  self, scan_id: str, report_type: str
168
284
  ) -> dict:
@@ -184,83 +300,249 @@ class ReportAPI(object):
184
300
  )
185
301
  return response.json()
186
302
 
187
- def create_sca_scan_report(self, scan_id: str) -> str:
303
+ def get_sca_export_file_formats(self) -> List[ScaExportFileFormats]:
304
+ """GET /api/sca/export/file-formats -- the fileFormat values
305
+ accepted by each SCA export route (e.g. /requests, the route
306
+ used by create_sca_scan_report).
307
+
308
+ Returns:
309
+ List[ScaExportFileFormats]
188
310
  """
311
+ base = self.api_client.configuration.server_base_url
312
+ url = f"{base}/api/sca/export/file-formats"
313
+ response = self.api_client.call_api(method="GET", url=url)
314
+ return [
315
+ ScaExportFileFormats.from_dict(item) for item in response.json()
316
+ ]
317
+
318
+ def create_sca_scan_report(
319
+ self,
320
+ scan_id: str,
321
+ file_format: str = "ScanReportJson",
322
+ export_parameters: Union[
323
+ ExportParametersSbom, ExportParametersScanReport, dict
324
+ ] = None,
325
+ ) -> str:
326
+ """POST /api/sca/export/requests -- request an SCA export/report
327
+ for a scan. Accepted asynchronously; poll/download the result
328
+ with get_sca_scan_report(export_id).
329
+
189
330
  Args:
190
- scan_id (str):
331
+ scan_id (str): The scan to generate a report for.
332
+ file_format (str): One of CycloneDxJson, CycloneDxXml,
333
+ SpdxJson, RemediatedPackagesJson, ScanReportJson,
334
+ ScanReportXml, ScanReportCsv, ScanReportPdf. Default:
335
+ ScanReportJson (matches this method's previous,
336
+ non-parameterized behavior).
337
+ export_parameters: Shape depends on `file_format` --
338
+ ExportParametersSbom for the CycloneDx*/SpdxJson
339
+ formats, ExportParametersScanReport for the
340
+ ScanReport* formats, or a plain dict (e.g. for
341
+ RemediatedPackagesJson, whose exportParameters shape
342
+ Checkmarx does not document). Defaults to the right
343
+ type's defaults for `file_format` if omitted
344
+ (ExportParametersScanReport() when `file_format` is
345
+ any ScanReport* value, matching this method's previous
346
+ hardcoded defaults exactly; ExportParametersSbom()
347
+ for SBOM formats; {} otherwise).
191
348
 
192
349
  Returns:
193
- str
350
+ str: exportId, used to poll/download via
351
+ get_sca_scan_report.
194
352
  """
353
+ if file_format not in SCA_EXPORT_FILE_FORMATS:
354
+ raise ValueError(
355
+ f"file_format must be one of {sorted(SCA_EXPORT_FILE_FORMATS)}, "
356
+ f"got {file_format!r}"
357
+ )
358
+ if export_parameters is None:
359
+ if file_format in SCA_EXPORT_SBOM_FILE_FORMATS:
360
+ export_parameters = ExportParametersSbom()
361
+ elif file_format in SCA_EXPORT_SCAN_REPORT_FILE_FORMATS:
362
+ export_parameters = ExportParametersScanReport()
363
+ else:
364
+ export_parameters = {}
365
+ if is_dataclass(export_parameters):
366
+ export_parameters = asdict(export_parameters)
367
+
195
368
  base = self.api_client.configuration.server_base_url
196
369
  url = f"{base}/api/sca/export/requests"
197
370
  payload = {
198
371
  "ScanId": scan_id,
199
- "FileFormat": "ScanReportJson",
200
- "ExportParameters": {
201
- "hideDevAndTestDependencies": False,
202
- "showOnlyEffectiveLicenses": False,
203
- "excludePackages": False,
204
- "excludeLicenses": True,
205
- "excludeVulnerabilities": False,
206
- "excludePolicies": True,
207
- },
372
+ "FileFormat": file_format,
373
+ "ExportParameters": export_parameters,
208
374
  }
209
375
  response = self.api_client.call_api(
210
376
  method="POST", url=url, json=payload
211
377
  )
212
378
  return response.json()["exportId"]
213
379
 
214
- def get_sca_scan_report(self, export_id: str) -> dict:
380
+ def get_sca_export_status(self, export_id: str) -> ScaExportStatus:
381
+ """GET /api/sca/export/requests?exportId={exportId} -- check
382
+ the status of an SCA export request (and, once Completed, its
383
+ download URL) without blocking/polling. For a one-shot
384
+ poll-until-done-and-download instead, see
385
+ get_sca_scan_report.
386
+
387
+ Args:
388
+ export_id (str):
389
+
390
+ Returns:
391
+ ScaExportStatus
392
+ """
393
+ base = self.api_client.configuration.server_base_url
394
+ url = f"{base}/api/sca/export/requests"
395
+ response = self.api_client.call_api(
396
+ method="GET", url=url, params={"exportId": export_id},
397
+ )
398
+ return ScaExportStatus.from_dict(response.json())
399
+
400
+ def download_sca_export(
401
+ self, export_id: str, timeout: float = None
402
+ ) -> Union[dict, bytes]:
403
+ """GET /api/sca/export/requests/{exportId}/download -- download
404
+ a completed SCA export/report. Does not check status first --
405
+ call get_sca_export_status (or wait for "Completed") before
406
+ calling this; downloading one that isn't ready yet may 404.
407
+
408
+ Returns dict for JSON export formats (set via
409
+ create_sca_scan_report's file_format), and raw bytes for the
410
+ others (XML/CSV/PDF) -- decided from the response's actual
411
+ Content-Type, not from a remembered file_format.
412
+
413
+ Args:
414
+ export_id (str):
415
+ timeout (float): per-call timeout in seconds for the
416
+ download; defaults to the configured timeout.
417
+
418
+ Returns:
419
+ dict: for JSON export formats.
420
+ bytes: for XML/CSV/PDF export formats -- caller is
421
+ responsible for writing to disk / decoding as needed.
215
422
  """
423
+ base = self.api_client.configuration.server_base_url
424
+ url = f"{base}/api/sca/export/requests/{export_id}/download"
425
+ response = self.api_client.call_api(
426
+ method="GET", url=url, timeout=timeout
427
+ )
428
+ if "json" in response.headers.get("content-type", "").lower():
429
+ return response.json()
430
+ return response.content
431
+
432
+ def get_sca_scan_report(
433
+ self, export_id: str, max_wait: int = 3600, timeout: float = None
434
+ ) -> Union[dict, bytes]:
435
+ """Poll an SCA export request until it completes, then download
436
+ it via download_sca_export.
437
+
216
438
  Args:
217
439
  export_id (str):
440
+ max_wait (int): maximum seconds to wait for the export;
441
+ raises TimeoutError afterwards, and RuntimeError if the
442
+ export failed.
443
+ timeout (float): per-call timeout in seconds for the
444
+ download.
218
445
 
219
446
  Returns:
220
- dict
447
+ dict: for JSON export formats.
448
+ bytes: for XML/CSV/PDF export formats -- caller is
449
+ responsible for writing to disk / decoding as needed.
450
+ """
451
+ self._wait_for_sca_export(export_id, max_wait)
452
+ return self.download_sca_export(export_id, timeout=timeout)
453
+
454
+ def download_sca_scan_report(
455
+ self,
456
+ export_id: str,
457
+ path: str,
458
+ max_wait: int = 3600,
459
+ timeout: float = None,
460
+ ) -> str:
461
+ """Wait for an SCA export, then stream it to ``path``.
462
+
463
+ Works for every export format and never holds the file in
464
+ memory, so prefer it over get_sca_scan_report for large exports.
465
+
466
+ Args:
467
+ export_id (str):
468
+ path (str): destination file path.
469
+ max_wait (int): maximum seconds to wait for the export; raises
470
+ TimeoutError afterwards, and RuntimeError if the export failed.
471
+ timeout (float): per-call timeout in seconds for the download.
472
+
473
+ Returns:
474
+ str: ``path``
221
475
  """
476
+ download_url = self._wait_for_sca_export(export_id, max_wait)
477
+ return self.api_client.download_to(
478
+ "GET", download_url, path, timeout=timeout
479
+ )
480
+
481
+ def _wait_for_sca_export(self, export_id: str, max_wait: int) -> str:
482
+ """Poll until the export is complete and return its download url."""
222
483
  base = self.api_client.configuration.server_base_url
223
484
  status_url = f"{base}/api/sca/export/requests"
224
- download_url = (
225
- f"{base}/api/sca/export/requests/{export_id}/download"
226
- )
485
+ download_url = f"{base}/api/sca/export/requests/{export_id}/download"
486
+ deadline = time.monotonic() + max_wait
227
487
  while True:
228
488
  response = self.api_client.call_api(
229
- method="GET",
230
- url=status_url,
231
- params={"exportId": export_id},
489
+ method="GET", url=status_url, params={"exportId": export_id}
232
490
  )
233
491
  status = response.json().get("exportStatus")
234
492
  if status == "Completed":
235
- response = self.api_client.call_api(
236
- method="GET", url=download_url
237
- )
238
493
  logger.info("Report has been generated successfully!")
239
- break
494
+ return download_url
240
495
  if status == "Failed":
241
- logger.error(f"Error: {response.content}")
242
- break
243
- else:
244
- logger.info("Generating report, please wait...")
245
- time.sleep(2)
246
- return response.json()
496
+ raise RuntimeError(
497
+ f"SCA export {export_id} failed: {response.text}"
498
+ )
499
+ if time.monotonic() >= deadline:
500
+ raise TimeoutError(
501
+ f"SCA export {export_id} not completed within "
502
+ f"{max_wait}s, last status: {status}"
503
+ )
504
+ logger.info("Generating report, please wait...")
505
+ time.sleep(2)
247
506
 
248
507
 
249
508
  def create_scan_report_v2(
250
- file_format: str, scan_engines: List[str], scan_id: str
509
+ file_format: str,
510
+ scan_engines: List[str],
511
+ scan_id: str,
512
+ severities: List[str] = None,
513
+ states: List[str] = None,
514
+ status: List[str] = None,
515
+ sections: List[str] = None,
516
+ report_type: str = "ui",
517
+ emails: List[str] = None,
518
+ report_filename: str = None,
519
+ timezone: str = None,
520
+ max_wait: int = 3600,
251
521
  ) -> str:
252
522
  return ReportAPI().create_scan_report_v2(
253
523
  file_format=file_format,
254
524
  scan_engines=scan_engines,
255
525
  scan_id=scan_id,
526
+ severities=severities,
527
+ states=states,
528
+ status=status,
529
+ sections=sections,
530
+ report_type=report_type,
531
+ emails=emails,
532
+ report_filename=report_filename,
533
+ timezone=timezone,
534
+ max_wait=max_wait,
256
535
  )
257
536
 
258
537
 
259
538
  def create_scan_report(
260
- file_format: str, scan_id: str, project_id: str
539
+ file_format: str, scan_id: str, project_id: str, max_wait: int = 3600
261
540
  ) -> str:
262
541
  return ReportAPI().create_scan_report(
263
- file_format=file_format, scan_id=scan_id, project_id=project_id
542
+ file_format=file_format,
543
+ scan_id=scan_id,
544
+ project_id=project_id,
545
+ max_wait=max_wait,
264
546
  )
265
547
 
266
548
 
@@ -280,9 +562,31 @@ def get_risk_scan_report(scan_id: str, report_type: str) -> dict:
280
562
  )
281
563
 
282
564
 
283
- def create_sca_scan_report(scan_id: str) -> str:
284
- return ReportAPI().create_sca_scan_report(scan_id=scan_id)
565
+ def get_sca_export_file_formats() -> List[ScaExportFileFormats]:
566
+ return ReportAPI().get_sca_export_file_formats()
567
+
568
+
569
+ def create_sca_scan_report(
570
+ scan_id: str,
571
+ file_format: str = "ScanReportJson",
572
+ export_parameters: Union[
573
+ ExportParametersSbom, ExportParametersScanReport, dict
574
+ ] = None,
575
+ ) -> str:
576
+ return ReportAPI().create_sca_scan_report(
577
+ scan_id=scan_id,
578
+ file_format=file_format,
579
+ export_parameters=export_parameters,
580
+ )
581
+
582
+
583
+ def get_sca_export_status(export_id: str) -> ScaExportStatus:
584
+ return ReportAPI().get_sca_export_status(export_id=export_id)
585
+
586
+
587
+ def download_sca_export(export_id: str) -> Union[dict, bytes]:
588
+ return ReportAPI().download_sca_export(export_id=export_id)
285
589
 
286
590
 
287
- def get_sca_scan_report(export_id: str) -> dict:
591
+ def get_sca_scan_report(export_id: str) -> Union[dict, bytes]:
288
592
  return ReportAPI().get_sca_scan_report(export_id=export_id)