diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c40b0db..9d32eed5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,9 @@ # Changelog All notable changes to this project will be documented in this file. +Unreleased +* [Add] PolicyManagerAPI for the Cx Policy Manager REST API (/api/policy_management_service_uri) — tenant policies (create/get/update/delete, V2/V3 pagination, pin, project assignment), policy violations, per-scan policy evaluation, incidents (including the enhanced V2 view), incident results, and internal data-retention cleanup. 27 endpoints, 22 new DTOs. + 1.9.3 - 2026-11-12 * [Fix] ReportAPI.create_scan_report_v2 (POST /reports/v2, Improved Scan Report) — the hardcoded severities filter silently excluded Critical, the single most severe category. Confirmed live against a real scan: the generated report's own reportFilters.filters showed "excluded": ["Critical"], and totalResults jumped from 117 to 139 (exactly the 22 Critical findings that were missing) once fixed. Every report generated by this method before this fix was silently missing all Critical-severity results. * [Add] ReportAPI.create_scan_report_v2 optional severities/states/status/sections/report_type/emails/report_filename/timezone params, matching the documented request body — previously these were all hardcoded with no way for callers to override them. report_filename, when omitted, now lets the server apply its own "Cx_ScanReport_{Scan_Date}" default instead of forcing an empty string. diff --git a/CheckmarxPythonSDK/CxOne/__init__.py b/CheckmarxPythonSDK/CxOne/__init__.py index f05992cd..80bb0687 100644 --- a/CheckmarxPythonSDK/CxOne/__init__.py +++ b/CheckmarxPythonSDK/CxOne/__init__.py @@ -63,6 +63,36 @@ get_risks_aggregate, get_risks_ai_insights, ) +from .policyManagerAPI import ( + PolicyManagerAPI, + get_tenant_policies, + create_policy, + delete_policies, + get_policy, + update_policy, + delete_policy, + get_policy_v2, + update_policy_v2, + get_tenant_policies_with_pagination, + create_policy_v2, + get_tenant_policies_with_pagination_v3, + get_default_policy, + assign_projects_to_policy, + delete_projects_from_policy, + pin_policy, + get_tenant_projects, + get_projects_tags, + get_policy_violations, + get_evaluated_policies_by_scan_id_and_project_id, + get_tenant_incidents, + get_tenant_incidents_total_count, + get_tenant_incidents_with_pagination, + get_tenant_incidents_with_pagination_and_filters, + get_enhanced_incidents_with_pagination_and_filters, + get_incident_results, + delete_data, + delete_data_for_service, +) from .accessManagementAPI import ( AccessManagementAPI, diff --git a/CheckmarxPythonSDK/CxOne/dto/BreakBuildExemptStateDto.py b/CheckmarxPythonSDK/CxOne/dto/BreakBuildExemptStateDto.py new file mode 100644 index 00000000..d1ebb2eb --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/BreakBuildExemptStateDto.py @@ -0,0 +1,28 @@ +from dataclasses import dataclass, field, asdict +from typing import List, Optional + + +@dataclass +class BreakBuildExemptStateDto: + """A result state that is exempt from breaking the build for a rule. + + Attributes: + scanner (Optional[str]): The scanner the exemption applies to. + ruleName (Optional[str]): The policy rule the exemption applies to. + stateName (List[str]): Result states exempt from breaking the build. + """ + + scanner: Optional[str] = None + ruleName: Optional[str] = None + stateName: List[str] = field(default_factory=list) + + @classmethod + def from_dict(cls, item: dict) -> "BreakBuildExemptStateDto": + return cls( + scanner=item.get("scanner"), + ruleName=item.get("ruleName"), + stateName=list(item.get("stateName") or []), + ) + + def to_dict(self) -> dict: + return {k: v for k, v in asdict(self).items() if v is not None} diff --git a/CheckmarxPythonSDK/CxOne/dto/EnhancedIncidentsPaginationDTO.py b/CheckmarxPythonSDK/CxOne/dto/EnhancedIncidentsPaginationDTO.py new file mode 100644 index 00000000..0d90171a --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/EnhancedIncidentsPaginationDTO.py @@ -0,0 +1,27 @@ +from dataclasses import dataclass, field +from typing import List, Optional + +from .EnhancedIncidentsWebDTO import EnhancedIncidentsWebDTO + + +@dataclass +class EnhancedIncidentsPaginationDTO: + """Paginated response from GET /incidents/filters/v2. + + Attributes: + incidents (List[EnhancedIncidentsWebDTO]): Incidents on the current page. + filteredIncidentsCount (Optional[int]): Total count after filtering. + """ + + incidents: List[EnhancedIncidentsWebDTO] = field(default_factory=list) + filteredIncidentsCount: Optional[int] = None + + @classmethod + def from_dict(cls, item: dict) -> "EnhancedIncidentsPaginationDTO": + return cls( + incidents=[ + EnhancedIncidentsWebDTO.from_dict(i) + for i in (item.get("incidents") or []) + ], + filteredIncidentsCount=item.get("filteredIncidentsCount"), + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/EnhancedIncidentsWebDTO.py b/CheckmarxPythonSDK/CxOne/dto/EnhancedIncidentsWebDTO.py new file mode 100644 index 00000000..48a11df7 --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/EnhancedIncidentsWebDTO.py @@ -0,0 +1,52 @@ +from dataclasses import dataclass, field +from typing import List, Optional + + +@dataclass +class EnhancedIncidentsWebDTO: + """A policy incident, as returned by the enhanced (v2) incidents endpoint. + + Same shape as IncidentWebDto plus the originating scanner engine. + + Attributes: + id (Optional[int]): Incident ID. + policyName (Optional[str]): Name of the violated policy. + projectName (Optional[str]): Name of the project scanned. + branch (Optional[str]): Branch scanned. + ruleName (Optional[str]): Name of the violated rule. + scanId (Optional[str]): The scan's UUID. + scanDate (Optional[str]): When the scan ran (date-time). + policyTags (List[str]): Tags on the violated policy. + defaultPolicy (Optional[bool]): Whether the policy is the tenant default. + defaultPolicyEvaluation (Optional[bool]): Whether the default policy + was the one evaluated. + engine (Optional[str]): The scanner engine that produced the incident. + """ + + id: Optional[int] = None + policyName: Optional[str] = None + projectName: Optional[str] = None + branch: Optional[str] = None + ruleName: Optional[str] = None + scanId: Optional[str] = None + scanDate: Optional[str] = None + policyTags: List[str] = field(default_factory=list) + defaultPolicy: Optional[bool] = None + defaultPolicyEvaluation: Optional[bool] = None + engine: Optional[str] = None + + @classmethod + def from_dict(cls, item: dict) -> "EnhancedIncidentsWebDTO": + return cls( + id=item.get("id"), + policyName=item.get("policyName"), + projectName=item.get("projectName"), + branch=item.get("branch"), + ruleName=item.get("ruleName"), + scanId=item.get("scanId"), + scanDate=item.get("scanDate"), + policyTags=list(item.get("policyTags") or []), + defaultPolicy=item.get("defaultPolicy"), + defaultPolicyEvaluation=item.get("defaultPolicyEvaluation"), + engine=item.get("engine"), + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/EvaluatedPolicyWebDto.py b/CheckmarxPythonSDK/CxOne/dto/EvaluatedPolicyWebDto.py new file mode 100644 index 00000000..579e6e2a --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/EvaluatedPolicyWebDto.py @@ -0,0 +1,34 @@ +from dataclasses import dataclass, field +from typing import List, Optional + + +@dataclass +class EvaluatedPolicyWebDto: + """A single policy's evaluation result for one scan/project. + + Attributes: + policyName (Optional[str]): The evaluated policy's name. + description (Optional[str]): The policy's description. + rulesViolated (List[str]): Names of rules that were violated. + tags (List[str]): The policy's tags. + breakBuild (Optional[bool]): Whether this policy breaks the build. + status (Optional[str]): Evaluation status. Values: PASSED, FAILED. + """ + + policyName: Optional[str] = None + description: Optional[str] = None + rulesViolated: List[str] = field(default_factory=list) + tags: List[str] = field(default_factory=list) + breakBuild: Optional[bool] = None + status: Optional[str] = None + + @classmethod + def from_dict(cls, item: dict) -> "EvaluatedPolicyWebDto": + return cls( + policyName=item.get("policyName"), + description=item.get("description"), + rulesViolated=list(item.get("rulesViolated") or []), + tags=list(item.get("tags") or []), + breakBuild=item.get("breakBuild"), + status=item.get("status"), + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/FindingsWebDto.py b/CheckmarxPythonSDK/CxOne/dto/FindingsWebDto.py new file mode 100644 index 00000000..b5e7e5ef --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/FindingsWebDto.py @@ -0,0 +1,46 @@ +from dataclasses import dataclass +from typing import Optional + + +@dataclass +class FindingsWebDto: + """A SAST/IaC finding as referenced from a policy violation. + + Attributes: + resultId (Optional[str]): The result ID. + similarityId (Optional[str]): The similarity ID. + queryId (Optional[str]): The query ID that produced the finding. + queryName (Optional[str]): The query name. + severity (Optional[str]): Severity. Values: CRITICAL, HIGH, MEDIUM, LOW, INFO. + cweId (Optional[int]): CWE ID, if applicable. + fileName (Optional[str]): File the finding was detected in. + line (Optional[int]): Line number of the finding. + description (Optional[str]): Finding description. + stateName (Optional[str]): Current result state. + """ + + resultId: Optional[str] = None + similarityId: Optional[str] = None + queryId: Optional[str] = None + queryName: Optional[str] = None + severity: Optional[str] = None + cweId: Optional[int] = None + fileName: Optional[str] = None + line: Optional[int] = None + description: Optional[str] = None + stateName: Optional[str] = None + + @classmethod + def from_dict(cls, item: dict) -> "FindingsWebDto": + return cls( + resultId=item.get("resultId"), + similarityId=item.get("similarityId"), + queryId=item.get("queryId"), + queryName=item.get("queryName"), + severity=item.get("severity"), + cweId=item.get("cweId"), + fileName=item.get("fileName"), + line=item.get("line"), + description=item.get("description"), + stateName=item.get("stateName"), + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/IncidentResultWebDTO.py b/CheckmarxPythonSDK/CxOne/dto/IncidentResultWebDTO.py new file mode 100644 index 00000000..fe715349 --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/IncidentResultWebDTO.py @@ -0,0 +1,64 @@ +from dataclasses import dataclass +from typing import Optional + + +@dataclass +class IncidentResultWebDTO: + """A single result underlying a policy incident. + + Attributes: + id (Optional[int]): Result ID. + severity (Optional[str]): Result severity. + issue (Optional[str]): Issue/query name. + issueLink (Optional[str]): Link to the issue in the CxOne UI. + cweLink (Optional[str]): Link to the CWE reference. + sourceFilePackage (Optional[str]): Source file or package name. + sourceFileLink (Optional[str]): Link to the source file in the CxOne UI. + lineNumber (Optional[int]): Line number of the finding. + insight (Optional[str]): Remediation insight text. + insightLink (Optional[str]): Link to the remediation insight. + resultId (Optional[str]): The underlying result's ID. + recommendedVersion (Optional[str]): Recommended package version (SCA). + attackVector (Optional[str]): Attack vector description. + attackComplexity (Optional[str]): Attack complexity description. + riskOrchestrationLink (Optional[str]): Link to Risk Orchestration. + sastResultsLink (Optional[str]): Link to the SAST result. + """ + + id: Optional[int] = None + severity: Optional[str] = None + issue: Optional[str] = None + issueLink: Optional[str] = None + cweLink: Optional[str] = None + sourceFilePackage: Optional[str] = None + sourceFileLink: Optional[str] = None + lineNumber: Optional[int] = None + insight: Optional[str] = None + insightLink: Optional[str] = None + resultId: Optional[str] = None + recommendedVersion: Optional[str] = None + attackVector: Optional[str] = None + attackComplexity: Optional[str] = None + riskOrchestrationLink: Optional[str] = None + sastResultsLink: Optional[str] = None + + @classmethod + def from_dict(cls, item: dict) -> "IncidentResultWebDTO": + return cls( + id=item.get("id"), + severity=item.get("severity"), + issue=item.get("issue"), + issueLink=item.get("issueLink"), + cweLink=item.get("cweLink"), + sourceFilePackage=item.get("sourceFilePackage"), + sourceFileLink=item.get("sourceFileLink"), + lineNumber=item.get("lineNumber"), + insight=item.get("insight"), + insightLink=item.get("insightLink"), + resultId=item.get("resultId"), + recommendedVersion=item.get("recommendedVersion"), + attackVector=item.get("attackVector"), + attackComplexity=item.get("attackComplexity"), + riskOrchestrationLink=item.get("riskOrchestrationLink"), + sastResultsLink=item.get("sastResultsLink"), + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/IncidentResultsDTO.py b/CheckmarxPythonSDK/CxOne/dto/IncidentResultsDTO.py new file mode 100644 index 00000000..b0968c8e --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/IncidentResultsDTO.py @@ -0,0 +1,36 @@ +from dataclasses import dataclass, field +from typing import List, Optional + +from .IncidentResultWebDTO import IncidentResultWebDTO +from .ViolationDetailsDTO import ViolationDetailsDTO + + +@dataclass +class IncidentResultsDTO: + """Response from GET /incidents/{incidentId}/results. + + Attributes: + violationDetails (Optional[ViolationDetailsDTO]): The violated + policy/rule details common to all results. + results (List[IncidentResultWebDTO]): Results on the current page. + filteredResultsCount (Optional[int]): Total count after filtering. + """ + + violationDetails: Optional[ViolationDetailsDTO] = None + results: List[IncidentResultWebDTO] = field(default_factory=list) + filteredResultsCount: Optional[int] = None + + @classmethod + def from_dict(cls, item: dict) -> "IncidentResultsDTO": + return cls( + violationDetails=( + ViolationDetailsDTO.from_dict(item["violationDetails"]) + if item.get("violationDetails") + else None + ), + results=[ + IncidentResultWebDTO.from_dict(r) + for r in (item.get("results") or []) + ], + filteredResultsCount=item.get("filteredResultsCount"), + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/IncidentWebDto.py b/CheckmarxPythonSDK/CxOne/dto/IncidentWebDto.py new file mode 100644 index 00000000..766b632a --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/IncidentWebDto.py @@ -0,0 +1,47 @@ +from dataclasses import dataclass, field +from typing import List, Optional + + +@dataclass +class IncidentWebDto: + """A policy incident (a policy violation recorded for a scan). + + Attributes: + id (Optional[int]): Incident ID. + policyName (Optional[str]): Name of the violated policy. + projectName (Optional[str]): Name of the project scanned. + branch (Optional[str]): Branch scanned. + ruleName (Optional[str]): Name of the violated rule. + scanId (Optional[str]): The scan's UUID. + scanDate (Optional[str]): When the scan ran (date-time). + policyTags (List[str]): Tags on the violated policy. + defaultPolicy (Optional[bool]): Whether the policy is the tenant default. + defaultPolicyEvaluation (Optional[bool]): Whether the default policy + was the one evaluated. + """ + + id: Optional[int] = None + policyName: Optional[str] = None + projectName: Optional[str] = None + branch: Optional[str] = None + ruleName: Optional[str] = None + scanId: Optional[str] = None + scanDate: Optional[str] = None + policyTags: List[str] = field(default_factory=list) + defaultPolicy: Optional[bool] = None + defaultPolicyEvaluation: Optional[bool] = None + + @classmethod + def from_dict(cls, item: dict) -> "IncidentWebDto": + return cls( + id=item.get("id"), + policyName=item.get("policyName"), + projectName=item.get("projectName"), + branch=item.get("branch"), + ruleName=item.get("ruleName"), + scanId=item.get("scanId"), + scanDate=item.get("scanDate"), + policyTags=list(item.get("policyTags") or []), + defaultPolicy=item.get("defaultPolicy"), + defaultPolicyEvaluation=item.get("defaultPolicyEvaluation"), + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/IncidentsPaginationDto.py b/CheckmarxPythonSDK/CxOne/dto/IncidentsPaginationDto.py new file mode 100644 index 00000000..12a9d9c8 --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/IncidentsPaginationDto.py @@ -0,0 +1,26 @@ +from dataclasses import dataclass, field +from typing import List, Optional + +from .IncidentWebDto import IncidentWebDto + + +@dataclass +class IncidentsPaginationDto: + """Paginated response from the GET /incidents* endpoints (non-enhanced). + + Attributes: + incidents (List[IncidentWebDto]): Incidents on the current page. + filteredIncidentsCount (Optional[int]): Total count after filtering. + """ + + incidents: List[IncidentWebDto] = field(default_factory=list) + filteredIncidentsCount: Optional[int] = None + + @classmethod + def from_dict(cls, item: dict) -> "IncidentsPaginationDto": + return cls( + incidents=[ + IncidentWebDto.from_dict(i) for i in (item.get("incidents") or []) + ], + filteredIncidentsCount=item.get("filteredIncidentsCount"), + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/PackageWebDto.py b/CheckmarxPythonSDK/CxOne/dto/PackageWebDto.py new file mode 100644 index 00000000..ef024992 --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/PackageWebDto.py @@ -0,0 +1,45 @@ +from dataclasses import dataclass, field +from typing import List, Optional + +from .VulnerabilityWebDto import VulnerabilityWebDto + + +@dataclass +class PackageWebDto: + """An SCA package as referenced from a policy violation. + + Attributes: + id (Optional[str]): Package ID. + name (Optional[str]): Package name. + version (Optional[str]): Package version. + outdated (Optional[bool]): Whether a newer version is available. + highVulnerabilityCount (Optional[int]): Count of high-severity vulnerabilities. + mediumVulnerabilityCount (Optional[int]): Count of medium-severity vulnerabilities. + packageState (Optional[str]): Current state of the package. + vulnerabilities (List[VulnerabilityWebDto]): Vulnerabilities found in the package. + """ + + id: Optional[str] = None + name: Optional[str] = None + version: Optional[str] = None + outdated: Optional[bool] = None + highVulnerabilityCount: Optional[int] = None + mediumVulnerabilityCount: Optional[int] = None + packageState: Optional[str] = None + vulnerabilities: List[VulnerabilityWebDto] = field(default_factory=list) + + @classmethod + def from_dict(cls, item: dict) -> "PackageWebDto": + return cls( + id=item.get("id"), + name=item.get("name"), + version=item.get("version"), + outdated=item.get("outdated"), + highVulnerabilityCount=item.get("highVulnerabilityCount"), + mediumVulnerabilityCount=item.get("mediumVulnerabilityCount"), + packageState=item.get("packageState"), + vulnerabilities=[ + VulnerabilityWebDto.from_dict(v) + for v in (item.get("vulnerabilities") or []) + ], + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/PoliciesPaginationDto.py b/CheckmarxPythonSDK/CxOne/dto/PoliciesPaginationDto.py new file mode 100644 index 00000000..f6e8acf8 --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/PoliciesPaginationDto.py @@ -0,0 +1,26 @@ +from dataclasses import dataclass, field +from typing import List, Optional + +from .PolicyWebDto import PolicyWebDto + + +@dataclass +class PoliciesPaginationDto: + """Paginated response from GET /policies/v2 and GET /policies/v3. + + Attributes: + policies (List[PolicyWebDto]): Policies on the current page. + filteredPoliciesCount (Optional[int]): Total count after filtering. + """ + + policies: List[PolicyWebDto] = field(default_factory=list) + filteredPoliciesCount: Optional[int] = None + + @classmethod + def from_dict(cls, item: dict) -> "PoliciesPaginationDto": + return cls( + policies=[ + PolicyWebDto.from_dict(p) for p in (item.get("policies") or []) + ], + filteredPoliciesCount=item.get("filteredPoliciesCount"), + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/PoliciesResultWebDto.py b/CheckmarxPythonSDK/CxOne/dto/PoliciesResultWebDto.py new file mode 100644 index 00000000..025da1fb --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/PoliciesResultWebDto.py @@ -0,0 +1,31 @@ +from dataclasses import dataclass, field +from typing import List, Optional + +from .EvaluatedPolicyWebDto import EvaluatedPolicyWebDto + + +@dataclass +class PoliciesResultWebDto: + """Response from GET /evaluation (policy evaluation for a scan/project). + + Attributes: + status (Optional[str]): Overall evaluation status. Values: + COMPLETED, NONE, EVALUATING. + breakBuild (Optional[bool]): Whether any evaluated policy breaks the build. + policies (List[EvaluatedPolicyWebDto]): Per-policy evaluation results. + """ + + status: Optional[str] = None + breakBuild: Optional[bool] = None + policies: List[EvaluatedPolicyWebDto] = field(default_factory=list) + + @classmethod + def from_dict(cls, item: dict) -> "PoliciesResultWebDto": + return cls( + status=item.get("status"), + breakBuild=item.get("breakBuild"), + policies=[ + EvaluatedPolicyWebDto.from_dict(p) + for p in (item.get("policies") or []) + ], + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/PolicyShortWebDto.py b/CheckmarxPythonSDK/CxOne/dto/PolicyShortWebDto.py new file mode 100644 index 00000000..f3af2edc --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/PolicyShortWebDto.py @@ -0,0 +1,21 @@ +from dataclasses import dataclass +from typing import Optional + + +@dataclass +class PolicyShortWebDto: + """A policy's ID and name only. + + Returned by POST /policies/v2 (create) and GET /policies/default. + + Attributes: + id (Optional[int]): Policy ID. + name (Optional[str]): Policy name. + """ + + id: Optional[int] = None + name: Optional[str] = None + + @classmethod + def from_dict(cls, item: dict) -> "PolicyShortWebDto": + return cls(id=item.get("id"), name=item.get("name")) diff --git a/CheckmarxPythonSDK/CxOne/dto/PolicyViolationWebDto.py b/CheckmarxPythonSDK/CxOne/dto/PolicyViolationWebDto.py new file mode 100644 index 00000000..51e831d1 --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/PolicyViolationWebDto.py @@ -0,0 +1,36 @@ +from dataclasses import dataclass, field +from typing import List, Optional + +from .ViolatedPolicyWebDto import ViolatedPolicyWebDto + + +@dataclass +class PolicyViolationWebDto: + """Response from GET /api/policy_management_service_uri/policy_violations. + + Attributes: + scanId (Optional[str]): The scan's UUID. + projectId (Optional[str]): The project ID. + generatedOn (Optional[str]): When the evaluation was generated (date-time). + policies (List[ViolatedPolicyWebDto]): Policies violated by the scan. + status (Optional[str]): Evaluation status. Values: COMPLETED, EVALUATING, NONE. + """ + + scanId: Optional[str] = None + projectId: Optional[str] = None + generatedOn: Optional[str] = None + policies: List[ViolatedPolicyWebDto] = field(default_factory=list) + status: Optional[str] = None + + @classmethod + def from_dict(cls, item: dict) -> "PolicyViolationWebDto": + return cls( + scanId=item.get("scanId"), + projectId=item.get("projectId"), + generatedOn=item.get("generatedOn"), + policies=[ + ViolatedPolicyWebDto.from_dict(p) + for p in (item.get("policies") or []) + ], + status=item.get("status"), + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/PolicyWebDto.py b/CheckmarxPythonSDK/CxOne/dto/PolicyWebDto.py new file mode 100644 index 00000000..63164645 --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/PolicyWebDto.py @@ -0,0 +1,104 @@ +from dataclasses import dataclass, field, asdict +from typing import Dict, List, Optional + +from .BreakBuildExemptStateDto import BreakBuildExemptStateDto +from .ProjectWebDto import ProjectWebDto +from .ViolatingAssocProjectsWebDto import ViolatingAssocProjectsWebDto + + +@dataclass +class PolicyWebDto: + """A Policy Manager policy. + + Used both as the request body for create/update and as the response + shape for get/list. + + Attributes: + id (Optional[int]): Policy ID. Only set on existing policies. + name (str): Policy name (1-255 chars). Required. + description (Optional[str]): Policy description (0-2500 chars). + isActivated (Optional[bool]): Whether the policy is active. + tags (List[str]): Up to 50 unique tags. + breakBuild (Optional[bool]): Whether a violation breaks the build. + pinPolicy (Optional[bool]): Whether the policy is pinned. + lastViolated (Optional[str]): When the policy was last violated (date-time). + updatedAt (Optional[str]): Last update time (date-time). + projects (List[ProjectWebDto]): Projects the policy is assigned to. + netNewBreakBuild (Optional[bool]): Whether only net-new violations break the build. + type (Optional[str]): Policy type. Values: NET_NEW, ENGINES_RULES. + allScannersSeverities (List[str]): Severities applied across all scanners. + Values: CRITICAL, HIGH, MEDIUM, LOW, INFO. + violatingAssocProjects (Optional[ViolatingAssocProjectsWebDto]): + Count of associated vs. violating projects. + netNewScannerMode (Optional[str]): Net-new scanner mode. Values: + ALL_SCANNERS, BY_SCANNER. + scannerSeverities (Dict[str, List[str]]): Per-scanner severity lists + when netNewScannerMode is BY_SCANNER. + breakBuildExemptStates (List[BreakBuildExemptStateDto]): Result + states exempt from breaking the build, per rule/scanner. + defaultPolicy (Optional[bool]): Whether this is the tenant's default policy. + """ + + name: str + id: Optional[int] = None + description: Optional[str] = None + isActivated: Optional[bool] = None + tags: List[str] = field(default_factory=list) + breakBuild: Optional[bool] = None + pinPolicy: Optional[bool] = None + lastViolated: Optional[str] = None + updatedAt: Optional[str] = None + projects: List[ProjectWebDto] = field(default_factory=list) + netNewBreakBuild: Optional[bool] = None + type: Optional[str] = None + allScannersSeverities: List[str] = field(default_factory=list) + violatingAssocProjects: Optional[ViolatingAssocProjectsWebDto] = None + netNewScannerMode: Optional[str] = None + scannerSeverities: Dict[str, List[str]] = field(default_factory=dict) + breakBuildExemptStates: List[BreakBuildExemptStateDto] = field(default_factory=list) + defaultPolicy: Optional[bool] = None + + @classmethod + def from_dict(cls, item: dict) -> "PolicyWebDto": + return cls( + id=item.get("id"), + name=item.get("name"), + description=item.get("description"), + isActivated=item.get("isActivated"), + tags=list(item.get("tags") or []), + breakBuild=item.get("breakBuild"), + pinPolicy=item.get("pinPolicy"), + lastViolated=item.get("lastViolated"), + updatedAt=item.get("updatedAt"), + projects=[ + ProjectWebDto.from_dict(p) for p in (item.get("projects") or []) + ], + netNewBreakBuild=item.get("netNewBreakBuild"), + type=item.get("type"), + allScannersSeverities=list(item.get("allScannersSeverities") or []), + violatingAssocProjects=( + ViolatingAssocProjectsWebDto.from_dict(item["violatingAssocProjects"]) + if item.get("violatingAssocProjects") + else None + ), + netNewScannerMode=item.get("netNewScannerMode"), + scannerSeverities=dict(item.get("scannerSeverities") or {}), + breakBuildExemptStates=[ + BreakBuildExemptStateDto.from_dict(s) + for s in (item.get("breakBuildExemptStates") or []) + ], + defaultPolicy=item.get("defaultPolicy"), + ) + + def to_dict(self) -> dict: + # asdict() recursively converts nested dataclasses (projects, + # violatingAssocProjects, breakBuildExemptStates) to plain dicts; + # dict_factory drops None values at every nesting level. + return { + k: v + for k, v in asdict( + self, + dict_factory=lambda obj: {k: v for k, v in obj if v is not None}, + ).items() + if v is not None + } diff --git a/CheckmarxPythonSDK/CxOne/dto/ProjectWebDto.py b/CheckmarxPythonSDK/CxOne/dto/ProjectWebDto.py new file mode 100644 index 00000000..b69ec76a --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/ProjectWebDto.py @@ -0,0 +1,25 @@ +from dataclasses import dataclass, asdict +from typing import Optional + + +@dataclass +class ProjectWebDto: + """A project reference as used by the Policy Manager service. + + Attributes: + astProjectId (str): The CxOne project ID. Required. + name (Optional[str]): The project name. + """ + + astProjectId: str + name: Optional[str] = None + + @classmethod + def from_dict(cls, item: dict) -> "ProjectWebDto": + return cls( + astProjectId=item.get("astProjectId"), + name=item.get("name"), + ) + + def to_dict(self) -> dict: + return {k: v for k, v in asdict(self).items() if v is not None} diff --git a/CheckmarxPythonSDK/CxOne/dto/ProjectsInPolicyDto.py b/CheckmarxPythonSDK/CxOne/dto/ProjectsInPolicyDto.py new file mode 100644 index 00000000..5cda3885 --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/ProjectsInPolicyDto.py @@ -0,0 +1,38 @@ +from dataclasses import dataclass, field, asdict +from typing import List, Optional + +from .ProjectWebDto import ProjectWebDto + + +@dataclass +class ProjectsInPolicyDto: + """Request body for assigning/removing projects on a policy. + + Used by PUT/DELETE /policies/projects/{policyId}. + + Attributes: + projects (List[ProjectWebDto]): Projects to assign or remove. + id (Optional[int]): The policy ID (also given in the URL path). + """ + + projects: List[ProjectWebDto] = field(default_factory=list) + id: Optional[int] = None + + @classmethod + def from_dict(cls, item: dict) -> "ProjectsInPolicyDto": + return cls( + projects=[ + ProjectWebDto.from_dict(p) for p in (item.get("projects") or []) + ], + id=item.get("id"), + ) + + def to_dict(self) -> dict: + return { + k: v + for k, v in asdict( + self, + dict_factory=lambda obj: {k: v for k, v in obj if v is not None}, + ).items() + if v is not None + } diff --git a/CheckmarxPythonSDK/CxOne/dto/RuleViolatedWebDto.py b/CheckmarxPythonSDK/CxOne/dto/RuleViolatedWebDto.py new file mode 100644 index 00000000..d63a6b99 --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/RuleViolatedWebDto.py @@ -0,0 +1,35 @@ +from dataclasses import dataclass, field +from typing import List, Optional + +from .FindingsWebDto import FindingsWebDto +from .PackageWebDto import PackageWebDto + + +@dataclass +class RuleViolatedWebDto: + """A single policy rule that was violated. + + Attributes: + ruleName (Optional[str]): The violated rule's name. + scanner (Optional[str]): The scanner that produced the violation. + packages (List[PackageWebDto]): SCA packages involved, if any. + findings (List[FindingsWebDto]): SAST/IaC findings involved, if any. + """ + + ruleName: Optional[str] = None + scanner: Optional[str] = None + packages: List[PackageWebDto] = field(default_factory=list) + findings: List[FindingsWebDto] = field(default_factory=list) + + @classmethod + def from_dict(cls, item: dict) -> "RuleViolatedWebDto": + return cls( + ruleName=item.get("ruleName"), + scanner=item.get("scanner"), + packages=[ + PackageWebDto.from_dict(p) for p in (item.get("packages") or []) + ], + findings=[ + FindingsWebDto.from_dict(f) for f in (item.get("findings") or []) + ], + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/ViolatedPolicyWebDto.py b/CheckmarxPythonSDK/CxOne/dto/ViolatedPolicyWebDto.py new file mode 100644 index 00000000..f8f0a7c6 --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/ViolatedPolicyWebDto.py @@ -0,0 +1,36 @@ +from dataclasses import dataclass, field +from typing import List, Optional + +from .RuleViolatedWebDto import RuleViolatedWebDto + + +@dataclass +class ViolatedPolicyWebDto: + """A policy that was violated by a scan, with the rules that triggered it. + + Attributes: + policyName (Optional[str]): The violated policy's name. + description (Optional[str]): The policy's description. + tags (List[str]): The policy's tags. + breakBuild (Optional[bool]): Whether this policy breaks the build. + rulesViolated (List[RuleViolatedWebDto]): The rules that were violated. + """ + + policyName: Optional[str] = None + description: Optional[str] = None + tags: List[str] = field(default_factory=list) + breakBuild: Optional[bool] = None + rulesViolated: List[RuleViolatedWebDto] = field(default_factory=list) + + @classmethod + def from_dict(cls, item: dict) -> "ViolatedPolicyWebDto": + return cls( + policyName=item.get("policyName"), + description=item.get("description"), + tags=list(item.get("tags") or []), + breakBuild=item.get("breakBuild"), + rulesViolated=[ + RuleViolatedWebDto.from_dict(r) + for r in (item.get("rulesViolated") or []) + ], + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/ViolatingAssocProjectsWebDto.py b/CheckmarxPythonSDK/CxOne/dto/ViolatingAssocProjectsWebDto.py new file mode 100644 index 00000000..abe0dd61 --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/ViolatingAssocProjectsWebDto.py @@ -0,0 +1,22 @@ +from dataclasses import dataclass +from typing import Optional + + +@dataclass +class ViolatingAssocProjectsWebDto: + """Count of a policy's associated projects vs. those violating it. + + Attributes: + assocProjects (Optional[int]): Number of projects the policy applies to. + violating (Optional[int]): Number of those projects currently violating it. + """ + + assocProjects: Optional[int] = None + violating: Optional[int] = None + + @classmethod + def from_dict(cls, item: dict) -> "ViolatingAssocProjectsWebDto": + return cls( + assocProjects=item.get("assocProjects"), + violating=item.get("violating"), + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/ViolationDetailsDTO.py b/CheckmarxPythonSDK/CxOne/dto/ViolationDetailsDTO.py new file mode 100644 index 00000000..c21a9a2b --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/ViolationDetailsDTO.py @@ -0,0 +1,31 @@ +from dataclasses import dataclass, field +from typing import List, Optional + + +@dataclass +class ViolationDetailsDTO: + """Describes the policy rule an incident's results violated. + + Attributes: + policyName (Optional[str]): Name of the violated policy. + ruleName (Optional[str]): Name of the violated rule. + engine (Optional[str]): The scanner engine that produced the violation. + conditions (List[str]): The rule's conditions. + breakBuild (Optional[bool]): Whether this violation breaks the build. + """ + + policyName: Optional[str] = None + ruleName: Optional[str] = None + engine: Optional[str] = None + conditions: List[str] = field(default_factory=list) + breakBuild: Optional[bool] = None + + @classmethod + def from_dict(cls, item: dict) -> "ViolationDetailsDTO": + return cls( + policyName=item.get("policyName"), + ruleName=item.get("ruleName"), + engine=item.get("engine"), + conditions=list(item.get("conditions") or []), + breakBuild=item.get("breakBuild"), + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/VulnerabilityWebDto.py b/CheckmarxPythonSDK/CxOne/dto/VulnerabilityWebDto.py new file mode 100644 index 00000000..2dab7c05 --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/dto/VulnerabilityWebDto.py @@ -0,0 +1,31 @@ +from dataclasses import dataclass +from typing import Optional + + +@dataclass +class VulnerabilityWebDto: + """An SCA vulnerability as referenced from a policy violation. + + Attributes: + id (Optional[str]): Vulnerability ID. + cveName (Optional[str]): CVE identifier. + severity (Optional[str]): Severity. Values: CRITICAL, HIGH, MEDIUM, LOW, INFO. + description (Optional[str]): Vulnerability description. + packageId (Optional[str]): ID of the package the vulnerability belongs to. + """ + + id: Optional[str] = None + cveName: Optional[str] = None + severity: Optional[str] = None + description: Optional[str] = None + packageId: Optional[str] = None + + @classmethod + def from_dict(cls, item: dict) -> "VulnerabilityWebDto": + return cls( + id=item.get("id"), + cveName=item.get("cveName"), + severity=item.get("severity"), + description=item.get("description"), + packageId=item.get("packageId"), + ) diff --git a/CheckmarxPythonSDK/CxOne/dto/__init__.py b/CheckmarxPythonSDK/CxOne/dto/__init__.py index d97e6087..bce9ea74 100644 --- a/CheckmarxPythonSDK/CxOne/dto/__init__.py +++ b/CheckmarxPythonSDK/CxOne/dto/__init__.py @@ -1,4 +1,26 @@ # encoding: utf-8 +from .BreakBuildExemptStateDto import BreakBuildExemptStateDto +from .ProjectWebDto import ProjectWebDto +from .ViolatingAssocProjectsWebDto import ViolatingAssocProjectsWebDto +from .PolicyWebDto import PolicyWebDto +from .PolicyShortWebDto import PolicyShortWebDto +from .ProjectsInPolicyDto import ProjectsInPolicyDto +from .PoliciesPaginationDto import PoliciesPaginationDto +from .FindingsWebDto import FindingsWebDto +from .VulnerabilityWebDto import VulnerabilityWebDto +from .PackageWebDto import PackageWebDto +from .RuleViolatedWebDto import RuleViolatedWebDto +from .ViolatedPolicyWebDto import ViolatedPolicyWebDto +from .PolicyViolationWebDto import PolicyViolationWebDto +from .IncidentWebDto import IncidentWebDto +from .IncidentsPaginationDto import IncidentsPaginationDto +from .EnhancedIncidentsWebDTO import EnhancedIncidentsWebDTO +from .EnhancedIncidentsPaginationDTO import EnhancedIncidentsPaginationDTO +from .ViolationDetailsDTO import ViolationDetailsDTO +from .IncidentResultWebDTO import IncidentResultWebDTO +from .IncidentResultsDTO import IncidentResultsDTO +from .EvaluatedPolicyWebDto import EvaluatedPolicyWebDto +from .PoliciesResultWebDto import PoliciesResultWebDto from .AiTriageInsight import AiTriageInsight from .RemediationInsight import RemediationInsight from .Risk import Risk diff --git a/CheckmarxPythonSDK/CxOne/policyManagerAPI.py b/CheckmarxPythonSDK/CxOne/policyManagerAPI.py new file mode 100644 index 00000000..7725a14f --- /dev/null +++ b/CheckmarxPythonSDK/CxOne/policyManagerAPI.py @@ -0,0 +1,765 @@ +from typing import List, Optional + +from CheckmarxPythonSDK.api_client import ApiClient +from CheckmarxPythonSDK.CxOne.config import construct_configuration +from .dto import ( + EnhancedIncidentsPaginationDTO, + IncidentResultsDTO, + IncidentsPaginationDto, + PoliciesPaginationDto, + PoliciesResultWebDto, + PolicyShortWebDto, + PolicyViolationWebDto, + PolicyWebDto, + ProjectsInPolicyDto, + ProjectWebDto, +) + + +class PolicyManagerAPI(object): + """API client for the Cx Policy Manager REST API. + + Covers tenant policies (break-build rules evaluated against scan + results), the incidents and results they generate, and the per-scan + policy evaluation/violation views. + + Base URL: {server}/api/policy_management_service_uri + """ + + def __init__(self, api_client: ApiClient = None): + if api_client is None: + configuration = construct_configuration() + api_client = ApiClient(configuration=configuration) + self.api_client = api_client + self.base_url = ( + f"{self.api_client.configuration.server_base_url}" + f"/api/policy_management_service_uri" + ) + + # ========================================================================= + # Policies + # ========================================================================= + + def get_tenant_policies(self) -> List[PolicyWebDto]: + """Get all policies for the tenant (unpaginated). + + Returns: + List[PolicyWebDto]: All tenant policies. + """ + url = f"{self.base_url}/policies" + response = self.api_client.call_api(method="GET", url=url) + return [PolicyWebDto.from_dict(p) for p in response.json()] + + def create_policy(self, policy: PolicyWebDto) -> int: + """Create a new policy. + + Args: + policy (PolicyWebDto): The policy to create. `name` is required. + + Returns: + int: The new policy's ID. + """ + url = f"{self.base_url}/policies" + response = self.api_client.call_api( + method="POST", url=url, json=policy.to_dict() + ) + return response.json() + + def delete_policies(self, ids: List[int]) -> bool: + """Delete multiple policies by ID. + + Args: + ids (List[int]): IDs of the policies to delete. + + Returns: + bool: True if the request succeeded. + """ + url = f"{self.base_url}/policies" + params = {"id": ids} + response = self.api_client.call_api( + method="DELETE", url=url, params=params + ) + return response.status_code in (200, 204) + + def get_policy(self, policy_id: int) -> PolicyWebDto: + """Get a policy by ID. + + Args: + policy_id (int): The policy ID. + + Returns: + PolicyWebDto: The policy. + """ + url = f"{self.base_url}/policies/{policy_id}" + response = self.api_client.call_api(method="GET", url=url) + return PolicyWebDto.from_dict(response.json()) + + def update_policy(self, policy_id: int, policy: PolicyWebDto) -> int: + """Update an existing policy. + + Args: + policy_id (int): The policy ID. + policy (PolicyWebDto): The new policy content. + + Returns: + int: The policy's ID. + """ + url = f"{self.base_url}/policies/{policy_id}" + response = self.api_client.call_api( + method="PUT", url=url, json=policy.to_dict() + ) + return response.json() + + def delete_policy(self, policy_id: int) -> bool: + """Delete a policy by ID. + + Args: + policy_id (int): The policy ID. + + Returns: + bool: True if the request succeeded. + """ + url = f"{self.base_url}/policies/{policy_id}" + response = self.api_client.call_api(method="DELETE", url=url) + return response.status_code in (200, 204) + + def get_policy_v2(self, policy_id: int) -> PolicyWebDto: + """Get a policy by ID (V2). + + Args: + policy_id (int): The policy ID. + + Returns: + PolicyWebDto: The policy. + """ + url = f"{self.base_url}/policies/v2/{policy_id}" + response = self.api_client.call_api(method="GET", url=url) + return PolicyWebDto.from_dict(response.json()) + + def update_policy_v2(self, policy_id: int, policy: PolicyWebDto) -> int: + """Update an existing policy (V2). + + Args: + policy_id (int): The policy ID. + policy (PolicyWebDto): The new policy content. + + Returns: + int: The policy's ID. + """ + url = f"{self.base_url}/policies/v2/{policy_id}" + response = self.api_client.call_api( + method="PUT", url=url, json=policy.to_dict() + ) + return response.json() + + def get_tenant_policies_with_pagination( + self, limit: int, page: int, policy_name: str = "" + ) -> PoliciesPaginationDto: + """Get tenant policies with pagination. + + Args: + limit (int): Page size. 1-1000. + page (int): Page number (1-based). + policy_name (str): Filter by policy name. Default: "". + + Returns: + PoliciesPaginationDto: Policies on the page, and the filtered total count. + """ + url = f"{self.base_url}/policies/v2" + params = {"limit": limit, "page": page, "policyName": policy_name} + response = self.api_client.call_api(method="GET", url=url, params=params) + return PoliciesPaginationDto.from_dict(response.json()) + + def create_policy_v2(self, policy: PolicyWebDto) -> int: + """Create a new policy (V2). + + Args: + policy (PolicyWebDto): The policy to create. `name` is required. + + Returns: + int: The new policy's ID. (The spec claims this returns a + PolicyShortWebDto object; live behavior is a bare int, + same as POST /policies.) + """ + url = f"{self.base_url}/policies/v2" + response = self.api_client.call_api( + method="POST", url=url, json=policy.to_dict() + ) + return response.json() + + def get_tenant_policies_with_pagination_v3( + self, limit: int, page: int, policy_name: str = "" + ) -> PoliciesPaginationDto: + """Get tenant policies with pagination (V3, path /policies/v3). + + Args: + limit (int): Page size. 1-1000. + page (int): Page number (1-based). + policy_name (str): Filter by policy name. Default: "". + + Returns: + PoliciesPaginationDto: Policies on the page, and the filtered total count. + """ + url = f"{self.base_url}/policies/v3" + params = {"limit": limit, "page": page, "policyName": policy_name} + response = self.api_client.call_api(method="GET", url=url, params=params) + return PoliciesPaginationDto.from_dict(response.json()) + + def get_default_policy(self) -> Optional[PolicyShortWebDto]: + """Get the tenant's default policy. + + Returns: + Optional[PolicyShortWebDto]: The default policy's ID and name, + or None if the tenant has no default policy configured + (the API responds 200 with an empty body in that case). + """ + url = f"{self.base_url}/policies/default" + response = self.api_client.call_api(method="GET", url=url) + if not response.text: + return None + return PolicyShortWebDto.from_dict(response.json()) + + def assign_projects_to_policy( + self, policy_id: int, projects: ProjectsInPolicyDto + ) -> int: + """Assign projects to an existing policy. + + Args: + policy_id (int): The policy ID. + projects (ProjectsInPolicyDto): Projects to assign. + + Returns: + int: The policy's ID. + """ + url = f"{self.base_url}/policies/projects/{policy_id}" + response = self.api_client.call_api( + method="PUT", url=url, json=projects.to_dict() + ) + return response.json() + + def delete_projects_from_policy( + self, policy_id: int, projects: ProjectsInPolicyDto + ) -> bool: + """Remove projects from an existing policy. + + Args: + policy_id (int): The policy ID. + projects (ProjectsInPolicyDto): Projects to remove. + + Returns: + bool: True if the request succeeded. + """ + url = f"{self.base_url}/policies/projects/{policy_id}" + response = self.api_client.call_api( + method="DELETE", url=url, json=projects.to_dict() + ) + return response.status_code in (200, 204) + + def pin_policy(self, policy_id: int, pin_policy: bool) -> int: + """Pin or unpin a policy in the policies table. + + Args: + policy_id (int): The policy ID. + pin_policy (bool): True to pin, False to unpin. + + Returns: + int: The policy's ID. + """ + url = f"{self.base_url}/policies/pinPolicy/{policy_id}/{pin_policy}" + response = self.api_client.call_api(method="PUT", url=url) + return response.json() + + # ========================================================================= + # Projects + # ========================================================================= + + def get_tenant_projects(self) -> List[ProjectWebDto]: + """Get all AST projects known to the Policy Manager service. + + Returns: + List[ProjectWebDto]: Tenant projects. + """ + url = f"{self.base_url}/projects" + response = self.api_client.call_api(method="GET", url=url) + return [ProjectWebDto.from_dict(p) for p in response.json()] + + def get_projects_tags(self) -> List[str]: + """Get all AST project tags known to the Policy Manager service. + + Returns: + List[str]: Project tags. + """ + url = f"{self.base_url}/projects/tags" + response = self.api_client.call_api(method="GET", url=url) + return response.json() + + # ========================================================================= + # Policy violations and evaluation + # ========================================================================= + + def get_policy_violations( + self, project_id: str, scan_id: str + ) -> PolicyViolationWebDto: + """Get policy violations for a project's scan. + + Args: + project_id (str): The project ID. + scan_id (str): The scan UUID. + + Returns: + PolicyViolationWebDto: Policies violated by the scan. + """ + url = f"{self.base_url}/policy_violations" + params = {"projectId": project_id, "scanId": scan_id} + response = self.api_client.call_api(method="GET", url=url, params=params) + return PolicyViolationWebDto.from_dict(response.json()) + + def get_evaluated_policies_by_scan_id_and_project_id( + self, scan_id: str, ast_project_id: str + ) -> PoliciesResultWebDto: + """Get the policy evaluation result for a scan and project. + + Args: + scan_id (str): The scan UUID. + ast_project_id (str): The project ID. + + Returns: + PoliciesResultWebDto: Overall status, breakBuild flag, and + per-policy evaluation results. + """ + url = f"{self.base_url}/evaluation" + params = {"scanId": scan_id, "astProjectId": ast_project_id} + response = self.api_client.call_api(method="GET", url=url, params=params) + return PoliciesResultWebDto.from_dict(response.json()) + + # ========================================================================= + # Incidents + # ========================================================================= + + def get_tenant_incidents(self) -> IncidentsPaginationDto: + """Get all tenant incidents (unpaginated). + + Returns: + IncidentsPaginationDto: Incidents and the filtered total count. + """ + url = f"{self.base_url}/incidents" + response = self.api_client.call_api(method="GET", url=url) + return IncidentsPaginationDto.from_dict(response.json()) + + def get_tenant_incidents_total_count(self) -> int: + """Get the tenant's total incident count. + + Returns: + int: Total number of incidents. + """ + url = f"{self.base_url}/incidents/total" + response = self.api_client.call_api(method="GET", url=url) + return response.json() + + def get_tenant_incidents_with_pagination( + self, limit: int, page: int, incident_name: str = "" + ) -> IncidentsPaginationDto: + """Get tenant incidents with pagination. + + Args: + limit (int): Page size. 1-1000. + page (int): Page number (1-based). + incident_name (str): Filter by incident name. Default: "". + + Returns: + IncidentsPaginationDto: Incidents on the page, and the filtered + total count. + """ + url = f"{self.base_url}/incidents/" + params = {"limit": limit, "page": page, "incidentName": incident_name} + response = self.api_client.call_api(method="GET", url=url, params=params) + return IncidentsPaginationDto.from_dict(response.json()) + + def get_tenant_incidents_with_pagination_and_filters( + self, + limit: int, + page: int, + policy_name: str = "", + rule_name: str = "", + scan_id: str = "", + project_name: str = "", + branch: str = "", + scan_date: str = "", + ) -> IncidentsPaginationDto: + """Get tenant incidents with pagination and filters. + + Args: + limit (int): Page size. 1-1000. + page (int): Page number (1-based). + policy_name (str): Filter by policy name. Default: "". + rule_name (str): Filter by rule name. Default: "". + scan_id (str): Filter by scan UUID. Default: "". + project_name (str): Filter by project name. Default: "". + branch (str): Filter by branch. Default: "". + scan_date (str): Filter by scan date. Default: "". + + Returns: + IncidentsPaginationDto: Incidents on the page, and the filtered + total count. + """ + url = f"{self.base_url}/incidents/filters" + params = { + "limit": limit, + "page": page, + "policyName": policy_name, + "ruleName": rule_name, + "scanId": scan_id, + "projectName": project_name, + "branch": branch, + "scanDate": scan_date, + } + response = self.api_client.call_api(method="GET", url=url, params=params) + return IncidentsPaginationDto.from_dict(response.json()) + + def get_enhanced_incidents_with_pagination_and_filters( + self, + limit: int, + page: int, + policy_name: str = "", + rule_name: str = "", + scan_id: str = "", + project_name: str = "", + branch: str = "", + scanner: str = "", + tags: str = "", + scan_date_from: str = "", + scan_date_to: str = "", + sort: str = "", + sort_field: str = "", + sort_order: str = "", + ) -> EnhancedIncidentsPaginationDTO: + """Get tenant incidents (V2, with engine info) with pagination, + filters, and sorting. + + Args: + limit (int): Page size. Minimum 1. + page (int): Page number (1-based). + policy_name (str): Filter by policy name. Default: "". + rule_name (str): Filter by rule name. Default: "". + scan_id (str): Filter by scan UUID. Default: "". + project_name (str): Filter by project name. Default: "". + branch (str): Filter by branch. Default: "". + scanner (str): Filter by scanner engine. Default: "". + tags (str): Filter by policy tags. Default: "". + scan_date_from (str): Filter by scan date range start. Default: "". + scan_date_to (str): Filter by scan date range end. Default: "". + sort (str): Sort direction. Default: "". + sort_field (str): Field to sort by. Default: "". + sort_order (str): Sort order. Default: "". + + Returns: + EnhancedIncidentsPaginationDTO: Incidents on the page, and the + filtered total count. + """ + url = f"{self.base_url}/incidents/filters/v2" + params = { + "limit": limit, + "page": page, + "policyName": policy_name, + "ruleName": rule_name, + "scanId": scan_id, + "projectName": project_name, + "branch": branch, + "scanner": scanner, + "tags": tags, + "scanDateFrom": scan_date_from, + "scanDateTo": scan_date_to, + "sort": sort, + "sortField": sort_field, + "sortOrder": sort_order, + } + response = self.api_client.call_api(method="GET", url=url, params=params) + return EnhancedIncidentsPaginationDTO.from_dict(response.json()) + + def get_incident_results( + self, + incident_id: int, + limit: int, + page: int, + issue: str = "", + search: str = "", + severity: str = "", + sort_field: str = "severity", + sort_order: str = "descend", + ) -> IncidentResultsDTO: + """Get the results underlying a specific incident. + + Args: + incident_id (int): The incident ID. + limit (int): Page size. Minimum 1. + page (int): Page number (1-based). + issue (str): Legacy issue-name filter. Ignored if `search` is + also provided (a non-blank `search` takes precedence). + Default: "". + search (str): Free-text search over the issue name. Takes + precedence over `issue` when non-blank. Default: "". + severity (str): Filter by severity. Default: "". + sort_field (str): Field to sort by. Default: "severity". + sort_order (str): Sort order. Default: "descend". + + Returns: + IncidentResultsDTO: Violation details common to all results, + the results on the page, and the filtered total count. + """ + url = f"{self.base_url}/incidents/{incident_id}/results" + params = { + "limit": limit, + "page": page, + "issue": issue, + "search": search, + "severity": severity, + "sortField": sort_field, + "sortOrder": sort_order, + } + response = self.api_client.call_api(method="GET", url=url, params=params) + return IncidentResultsDTO.from_dict(response.json()) + + # ========================================================================= + # Internal data retention + # ========================================================================= + + def delete_data(self, limitation: int = None) -> bool: + """Delete data from all services implementing IDataRetention. + + Args: + limitation (int): Maximum number of records to delete, if given. + + Returns: + bool: True if the request succeeded. + """ + url = f"{self.base_url}/internal/data-retention" + params = {"limitation": limitation} + response = self.api_client.call_api( + method="DELETE", url=url, params=params + ) + return response.status_code in (200, 204) + + def delete_data_for_service( + self, service_name: str, limitation: int = None + ) -> bool: + """Delete data from a specific service implementing IDataRetention. + + Args: + service_name (str): The service's name. + limitation (int): Maximum number of records to delete, if given. + + Returns: + bool: True if the request succeeded. + """ + url = f"{self.base_url}/internal/data-retention/{service_name}" + params = {"limitation": limitation} + response = self.api_client.call_api( + method="DELETE", url=url, params=params + ) + return response.status_code in (200, 204) + + +# ---- Module-level convenience functions ---- + +def get_tenant_policies() -> List[PolicyWebDto]: + return PolicyManagerAPI().get_tenant_policies() + + +def create_policy(policy: PolicyWebDto) -> int: + return PolicyManagerAPI().create_policy(policy=policy) + + +def delete_policies(ids: List[int]) -> bool: + return PolicyManagerAPI().delete_policies(ids=ids) + + +def get_policy(policy_id: int) -> PolicyWebDto: + return PolicyManagerAPI().get_policy(policy_id=policy_id) + + +def update_policy(policy_id: int, policy: PolicyWebDto) -> int: + return PolicyManagerAPI().update_policy(policy_id=policy_id, policy=policy) + + +def delete_policy(policy_id: int) -> bool: + return PolicyManagerAPI().delete_policy(policy_id=policy_id) + + +def get_policy_v2(policy_id: int) -> PolicyWebDto: + return PolicyManagerAPI().get_policy_v2(policy_id=policy_id) + + +def update_policy_v2(policy_id: int, policy: PolicyWebDto) -> int: + return PolicyManagerAPI().update_policy_v2(policy_id=policy_id, policy=policy) + + +def get_tenant_policies_with_pagination( + limit: int, page: int, policy_name: str = "" +) -> PoliciesPaginationDto: + return PolicyManagerAPI().get_tenant_policies_with_pagination( + limit=limit, page=page, policy_name=policy_name + ) + + +def create_policy_v2(policy: PolicyWebDto) -> int: + return PolicyManagerAPI().create_policy_v2(policy=policy) + + +def get_tenant_policies_with_pagination_v3( + limit: int, page: int, policy_name: str = "" +) -> PoliciesPaginationDto: + return PolicyManagerAPI().get_tenant_policies_with_pagination_v3( + limit=limit, page=page, policy_name=policy_name + ) + + +def get_default_policy() -> Optional[PolicyShortWebDto]: + return PolicyManagerAPI().get_default_policy() + + +def assign_projects_to_policy( + policy_id: int, projects: ProjectsInPolicyDto +) -> int: + return PolicyManagerAPI().assign_projects_to_policy( + policy_id=policy_id, projects=projects + ) + + +def delete_projects_from_policy( + policy_id: int, projects: ProjectsInPolicyDto +) -> bool: + return PolicyManagerAPI().delete_projects_from_policy( + policy_id=policy_id, projects=projects + ) + + +def pin_policy(policy_id: int, pin_policy_flag: bool) -> int: + return PolicyManagerAPI().pin_policy( + policy_id=policy_id, pin_policy=pin_policy_flag + ) + + +def get_tenant_projects() -> List[ProjectWebDto]: + return PolicyManagerAPI().get_tenant_projects() + + +def get_projects_tags() -> List[str]: + return PolicyManagerAPI().get_projects_tags() + + +def get_policy_violations(project_id: str, scan_id: str) -> PolicyViolationWebDto: + return PolicyManagerAPI().get_policy_violations( + project_id=project_id, scan_id=scan_id + ) + + +def get_evaluated_policies_by_scan_id_and_project_id( + scan_id: str, ast_project_id: str +) -> PoliciesResultWebDto: + return PolicyManagerAPI().get_evaluated_policies_by_scan_id_and_project_id( + scan_id=scan_id, ast_project_id=ast_project_id + ) + + +def get_tenant_incidents() -> IncidentsPaginationDto: + return PolicyManagerAPI().get_tenant_incidents() + + +def get_tenant_incidents_total_count() -> int: + return PolicyManagerAPI().get_tenant_incidents_total_count() + + +def get_tenant_incidents_with_pagination( + limit: int, page: int, incident_name: str = "" +) -> IncidentsPaginationDto: + return PolicyManagerAPI().get_tenant_incidents_with_pagination( + limit=limit, page=page, incident_name=incident_name + ) + + +def get_tenant_incidents_with_pagination_and_filters( + limit: int, + page: int, + policy_name: str = "", + rule_name: str = "", + scan_id: str = "", + project_name: str = "", + branch: str = "", + scan_date: str = "", +) -> IncidentsPaginationDto: + return PolicyManagerAPI().get_tenant_incidents_with_pagination_and_filters( + limit=limit, + page=page, + policy_name=policy_name, + rule_name=rule_name, + scan_id=scan_id, + project_name=project_name, + branch=branch, + scan_date=scan_date, + ) + + +def get_enhanced_incidents_with_pagination_and_filters( + limit: int, + page: int, + policy_name: str = "", + rule_name: str = "", + scan_id: str = "", + project_name: str = "", + branch: str = "", + scanner: str = "", + tags: str = "", + scan_date_from: str = "", + scan_date_to: str = "", + sort: str = "", + sort_field: str = "", + sort_order: str = "", +) -> EnhancedIncidentsPaginationDTO: + return PolicyManagerAPI().get_enhanced_incidents_with_pagination_and_filters( + limit=limit, + page=page, + policy_name=policy_name, + rule_name=rule_name, + scan_id=scan_id, + project_name=project_name, + branch=branch, + scanner=scanner, + tags=tags, + scan_date_from=scan_date_from, + scan_date_to=scan_date_to, + sort=sort, + sort_field=sort_field, + sort_order=sort_order, + ) + + +def get_incident_results( + incident_id: int, + limit: int, + page: int, + issue: str = "", + search: str = "", + severity: str = "", + sort_field: str = "severity", + sort_order: str = "descend", +) -> IncidentResultsDTO: + return PolicyManagerAPI().get_incident_results( + incident_id=incident_id, + limit=limit, + page=page, + issue=issue, + search=search, + severity=severity, + sort_field=sort_field, + sort_order=sort_order, + ) + + +def delete_data(limitation: int = None) -> bool: + return PolicyManagerAPI().delete_data(limitation=limitation) + + +def delete_data_for_service(service_name: str, limitation: int = None) -> bool: + return PolicyManagerAPI().delete_data_for_service( + service_name=service_name, limitation=limitation + ) diff --git a/docs/CxOne_REST_API_List.md b/docs/CxOne_REST_API_List.md index cdda3cc8..b462c0af 100644 --- a/docs/CxOne_REST_API_List.md +++ b/docs/CxOne_REST_API_List.md @@ -225,6 +225,33 @@ | ORGANIZATIONAL_DOMAINS.yaml | OrganizationalDomainsAPI | `list_organizational_domains` | GET | `/api/organizational-domains` | | ORGANIZATIONAL_DOMAINS.yaml | OrganizationalDomainsAPI | `add_organizational_domains` | POST | `/api/organizational-domains` | | ORGANIZATIONAL_DOMAINS.yaml | OrganizationalDomainsAPI | `delete_organizational_domain` | DELETE | `/api/organizational-domains/{id}` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `get_tenant_policies` | GET | `/api/policy_management_service_uri/policies` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `create_policy` | POST | `/api/policy_management_service_uri/policies` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `delete_policies` | DELETE | `/api/policy_management_service_uri/policies` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `get_policy` | GET | `/api/policy_management_service_uri/policies/{policy_id}` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `update_policy` | PUT | `/api/policy_management_service_uri/policies/{policy_id}` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `delete_policy` | DELETE | `/api/policy_management_service_uri/policies/{policy_id}` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `get_policy_v2` | GET | `/api/policy_management_service_uri/policies/v2/{policy_id}` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `update_policy_v2` | PUT | `/api/policy_management_service_uri/policies/v2/{policy_id}` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `get_tenant_policies_with_pagination` | GET | `/api/policy_management_service_uri/policies/v2` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `create_policy_v2` | POST | `/api/policy_management_service_uri/policies/v2` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `get_tenant_policies_with_pagination_v3` | GET | `/api/policy_management_service_uri/policies/v3` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `get_default_policy` | GET | `/api/policy_management_service_uri/policies/default` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `assign_projects_to_policy` | PUT | `/api/policy_management_service_uri/policies/projects/{policy_id}` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `delete_projects_from_policy` | DELETE | `/api/policy_management_service_uri/policies/projects/{policy_id}` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `pin_policy` | PUT | `/api/policy_management_service_uri/policies/pinPolicy/{policy_id}/{pin_policy}` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `get_tenant_projects` | GET | `/api/policy_management_service_uri/projects` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `get_projects_tags` | GET | `/api/policy_management_service_uri/projects/tags` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `get_policy_violations` | GET | `/api/policy_management_service_uri/policy_violations` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `get_evaluated_policies_by_scan_id_and_project_id` | GET | `/api/policy_management_service_uri/evaluation` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `get_tenant_incidents` | GET | `/api/policy_management_service_uri/incidents` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `get_tenant_incidents_total_count` | GET | `/api/policy_management_service_uri/incidents/total` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `get_tenant_incidents_with_pagination` | GET | `/api/policy_management_service_uri/incidents/` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `get_tenant_incidents_with_pagination_and_filters` | GET | `/api/policy_management_service_uri/incidents/filters` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `get_enhanced_incidents_with_pagination_and_filters` | GET | `/api/policy_management_service_uri/incidents/filters/v2` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `get_incident_results` | GET | `/api/policy_management_service_uri/incidents/{incident_id}/results` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `delete_data` | DELETE | `/api/policy_management_service_uri/internal/data-retention` | +| POLICY_MANAGER.yaml | PolicyManagerAPI | `delete_data_for_service` | DELETE | `/api/policy_management_service_uri/internal/data-retention/{service_name}` | | PRESET_MANAGER.yaml | PresetManagerAPI | `get_scanner_presets` | GET | `/api/preset-manager/{scanner}/presets` | | PRESET_MANAGER.yaml | PresetManagerAPI | `get_scanner_preset_by_id` | GET | `/api/preset-manager/{scanner}/presets/{id}` | | PRESET_MANAGER.yaml | PresetManagerAPI | `create_preset` | POST | `/api/preset-manager/{scanner}/presets` | diff --git a/docs/swagger_yaml/CxOne/POLICY_MANAGER.yaml b/docs/swagger_yaml/CxOne/POLICY_MANAGER.yaml new file mode 100644 index 00000000..66df691a --- /dev/null +++ b/docs/swagger_yaml/CxOne/POLICY_MANAGER.yaml @@ -0,0 +1,1202 @@ +openapi: 3.0.1 +info: + title: Cx Policy Manager API + description: Cx Policy Manager Endpoints + version: v0.0.1 +paths: + /policies/{policyId}: + get: + tags: + - policy-controller + summary: Get policy by id + operationId: getPolicy + parameters: + - name: policyId + in: path + required: true + schema: + type: integer + format: int64 + responses: + "200": + description: OK + content: + '*/*': + schema: + $ref: "#/components/schemas/PolicyWebDto" + put: + tags: + - policy-controller + summary: Update existing policy + operationId: updatePolicy + parameters: + - name: policyId + in: path + required: true + schema: + type: integer + format: int64 + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PolicyWebDto" + required: true + responses: + "200": + description: OK + content: + '*/*': + schema: + type: integer + format: int64 + delete: + tags: + - policy-controller + summary: Delete policy by id + operationId: deletePolicy + parameters: + - name: policyId + in: path + required: true + schema: + type: integer + format: int64 + responses: + "200": + description: OK + /policies/v2/{policyId}: + get: + tags: + - policy-controller + summary: Get policy by id (V2) + operationId: getPolicyV2 + parameters: + - name: policyId + in: path + required: true + schema: + type: integer + format: int64 + responses: + "200": + description: OK + content: + '*/*': + schema: + $ref: "#/components/schemas/PolicyWebDto" + put: + tags: + - policy-controller + summary: Update existing policy (V2) + operationId: updatePolicyV2 + parameters: + - name: policyId + in: path + required: true + schema: + type: integer + format: int64 + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PolicyWebDto" + required: true + responses: + "200": + description: OK + content: + '*/*': + schema: + type: integer + format: int64 + /policies/projects/{policyId}: + put: + tags: + - policy-controller + summary: Assign projects to existing policy + operationId: assignProjectsToPolicy + parameters: + - name: policyId + in: path + required: true + schema: + type: integer + format: int64 + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/ProjectsInPolicyDto" + required: true + responses: + "200": + description: OK + content: + '*/*': + schema: + type: integer + format: int64 + delete: + tags: + - policy-controller + summary: Delete projects from existing policy + operationId: deleteProjectsFromPolicy + parameters: + - name: policyId + in: path + required: true + schema: + type: integer + format: int64 + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/ProjectsInPolicyDto" + required: true + responses: + "200": + description: OK + /policies/pinPolicy/{policyId}/{pinPolicy}: + put: + tags: + - policy-controller + summary: Pin/unPin policy in table + operationId: pinPolicy + parameters: + - name: policyId + in: path + required: true + schema: + type: integer + format: int64 + - name: pinPolicy + in: path + required: true + schema: + type: boolean + responses: + "200": + description: OK + content: + '*/*': + schema: + type: integer + format: int64 + /policies: + get: + tags: + - policy-controller + summary: Get tenant policies. + operationId: getTenantPolicies + responses: + "200": + description: OK + content: + '*/*': + schema: + uniqueItems: true + type: array + items: + $ref: "#/components/schemas/PolicyWebDto" + post: + tags: + - policy-controller + summary: Create policy + operationId: createPolicy + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PolicyWebDto" + required: true + responses: + "200": + description: OK + content: + '*/*': + schema: + type: integer + format: int64 + delete: + tags: + - policy-controller + summary: Delete policies by ids + operationId: deletePolicies + parameters: + - name: id + in: query + required: true + schema: + type: array + items: + type: integer + format: int64 + responses: + "200": + description: OK + /policies/v2: + get: + tags: + - policy-controller + summary: Get tenant policies with pagination + operationId: getTenantPoliciesWithPagination + parameters: + - name: limit + in: query + required: true + schema: + maximum: 1000 + minimum: 1 + type: integer + format: int32 + - name: page + in: query + required: true + schema: + minimum: 1 + type: integer + format: int32 + - name: policyName + in: query + required: false + schema: + type: string + default: "" + responses: + "200": + description: OK + content: + '*/*': + schema: + $ref: "#/components/schemas/PoliciesPaginationDto" + post: + tags: + - policy-controller + summary: Create policy (V2) + operationId: createPolicyV2 + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PolicyWebDto" + required: true + responses: + "200": + description: OK + content: + '*/*': + schema: + $ref: "#/components/schemas/PolicyShortWebDto" + /projects: + get: + tags: + - project-controller + summary: Get tenant projects. + operationId: getTenantProjects + responses: + "200": + description: OK + content: + '*/*': + schema: + uniqueItems: true + type: array + items: + $ref: "#/components/schemas/ProjectWebDto" + /projects/tags: + get: + tags: + - project-controller + summary: Get AST projects tags + operationId: getProjectsTags + responses: + "200": + description: OK + content: + '*/*': + schema: + uniqueItems: true + type: array + items: + type: string + /policy_violations: + get: + tags: + - policy-violation-controller + summary: Get policy violations by projectId and scanId + operationId: getPolicyViolations + parameters: + - name: projectId + in: query + required: true + schema: + type: string + - name: scanId + in: query + required: true + schema: + type: string + format: uuid + responses: + "200": + description: OK + content: + '*/*': + schema: + $ref: "#/components/schemas/PolicyViolationWebDto" + /policies/v3: + get: + tags: + - policy-controller + summary: Get tenant policies with pagination (V3) + operationId: getTenantPoliciesWithPaginationV2 + parameters: + - name: limit + in: query + required: true + schema: + maximum: 1000 + minimum: 1 + type: integer + format: int32 + - name: page + in: query + required: true + schema: + minimum: 1 + type: integer + format: int32 + - name: policyName + in: query + required: false + schema: + type: string + default: "" + responses: + "200": + description: OK + content: + '*/*': + schema: + $ref: "#/components/schemas/PoliciesPaginationDto" + /policies/default: + get: + tags: + - policy-controller + summary: Get default policy + operationId: getDefaultPolicy + responses: + "200": + description: OK + content: + '*/*': + schema: + $ref: "#/components/schemas/PolicyShortWebDto" + /incidents: + get: + tags: + - incident-controller + summary: Get tenant incidents. + operationId: getTenantIncidents + responses: + "200": + description: OK + content: + '*/*': + schema: + $ref: "#/components/schemas/IncidentsPaginationDto" + /incidents/total: + get: + tags: + - incident-controller + summary: Get tenant incidents total count. + operationId: getTenantIncidentsTotalCount + responses: + "200": + description: OK + content: + '*/*': + schema: + type: integer + format: int64 + /incidents/filters: + get: + tags: + - incident-controller + summary: Get tenant incidents with pagination and filters + operationId: getTenantIncidentsWithPaginationAndFilters + parameters: + - name: limit + in: query + required: true + schema: + maximum: 1000 + minimum: 1 + type: integer + format: int32 + - name: page + in: query + required: true + schema: + minimum: 1 + type: integer + format: int32 + - name: policyName + in: query + required: false + schema: + type: string + default: "" + - name: ruleName + in: query + required: false + schema: + type: string + default: "" + - name: scanId + in: query + required: false + schema: + type: string + default: "" + - name: projectName + in: query + required: false + schema: + type: string + default: "" + - name: branch + in: query + required: false + schema: + type: string + default: "" + - name: scanDate + in: query + required: false + schema: + type: string + default: "" + responses: + "200": + description: OK + content: + '*/*': + schema: + $ref: "#/components/schemas/IncidentsPaginationDto" + /incidents/: + get: + tags: + - incident-controller + summary: Get tenant incidents with pagination + operationId: getTenantIncidentsWithPagination + parameters: + - name: limit + in: query + required: true + schema: + maximum: 1000 + minimum: 1 + type: integer + format: int32 + - name: page + in: query + required: true + schema: + minimum: 1 + type: integer + format: int32 + - name: incidentName + in: query + required: false + schema: + type: string + default: "" + responses: + "200": + description: OK + content: + '*/*': + schema: + $ref: "#/components/schemas/IncidentsPaginationDto" + /incidents/filters/v2: + get: + tags: + - incident-controller + summary: Get tenant enhanced incidents V2 with pagination, filters and sorting + operationId: getEnhancedIncidentsWithPaginationAndFilters + parameters: + - name: limit + in: query + required: true + schema: + minimum: 1 + type: integer + format: int32 + - name: page + in: query + required: true + schema: + minimum: 1 + type: integer + format: int32 + - name: policyName + in: query + required: false + schema: + type: string + default: "" + - name: ruleName + in: query + required: false + schema: + type: string + default: "" + - name: scanId + in: query + required: false + schema: + type: string + default: "" + - name: projectName + in: query + required: false + schema: + type: string + default: "" + - name: branch + in: query + required: false + schema: + type: string + default: "" + - name: scanner + in: query + required: false + schema: + type: string + default: "" + - name: tags + in: query + required: false + schema: + type: string + default: "" + - name: scanDateFrom + in: query + required: false + schema: + type: string + default: "" + - name: scanDateTo + in: query + required: false + schema: + type: string + default: "" + - name: sort + in: query + required: false + schema: + type: string + default: "" + - name: sortField + in: query + required: false + schema: + type: string + default: "" + - name: sortOrder + in: query + required: false + schema: + type: string + default: "" + responses: + "200": + description: OK + content: + '*/*': + schema: + $ref: "#/components/schemas/EnhancedIncidentsPaginationDTO" + /incidents/{incidentId}/results: + get: + tags: + - incident-controller + summary: Get results for a specific incident + operationId: getIncidentResults + parameters: + - name: incidentId + in: path + required: true + schema: + type: integer + format: int64 + - name: limit + in: query + required: true + schema: + minimum: 1 + type: integer + format: int32 + - name: page + in: query + required: true + schema: + minimum: 1 + type: integer + format: int32 + - name: issue + in: query + required: false + description: Legacy issue-name filter. Ignored if 'search' is also provided (non-blank 'search' takes precedence). + schema: + type: string + default: "" + - name: search + in: query + required: false + description: Free-text search over the issue name. Takes precedence over 'issue' when non-blank. + schema: + type: string + default: "" + - name: severity + in: query + required: false + schema: + type: string + default: "" + - name: sortField + in: query + required: false + schema: + type: string + default: "severity" + - name: sortOrder + in: query + required: false + schema: + type: string + default: "descend" + responses: + "200": + description: OK + content: + '*/*': + schema: + $ref: "#/components/schemas/IncidentResultsDTO" + /evaluation: + get: + tags: + - evaluated-policy-controller + summary: Get evaluated policy by scan id and ast project id + operationId: getEvaluatedPoliciesByScanIdAndProjectId + parameters: + - name: scanId + in: query + required: true + schema: + type: string + format: uuid + - name: astProjectId + in: query + required: true + schema: + type: string + responses: + "200": + description: OK + content: + '*/*': + schema: + $ref: "#/components/schemas/PoliciesResultWebDto" + /internal/data-retention: + delete: + tags: + - data-retention-controller + summary: Delete data from all the services that implements the IDataRetention + operationId: deleteData + parameters: + - name: limitation + in: query + required: false + schema: + type: integer + format: int32 + responses: + "200": + description: OK + /internal/data-retention/{serviceName}: + delete: + tags: + - data-retention-controller + summary: Delete data from a specific service that implements the IDataRetention + operationId: deleteData_1 + parameters: + - name: serviceName + in: path + required: true + schema: + type: string + - name: limitation + in: query + required: false + schema: + type: integer + format: int32 + responses: + "200": + description: OK +components: + schemas: + BreakBuildExemptStateDto: + type: object + properties: + scanner: + type: string + ruleName: + maxLength: 255 + minLength: 0 + type: string + stateName: + type: array + items: + type: string + PolicyWebDto: + required: + - name + type: object + properties: + id: + type: integer + format: int64 + name: + maxLength: 255 + minLength: 1 + type: string + description: + maxLength: 2500 + minLength: 0 + type: string + isActivated: + type: boolean + tags: + maxItems: 50 + minItems: 0 + uniqueItems: true + type: array + items: + type: string + breakBuild: + type: boolean + pinPolicy: + type: boolean + lastViolated: + type: string + format: date-time + updatedAt: + type: string + format: date-time + projects: + uniqueItems: true + type: array + items: + $ref: "#/components/schemas/ProjectWebDto" + netNewBreakBuild: + type: boolean + type: + type: string + enum: + - NET_NEW + - ENGINES_RULES + allScannersSeverities: + uniqueItems: true + type: array + items: + type: string + enum: + - CRITICAL + - HIGH + - MEDIUM + - LOW + - INFO + violatingAssocProjects: + $ref: "#/components/schemas/ViolatingAssocProjectsWebDto" + netNewScannerMode: + type: string + enum: + - ALL_SCANNERS + - BY_SCANNER + scannerSeverities: + type: object + additionalProperties: + uniqueItems: true + type: array + items: + type: string + enum: + - CRITICAL + - HIGH + - MEDIUM + - LOW + - INFO + breakBuildExemptStates: + type: array + items: + $ref: "#/components/schemas/BreakBuildExemptStateDto" + defaultPolicy: + type: boolean + ProjectWebDto: + required: + - astProjectId + type: object + properties: + astProjectId: + type: string + name: + type: string + ViolatingAssocProjectsWebDto: + type: object + properties: + assocProjects: + type: integer + format: int64 + violating: + type: integer + format: int64 + ProjectsInPolicyDto: + type: object + properties: + projects: + uniqueItems: true + type: array + items: + $ref: "#/components/schemas/ProjectWebDto" + id: + type: integer + format: int64 + PolicyShortWebDto: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + FindingsWebDto: + type: object + properties: + resultId: + type: string + similarityId: + type: string + queryId: + type: string + queryName: + type: string + severity: + type: string + cweId: + type: integer + format: int64 + fileName: + type: string + line: + type: integer + format: int32 + description: + type: string + stateName: + type: string + PackageWebDto: + type: object + properties: + id: + type: string + name: + type: string + version: + type: string + outdated: + type: boolean + highVulnerabilityCount: + type: integer + format: int32 + mediumVulnerabilityCount: + type: integer + format: int32 + packageState: + type: string + vulnerabilities: + type: array + items: + $ref: "#/components/schemas/VulnerabilityWebDto" + PolicyViolationWebDto: + type: object + properties: + scanId: + type: string + format: uuid + projectId: + type: string + generatedOn: + type: string + format: date-time + policies: + type: array + items: + $ref: "#/components/schemas/ViolatedPolicyWebDto" + status: + type: string + enum: + - COMPLETED + - EVALUATING + - NONE + RuleViolatedWebDto: + type: object + properties: + ruleName: + type: string + scanner: + type: string + packages: + type: array + items: + $ref: "#/components/schemas/PackageWebDto" + findings: + type: array + items: + $ref: "#/components/schemas/FindingsWebDto" + ViolatedPolicyWebDto: + type: object + properties: + policyName: + type: string + description: + type: string + tags: + type: array + items: + type: string + breakBuild: + type: boolean + rulesViolated: + type: array + items: + $ref: "#/components/schemas/RuleViolatedWebDto" + VulnerabilityWebDto: + type: object + properties: + id: + type: string + cveName: + type: string + severity: + type: string + description: + type: string + packageId: + type: string + PoliciesPaginationDto: + type: object + properties: + policies: + type: array + items: + $ref: "#/components/schemas/PolicyWebDto" + filteredPoliciesCount: + type: integer + format: int64 + IncidentWebDto: + type: object + properties: + id: + type: integer + format: int64 + policyName: + type: string + projectName: + type: string + branch: + type: string + ruleName: + type: string + scanId: + type: string + scanDate: + type: string + format: date-time + policyTags: + uniqueItems: true + type: array + items: + type: string + defaultPolicy: + type: boolean + defaultPolicyEvaluation: + type: boolean + IncidentsPaginationDto: + type: object + properties: + incidents: + type: array + items: + $ref: "#/components/schemas/IncidentWebDto" + filteredIncidentsCount: + type: integer + format: int64 + EvaluatedPolicyWebDto: + type: object + properties: + policyName: + type: string + description: + type: string + rulesViolated: + type: array + items: + type: string + tags: + uniqueItems: true + type: array + items: + type: string + breakBuild: + type: boolean + status: + type: string + enum: + - PASSED + - FAILED + EnhancedIncidentsWebDTO: + type: object + properties: + id: + type: integer + format: int64 + policyName: + type: string + projectName: + type: string + branch: + type: string + ruleName: + type: string + scanId: + type: string + scanDate: + type: string + format: date-time + policyTags: + type: array + items: + type: string + defaultPolicy: + type: boolean + defaultPolicyEvaluation: + type: boolean + engine: + type: string + EnhancedIncidentsPaginationDTO: + type: object + properties: + incidents: + type: array + items: + $ref: "#/components/schemas/EnhancedIncidentsWebDTO" + filteredIncidentsCount: + type: integer + format: int64 + ViolationDetailsDTO: + type: object + properties: + policyName: + type: string + ruleName: + type: string + engine: + type: string + conditions: + type: array + items: + type: string + breakBuild: + type: boolean + IncidentResultWebDTO: + type: object + properties: + id: + type: integer + format: int64 + severity: + type: string + issue: + type: string + issueLink: + type: string + cweLink: + type: string + sourceFilePackage: + type: string + sourceFileLink: + type: string + lineNumber: + type: integer + format: int64 + insight: + type: string + insightLink: + type: string + resultId: + type: string + recommendedVersion: + type: string + attackVector: + type: string + attackComplexity: + type: string + riskOrchestrationLink: + type: string + sastResultsLink: + type: string + IncidentResultsDTO: + type: object + properties: + violationDetails: + $ref: "#/components/schemas/ViolationDetailsDTO" + results: + type: array + items: + $ref: "#/components/schemas/IncidentResultWebDTO" + filteredResultsCount: + type: integer + format: int64 + PoliciesResultWebDto: + type: object + properties: + status: + type: string + enum: + - COMPLETED + - NONE + - EVALUATING + breakBuild: + type: boolean + policies: + type: array + items: + $ref: "#/components/schemas/EvaluatedPolicyWebDto" + securitySchemes: + Login: + type: oauth2 + flows: + implicit: + authorizationUrl: /spec/cxauth.html + scopes: {} +servers: + - url: /api/policy_management_service_uri +security: + - Login: [] diff --git a/tests/CxOne/test_policy_manager_api.py b/tests/CxOne/test_policy_manager_api.py new file mode 100644 index 00000000..3cc2a67a --- /dev/null +++ b/tests/CxOne/test_policy_manager_api.py @@ -0,0 +1,249 @@ +import pytest + +from CheckmarxPythonSDK.CxOne import ( + assign_projects_to_policy, + create_policy, + create_policy_v2, + delete_policies, + delete_policy, + delete_projects_from_policy, + get_default_policy, + get_enhanced_incidents_with_pagination_and_filters, + get_evaluated_policies_by_scan_id_and_project_id, + get_policy, + get_policy_v2, + get_policy_violations, + get_projects_tags, + get_tenant_incidents, + get_tenant_incidents_total_count, + get_tenant_incidents_with_pagination, + get_tenant_incidents_with_pagination_and_filters, + get_tenant_policies, + get_tenant_policies_with_pagination, + get_tenant_policies_with_pagination_v3, + get_tenant_projects, + pin_policy, + update_policy, + update_policy_v2, +) +from CheckmarxPythonSDK.CxOne import ScansAPI as _ScansAPI +from CheckmarxPythonSDK.CxOne.dto import ( + IncidentsPaginationDto, + PoliciesPaginationDto, + PolicyViolationWebDto, + PolicyWebDto, + ProjectsInPolicyDto, + ProjectWebDto, +) + +_TEST_POLICY_NAME = "sdk-test-policy-delete-me" + + +def _skip_on_client_error(e: Exception): + msg = str(e) + if "400" in msg or "401" in msg or "403" in msg or "404" in msg: + pytest.skip("API returned client error: {}".format(msg)) + raise e + + +@pytest.fixture +def temp_policy(): + """Create a throwaway policy for a test, and delete it afterwards.""" + try: + policy_id = create_policy(PolicyWebDto(name=_TEST_POLICY_NAME)) + except Exception as e: + _skip_on_client_error(e) + return + try: + yield policy_id + finally: + delete_policy(policy_id) + + +@pytest.fixture(scope="session") +def completed_scan(): + """A recently completed scan, for the per-scan endpoints.""" + try: + scans = _ScansAPI().get_a_list_of_scans( + limit=1, offset=0, statuses=["Completed"] + ) + except Exception as e: + pytest.skip("Could not list scans: {}".format(e)) + return + if not scans.scans: + pytest.skip("No completed scans found") + return scans.scans[0] + + +# ---- Policies ---- + + +def test_get_tenant_policies(): + policies = get_tenant_policies() + assert isinstance(policies, list) + for p in policies: + assert isinstance(p, PolicyWebDto) + assert p.id is not None + assert p.name is not None + + +def test_get_tenant_policies_with_pagination(): + result = get_tenant_policies_with_pagination(limit=5, page=1) + assert isinstance(result, PoliciesPaginationDto) + assert isinstance(result.filteredPoliciesCount, int) + assert len(result.policies) <= 5 + + +def test_get_tenant_policies_with_pagination_v3(): + result = get_tenant_policies_with_pagination_v3(limit=5, page=1) + assert isinstance(result, PoliciesPaginationDto) + assert isinstance(result.filteredPoliciesCount, int) + + +def test_get_default_policy(): + # May legitimately be None if the tenant has no default policy set. + result = get_default_policy() + assert result is None or result.id is not None + + +def test_create_get_update_delete_policy_lifecycle(): + policy_id = create_policy(PolicyWebDto(name=_TEST_POLICY_NAME)) + try: + policy = get_policy(policy_id) + assert isinstance(policy, PolicyWebDto) + assert policy.id == policy_id + assert policy.name == _TEST_POLICY_NAME + + policy.description = "updated by test" + assert update_policy(policy_id, policy) == policy_id + + updated = get_policy_v2(policy_id) + assert updated.description == "updated by test" + + assert update_policy_v2(policy_id, updated) == policy_id + finally: + assert delete_policy(policy_id) is True + + +def test_create_policy_v2_and_bulk_delete(): + policy_id = create_policy_v2(PolicyWebDto(name=_TEST_POLICY_NAME + "-v2")) + assert isinstance(policy_id, int) + assert delete_policies([policy_id]) is True + + +def test_pin_policy(temp_policy): + assert pin_policy(temp_policy, True) == temp_policy + assert get_policy(temp_policy).pinPolicy is True + assert pin_policy(temp_policy, False) == temp_policy + assert get_policy(temp_policy).pinPolicy is False + + +def test_assign_and_remove_projects(temp_policy): + projects = get_tenant_projects() + if not projects: + pytest.skip("No projects available on this tenant") + target = ProjectWebDto(astProjectId=projects[0].astProjectId, name=projects[0].name) + + assert ( + assign_projects_to_policy( + temp_policy, ProjectsInPolicyDto(projects=[target], id=temp_policy) + ) + == temp_policy + ) + assert any( + p.astProjectId == target.astProjectId + for p in get_policy(temp_policy).projects + ) + + assert ( + delete_projects_from_policy( + temp_policy, ProjectsInPolicyDto(projects=[target], id=temp_policy) + ) + is True + ) + assert get_policy(temp_policy).projects == [] + + +# ---- Projects ---- + + +def test_get_tenant_projects(): + projects = get_tenant_projects() + assert isinstance(projects, list) + for p in projects: + assert isinstance(p, ProjectWebDto) + assert p.astProjectId is not None + + +def test_get_projects_tags(): + tags = get_projects_tags() + assert isinstance(tags, list) + + +# ---- Incidents ---- + + +def test_get_tenant_incidents(): + result = get_tenant_incidents() + assert isinstance(result, IncidentsPaginationDto) + assert isinstance(result.filteredIncidentsCount, int) + + +def test_get_tenant_incidents_total_count(): + count = get_tenant_incidents_total_count() + assert isinstance(count, int) + assert count >= 0 + + +def test_get_tenant_incidents_with_pagination(): + result = get_tenant_incidents_with_pagination(limit=5, page=1) + assert isinstance(result, IncidentsPaginationDto) + + +def test_get_tenant_incidents_with_pagination_and_filters(): + result = get_tenant_incidents_with_pagination_and_filters(limit=5, page=1) + assert isinstance(result, IncidentsPaginationDto) + + +def test_get_enhanced_incidents_with_pagination_and_filters(): + try: + result = get_enhanced_incidents_with_pagination_and_filters(limit=5, page=1) + except Exception as e: + _skip_on_client_error(e) + return + assert isinstance(result.filteredIncidentsCount, int) + + +def test_get_incident_results(): + result = get_tenant_incidents() + from CheckmarxPythonSDK.CxOne import get_incident_results + from CheckmarxPythonSDK.CxOne.dto import IncidentResultsDTO + + incident_results = get_incident_results(result.incidents[0].id, limit=5, page=1) + assert isinstance(incident_results, IncidentResultsDTO) + + +# ---- Policy violations / evaluation (require a scan a policy has evaluated) ---- + + +def test_get_policy_violations(completed_scan): + result = get_policy_violations( + project_id=completed_scan.project_id, scan_id=completed_scan.id + ) + assert isinstance(result, PolicyViolationWebDto) + + +def test_get_evaluated_policies_by_scan_id_and_project_id(completed_scan): + try: + result = get_evaluated_policies_by_scan_id_and_project_id( + scan_id=completed_scan.id, ast_project_id=completed_scan.project_id + ) + except Exception as e: + _skip_on_client_error(e) + return + assert result.status in ("COMPLETED", "NONE", "EVALUATING") + + +# Note: delete_data() / delete_data_for_service() are not exercised here -- +# they delete data-retention records across services tenant-wide and are +# not something a test should run against a real tenant.