diff --git a/.github/actions/security-issues/action.yml b/.github/actions/security-issues/action.yml deleted file mode 100644 index 3f8c3f78e..000000000 --- a/.github/actions/security-issues/action.yml +++ /dev/null @@ -1,89 +0,0 @@ -name: 'SIA' -description: 'The Security Issues Action creates github issues for open security issues in the repository' - -inputs: - - command: - description: 'Command for generating a security report' - required: true - - format: - description: 'Input format (e.g. "maven" or "pass-through")' - required: true - - github-token: - description: 'Github Token' - required: true - - project: - description: 'Project the created tickets shall be associated with' - required: false - - -outputs: - - created-issues: - description: 'Information about the created issues and the vulnerabilities in JSONL format' - value: ${{ steps.get-created-issues.outputs.issues }} - -runs: - - using: "composite" - steps: - - - name: Setup Python (${{ inputs.python-version}}) - uses: actions/setup-python@v6 - with: - python-version: 3.11 - - - name: Install Python Toolbox / Security tool - shell: bash - run: | - pip install exasol-toolbox==13.0.0 - - - name: Create Security Issue Report - shell: bash - env: - SECURITY_COMMAND: ${{ inputs.command }} - run: | - bash -euo pipefail -c "$SECURITY_COMMAND" | tee input - - - name: Convert Report To Common Input Format - shell: bash - env: - SECURITY_FORMAT: ${{ inputs.format }} - run: | - tbx security cve convert "$SECURITY_FORMAT" < input | tee cves.jsonl - - - name: Filter Issues - env: - GH_TOKEN: ${{ inputs.github-token }} - shell: bash - run: | - tbx security cve filter github-issues < cves.jsonl 2> filtered.txt | tee issues.jsonl - cat filtered.txt - - - name: Create Issues - env: - GH_TOKEN: ${{ inputs.github-token }} - SECURITY_PROJECT: ${{ inputs.project }} - shell: bash - run: | - tbx security cve create --project "$SECURITY_PROJECT" < issues.jsonl | tee created.jsonl - - - name: Define Output Parameter - id: get-created-issues - shell: bash - run: | - echo 'issues<> "$GITHUB_OUTPUT" - cat created.jsonl >> "$GITHUB_OUTPUT" - echo 'EOF' >> "$GITHUB_OUTPUT" - - - name: Create Report - shell: bash - run: | - echo -e "# Summary\n" >> $GITHUB_STEP_SUMMARY - echo -e "## Created Security Issue\n" >> $GITHUB_STEP_SUMMARY - cat created.jsonl >> $GITHUB_STEP_SUMMARY - echo -e "## Filtered Security Issue\n" >> $GITHUB_STEP_SUMMARY - tail -n +2 filtered.txt | grep . || true >> $GITHUB_STEP_SUMMARY diff --git a/doc/changes/unreleased.md b/doc/changes/unreleased.md index 61e89e88e..cd41674c0 100644 --- a/doc/changes/unreleased.md +++ b/doc/changes/unreleased.md @@ -2,6 +2,16 @@ ## Summary +This release removes the code for creating security issues, as project-keeper +no longer supports it (see exasol/project-keeper#808). This is a breaking change: + +* Removed the GitHub action `security-issues` +* Removed the CLI commands `tbx security`command group + + ## Refactoring * #1009: Fixed Sonar issues in test files +* #987: Removed code creating security issues + * Removed GitHub action `security-issues` + * Removed `tbx security` CLI and module `exasol.toolbox.tools.security` diff --git a/doc/design.rst b/doc/design.rst index a58641039..7fceae1de 100644 --- a/doc/design.rst +++ b/doc/design.rst @@ -189,97 +189,6 @@ _________________ - Description * - python-environment - Sets up an appropriate poetry-based python environment - * - security-issues - - Takes a JSON of known vulnerabilities affecting a repo & creates GitHub Issues - in said repo for any vulnerabilities, which do not yet have a GitHub Issue - -security-issues -^^^^^^^^^^^^^^^ -The `security-issues/action.yml` creates GitHub Issues for known vulnerabilities -for `maven `_ and `pip-audit `_. -The following steps are taken: - -1. Convert a JSON of known vulnerabilities into a common format (`class Issue`) -2. Filter out vulnerabilities which already have an existing GitHub Issue via CVE -3. Create new GitHub Issues -4. Return a JSON of the newly created GitHub Issues - -Input Variants -"""""""""""""" -An input variant would be passed in as a string-encoded JSON. - -`maven` (with `ossindex-audit `_) - -.. code-block:: json - - { - "vulnerable": { - "@:compile": { - "coordinates": "@", - "description": "", - "reference": "", - "vulnerabilities": [ - { - "id": "", - "displayName": "", - "title": "", - "description": "", - "cvssScore": 7.5, - "cvssVector": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", - "cwe": "", - "cve": "", - "reference": "", - "externalReferences": [""], - } - ], - }, - } - } - -`pip-audit` (via `nox -s dependency:audit`) - -.. code-block:: json - - { - "dependencies": [ - { - "name": "", - "version": "", - "vulns": - [ - { - "id": "", - "fix_versions": [""], - "aliases": [""], - "description": "" - } - ] - } - ] - } - -Known Issues -"""""""""""" -The `security-issues/action.yml` assumes that eventually every known vulnerability will -be associated with a singular CVE. - -* This can be problematic as vulnerabilities may be initially reported to different - services and not receive a CVE until a few days later or, in some cases, never. This - could mean that some vulnerabilities are initially missed or, in some cases, - never propagated by our action. -* Additionally, reporting tools like `pip-audit` must link a vulnerability with the - different vulnerability IDs from different reporting services. Typically, this is done - by selecting 1 of the vulnerability IDs as the unique identifier of the vulnerability. - This, as is the case for `pip-audit`, may not be the CVE, so it is possible if the - linked vulnerability IDs were to change (i.e. wrongly linked CVE) that we could end - up with multiple GitHub Issues for the same underlying vulnerability. - - -Known Issues ------------- - -This section documents flaws, sins, and known issues with the current design and/or its current implementation that were either known upfront or surfaced through the course of implementing it. Additionally, it attempts to explain why certain choices were made at the time, so one can better understand whether it may be reasonable to make changes now or in the future. - Passing files as individual arguments on the CLI ++++++++++++++++++++++++++++++++++++++++++++++++ diff --git a/doc/github_actions/github_actions.rst b/doc/github_actions/github_actions.rst index e9139e886..b32fc65ba 100644 --- a/doc/github_actions/github_actions.rst +++ b/doc/github_actions/github_actions.rst @@ -7,4 +7,3 @@ :maxdepth: 2 python_environment - security_issues diff --git a/doc/github_actions/security_issues.rst b/doc/github_actions/security_issues.rst deleted file mode 100644 index ef8a193fb..000000000 --- a/doc/github_actions/security_issues.rst +++ /dev/null @@ -1,115 +0,0 @@ -security-issues -=============== - -Example Usage -------------- - -.. code-block:: yaml - - name: Report Security Issues for Repository - - on: - schedule: - # “Every day at 00:00.” (https://crontab.guru) - - cron: "0 0 * * *" - - jobs: - - report_security_issues: - - name: Report Security Issues - - runs-on: ubuntu-24.04 - - permissions: - issues: write - - steps: - - name: SCM Checkout - uses: actions/checkout@v7 - - - name: Report Security Issues - uses: exasol/python-toolbox/.github/actions/security-issues@v1 - with: - format: "maven" - command: "cat maven-cve-report.json" - github-token: ${{ secrets.GITHUB_TOKEN }} - -Configuration -------------- -This action exposes 3 configuration parameters `command`_, `format`_ and `github-token`_, for details see -the specific sections below. - -command -+++++++ - -Workspace command which shall be executed in order to check the project's dependencies for CVEs. - -.. note:: - - The calling workflow needs to make sure the specified command can be executed in the context of the workflow. - - -format -++++++ - -Specifies converter which needs to be applied on the output of the provided command. -Currently there are only two converters available - -#. maven - - Converts the output of mavens oss plugin into required input format. - - -#. pass-through - - In case the command itself already outputs the expected input format, the format can be specified as code:`pass-through`. - - -Input Format -____________ - -The expect intput format is jsonl (line based json), of the following form: - -.. code-block:: python - - { "cve": "", "cwe": "", "description": "", "coordinates": "", "references": ["", "", ...] } - - -.. attention:: - - The input format may change in the future. Therefore make sure to rather use or contribute a converter for - a specific format rather than outputting this format by your own tooling. - - -github-token -++++++++++++ -The temporary GitHub token of the workflow needs to be passed into the action (:code:`${{ secrets.GITHUB_TOKEN }}`), -in order to enable the action to query and created GitHub issues. - - -project -+++++++ -Title of the GitHub-Project the created issue(s) shall be associated with (default = None). -To determine the title of an project you can use the GitHub-CLI, see example below. - -.. code-block:: shell - - gh project list --owner exasol - - NUMBER TITLE STATE ID - ... - - -Ideas ------ - -.. todo:: - - Add additional details to the :code:`security.Issue` type - - -.. todo:: - - Consider adapting common CVE report format as input, for additional details - `see here `_. diff --git a/exasol/toolbox/skills/exasol-python-toolbox/references/source-routing.md b/exasol/toolbox/skills/exasol-python-toolbox/references/source-routing.md index 3a64b31cc..cb772e350 100644 --- a/exasol/toolbox/skills/exasol-python-toolbox/references/source-routing.md +++ b/exasol/toolbox/skills/exasol-python-toolbox/references/source-routing.md @@ -55,7 +55,6 @@ Do not add new functions under `exasol/toolbox/tools/`. Put reusable code in - `exasol/toolbox/tools/issue.py`: issue template CLI. - `exasol/toolbox/tools/replace_version.py`: version replacement helpers. -- `exasol/toolbox/tools/security.py`: security issue conversion and creation. - `exasol/toolbox/tools/tbx.py`: CLI root. - `exasol/toolbox/tools/template.py`: template list, show, diff, install, and update helpers. diff --git a/exasol/toolbox/tools/security.py b/exasol/toolbox/tools/security.py deleted file mode 100644 index 46aa505fa..000000000 --- a/exasol/toolbox/tools/security.py +++ /dev/null @@ -1,342 +0,0 @@ -"""This module contains security related CLI tools and code""" - -from __future__ import annotations - -import json -import re -import subprocess # nosec: B404 - risk of subprocess is accepted -import sys -from collections.abc import ( - Generator, - Iterable, -) -from dataclasses import ( - asdict, - dataclass, -) -from enum import Enum -from functools import partial -from inspect import cleandoc - -import typer - -stdout = print -stderr = partial(print, file=sys.stderr) - - -# Note: In the long term we may want to adapt the official CVE json schema -# https://github.com/CVEProject/cve-schema/blob/master/schema/v5.0/CVE_JSON_5.0_schema.json -@dataclass(frozen=True) -class Issue: - cve: str - cwe: str - description: str - coordinates: str - references: tuple - - -def _issues(input) -> Generator[Issue]: - lines = (l for l in input if l.strip() != "") - for line in lines: - obj = json.loads(line) - yield Issue(**obj) - - -def _issues_as_json_str(issues): - for issue in issues: - issue = asdict(issue) - yield json.dumps(issue) - - -def gh_security_issues() -> Generator[tuple[str, str]]: - """ - Yields issue-id, cve-id pairs for all (closed, open) issues associated with CVEs - - Return: - A generator which yields tuples of (id,title). - - Raises: - subprocess.CalledProcessError: If the underlying command fails. - """ - # fmt: off - command = [ - "gh", "issue", "list", - "--label", "security", - "--search", "CVE", - "--json", "id,title", - "--limit", "1000", - ] - # fmt: on - try: - result = subprocess.run( - command, check=True, capture_output=True - ) # nosec: B603 - fixed gh CLI command is constructed internally - except FileNotFoundError as ex: - msg = "Command 'gh' not found. Please make sure you have installed the github cli." - raise FileNotFoundError(msg) from ex - except subprocess.CalledProcessError as ex: - stderr(f"{ex}") - raise ex - - cve_pattern = re.compile(r"CVE-\d{4}-\d{4,7}") - issues = json.loads(result.stdout.decode("utf-8")) - issues = ( - (issue["id"], cve_pattern.search(issue["title"]).group()) # type: ignore - for issue in issues - if cve_pattern.search(issue["title"]) - ) - return issues - - -def from_maven(report: str) -> Iterable[Issue]: - # Note: Consider adding warnings if there is the same cve with multiple coordinates - report = json.loads(report) - dependencies = report.get("vulnerable", {}) # type: ignore - for dependency_name, dependency in dependencies.items(): # type: ignore - for v in dependency["vulnerabilities"]: # type: ignore - references = [v["reference"]] + v["externalReferences"] - yield Issue( - cve=v["cve"], - cwe=v["cwe"], - description=v["description"], - coordinates=dependency_name, - references=tuple(references), - ) - - -def identify_pypi_references(references: list[str]) -> tuple[list[str], list[str]]: - # This import must be inside a function scope to prevent errors for - # non-Python projects. - from exasol.toolbox.util.dependencies.audit import VulnerabilitySource - - refs: dict = {k: [] for k in VulnerabilitySource} - for reference in references: - if source := VulnerabilitySource.from_prefix(reference.upper()): - refs[source].append(reference) - return ( - refs[VulnerabilitySource.CVE], - refs[VulnerabilitySource.CWE], - ) - - -def from_pip_audit(report: str) -> Iterable[Issue]: - """ - Transforms the JSON output from `nox -s dependency:audit` into an iterable of - `security.Issue` objects. - - This does not gracefully handle scenarios where: - - a CVE is not initially associated with the vulnerability; however, the assumption - is that such vulnerabilities will later be associated with a CVE. - - the same vulnerability ID (CVE, PYSEC, GHSA, etc.) is present across - multiple coordinates. - - Input as string: - [ - { - "name": "jinja2", - "version": "3.1.5", - "refs": [ - "GHSA-cpwx-vrp4-4pq7", - "CVE-2025-27516" - ], - "description": "An oversight ..." - "coordinates": "jinja2:3.1.5", - "references": [ - "https://github.com/advisories/GHSA-cpwx-vrp4-4pq7", - "https://nvd.nist.gov/vuln/detail/CVE-2025-27516" - ] - } - ] - - - Args: - report: - the JSON output of `nox -s dependency:audit` provided as a str - """ - vulnerabilities = json.loads(report) - - for vulnerability in vulnerabilities: - cves, cwes = identify_pypi_references( - references=vulnerability["refs"], - ) - if cves: - yield Issue( - cve=min(cves), - cwe="None" if not cwes else ", ".join(cwes), - description=vulnerability["description"], - coordinates=vulnerability["coordinates"], - references=tuple(vulnerability["references"]), - ) - - -def security_issue_title(issue: Issue) -> str: - return f"{issue.cve}: {issue.coordinates}" - - -def security_issue_body(issue: Issue) -> str: - def as_markdown_listing(elements: Iterable[str]): - return "\n".join(f"- {element}" for element in elements) - - body = cleandoc(""" - ## Summary - {description} - - CVE: {cve} - CWE: {cwe} - - ## References - {references} - """) - return body.format( - cve=issue.cve, - cwe=issue.cwe, - description=issue.description, - references=as_markdown_listing(issue.references), - ) - - -def create_security_issue(issue: Issue, project: str | None = None) -> tuple[str, str]: - # fmt: off - command = [ - "gh", "issue", "create", - "--label", "security", - "--title", security_issue_title(issue), - "--body", security_issue_body(issue), - ] - if project: - command.extend(['--project', project]) - # fmt: on - try: - result = subprocess.run( - command, check=True, capture_output=True - ) # nosec: B603 - fixed gh CLI command is constructed internally - except FileNotFoundError as ex: - msg = "Command 'gh' not found. Please make sure you have installed the github cli." - raise FileNotFoundError(msg) from ex - except subprocess.CalledProcessError as ex: - stderr(f"{ex}") - raise ex - - std_err = result.stderr.decode("utf-8") - std_out = result.stdout.decode("utf-8") - - return std_err, std_out - - -CLI = typer.Typer() -CVE_CLI = typer.Typer() -CLI.add_typer(CVE_CLI, name="cve", help="Work with CVE's") - - -class Format(str, Enum): - Maven = "maven" - PipAudit = "pip-audit" - - -# pylint: disable=redefined-builtin -@CVE_CLI.command(name="convert") -def convert( - format: Format = typer.Argument(..., help="input format to be converted."), - input_file: typer.FileText = typer.Argument( - default="-", mode="r", help="input file which shall be converted" - ), -) -> None: - """ - Convert a language or tool specific security report into a list of cve's in the jsonl format - - Output: - { "cve": "", "cwe": "", "description": "", "coordinates": "", "references": ["", "", ...] } - """ - - def _maven(infile): - issues = from_maven(infile.read()) - for issue in _issues_as_json_str(issues): - stdout(issue) - raise typer.Exit(code=0) - - def _pip_audit(infile): - issues = from_pip_audit(infile.read()) - for issue in _issues_as_json_str(issues): - stdout(issue) - raise typer.Exit(code=0) - - actions = {Format.Maven: _maven, Format.PipAudit: _pip_audit} - action = actions[format] - action(input_file) - - -class Filter(str, Enum): - GitHubIssues = "github-issues" - PassThrough = "pass-through" - - -# pylint: disable=redefined-builtin -@CVE_CLI.command(name="filter") -def filter( - type: Filter = typer.Argument(help="filter type to apply"), - input_file: typer.FileText = typer.Argument( - default="-", mode="r", help="file containing cve's in the jsonl format" - ), -) -> None: - """ - Filter specific CVE's from the input - - - Input: - { "cve": "", "cwe": "", "description": "", "coordinates": "", "references": ["", "", ...] } - """ - - def _github(infile): - to_be_filtered = {cve for _, cve in gh_security_issues()} - stderr("Filtering:") - for issue in to_be_filtered: - stderr(f"{issue}") - filtered_issues = [ - issue for issue in _issues(infile) if issue.cve not in to_be_filtered - ] - for issue in _issues_as_json_str(filtered_issues): - stdout(issue) - raise typer.Exit(code=0) - - def _pass_through(infile): - for line in infile: - stdout(line) - raise typer.Exit(code=0) - - actions = {Filter.GitHubIssues: _github, Filter.PassThrough: _pass_through} - action = actions[type] - action(input_file) - - -@CVE_CLI.command(name="create") -def create( - input_file: typer.FileText = typer.Argument( - default="-", mode="r", help="file of cve's in the jsonl format" - ), - project: str = typer.Option( - default="", help="Project the created ticket shall be associated with." - ), -) -> None: - """ - Create GitHub issues for CVE's - - Input: - { "cve": "", "cwe": "", "description": "", "coordinates": "", "references": ["", "", ...] } - - Output: - Links to the created issue(s) - """ - for issue in _issues(input_file): - std_err, issue_url = create_security_issue(issue, project) - stderr(std_err) - stdout(format_jsonl(issue_url, issue)) - - -def format_jsonl(issue_url: str, issue: Issue) -> str: - issue_json = asdict(issue) - issue_json["issue_url"] = issue_url.strip() - return json.dumps(issue_json) - - -if __name__ == "__main__": - CLI() diff --git a/exasol/toolbox/tools/tbx.py b/exasol/toolbox/tools/tbx.py index 178759c66..63c1a6902 100644 --- a/exasol/toolbox/tools/tbx.py +++ b/exasol/toolbox/tools/tbx.py @@ -1,12 +1,8 @@ import typer -from exasol.toolbox.tools import ( - issue, - security, -) +from exasol.toolbox.tools import issue CLI = typer.Typer() -CLI.add_typer(security.CLI, name="security", help="Security related helpers") CLI.add_typer(issue.CLI, name="issue", help="Manage issue templates") if __name__ == "__main__": diff --git a/exasol/toolbox/util/dependencies/audit.py b/exasol/toolbox/util/dependencies/audit.py index 8563f61b3..027b0fb18 100644 --- a/exasol/toolbox/util/dependencies/audit.py +++ b/exasol/toolbox/util/dependencies/audit.py @@ -278,7 +278,16 @@ def load_from_pip_audit(cls, working_directory: Path) -> Vulnerabilities: @property def security_issue_dict(self) -> list[PipAuditEntry]: - """Return pip-audit-compatible entries for `tbx security cve convert`.""" + """ + Return pip-audit-compatible entries. + + This was originally the input for `tbx security cve convert`, which has + been removed in https://github.com/exasol/python-toolbox/issues/987. + This is still used in `nox -s dependency:audit`. In this tracking issue, we + will consider whether it should be updated to align with + `vulnerabilities:update` or if it can be removed: + https://github.com/exasol/python-toolbox/issues/1013 + """ return [ vulnerability.security_issue_entry for vulnerability in self.vulnerabilities ] diff --git a/test/conftest.py b/test/conftest.py index bb0c59878..d68cd4d53 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -4,11 +4,6 @@ import pytest -from exasol.toolbox.tools import security -from exasol.toolbox.tools.security import ( - Issue, - _issues_as_json_str, -) from exasol.toolbox.util.dependencies.audit import ( PipAuditEntry, Vulnerability, @@ -94,101 +89,7 @@ def security_issue_entry(self) -> PipAuditEntry: ), } - @property - def security_issue(self) -> Issue: - return Issue( - cve=self.cve_id, - cwe="None", - description=self.description, - coordinates=f"{self.package_name}:{self.version}", - references=( - f"https://nvd.nist.gov/vuln/detail/{self.cve_id}", - f"https://github.com/advisories/{self.vulnerability_id}", - ), - ) - - -class SampleMavenVulnerabilities: - gturri_issue = security.Issue( - cve="CVE-2020-36641", - cwe="CWE-611", - description="A vulnerability classified as problematic was found in " - "gturri aXMLRPC up to 1.12.0. This vulnerability affects " - "the function ResponseParser of the file " - "src/main/java/de/timroes/axmlrpc/ResponseParser.java. The " - "manipulation leads to xml external entity reference. " - "Upgrading to version 1.12.1 is able to address this issue. " - "The patch is identified as " - "ad6615b3ec41353e614f6ea5fdd5b046442a832b. It is " - "recommended to upgrade the affected component. VDB-217450 " - "is the identifier assigned to this vulnerability.\n" - "\n" - "Sonatype's research suggests that this CVE's details " - "differ from those defined at NVD. See " - "https://ossindex.sonatype.org/vulnerability/CVE-2020-36641 " - "for details", - coordinates="fr.turri:aXMLRPC:jar:1.13.0:test", - references=( - "https://ossindex.sonatype.org/vulnerability/CVE-2020-36641?component-type=maven&component-name=fr.turri%2FaXMLRPC&utm_source=ossindex-client&utm_medium=integration&utm_content=1.8.1", - "http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2020-36641", - "https://www.tenable.com/cve/CVE-2020-36641", - ), - ) - github_issue_url = "https://github.com/exasol/a-project/issues/123" - - @property - def report_json(self) -> str: - return json.dumps( - { - "vulnerable": { - "fr.turri:aXMLRPC:jar:1.13.0:test": { - "coordinates": "pkg:maven/fr.turri/aXMLRPC@1.13.0", - "description": "Lightweight Java XML-RPC working also on Android.", - "reference": "https://ossindex.sonatype.org/component/pkg:maven/fr.turri/aXMLRPC@1.13.0?utm_source=ossindex-client&utm_medium=integration&utm_content=1.8.1", - "vulnerabilities": [ - { - "id": self.gturri_issue.cve, - "displayName": self.gturri_issue.cve, - "title": f"[{self.gturri_issue.cve}] {self.gturri_issue.cwe}: Improper Restriction of XML External Entity Reference ('XXE')", - "description": self.gturri_issue.description, - "cvssScore": 9.8, - "cvssVector": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", - "cwe": self.gturri_issue.cwe, - "cve": self.gturri_issue.cve, - "reference": self.gturri_issue.references[0], - "externalReferences": self.gturri_issue.references[1:], - } - ], - }, - }, - } - ) - - @property - def issues(self) -> set[Issue]: - return {self.gturri_issue} - - @property - def issues_json(self) -> str: - convert_to_json = list(_issues_as_json_str(self.issues)) - return convert_to_json[0] - - @property - def gh_security_issues(self): - yield "I_kwDOKj3wMM50puMN", self.gturri_issue.cve - - @property - def create_issues_json(self) -> str: - issues_dict = json.loads(self.issues_json) - issues_dict["issue_url"] = self.github_issue_url - return json.dumps(issues_dict) - @pytest.fixture(scope="session") def sample_vulnerability() -> SampleVulnerability: return SampleVulnerability() - - -@pytest.fixture(scope="session") -def sample_maven_vulnerabilities() -> SampleMavenVulnerabilities: - return SampleMavenVulnerabilities() diff --git a/test/integration/security_issues_test.py b/test/integration/security_issues_test.py deleted file mode 100644 index a8438fde4..000000000 --- a/test/integration/security_issues_test.py +++ /dev/null @@ -1,93 +0,0 @@ -import os -import shutil -import site -import subprocess -from pathlib import Path - -from noxconfig import PROJECT_CONFIG - - -def set_venv_env(monkeypatch, test_path: Path) -> None: - venv_bin = test_path / "venv" / "bin" - monkeypatch.setenv("VIRTUAL_ENV", str(test_path / "venv")) - monkeypatch.setenv("PATH", f"{venv_bin}{os.pathsep}{os.environ['PATH']}") - monkeypatch.setenv("PYTHONPATH", os.pathsep.join(site.getsitepackages())) - - -def test_security_issues_works(tmp_path, monkeypatch): - """ - To ensure that the `tbx security cve` CLI commands work for Java and - other non-Python projects, this test was created which: - - builds a wheel of the python-toolbox - - installs the wheel in a temporary directory - - executes `tbx security cve -- help` to ensure that no errors occur - - This issue primarily arises when one of the modules in `tools` imports something - from `noxconfig`, which is used in the Python projects using the toolbox, but it - is not needed nor used in the non-Python projects. - """ - build_output = subprocess.run(["poetry", "build", "--output", tmp_path]) - assert build_output.returncode == 0 - - venv_output = subprocess.run(["python", "-m", "venv", "venv"], cwd=tmp_path) - assert venv_output.returncode == 0 - - set_venv_env(monkeypatch, tmp_path) - wheel = min(tmp_path.glob("exasol_toolbox-*.whl")) - pip_output = subprocess.run( - ["pip", "install", "--no-deps", str(wheel)], cwd=tmp_path - ) - assert pip_output.returncode == 0 - - tbx_output = subprocess.run(["tbx", "security", "cve", "--help"], cwd=tmp_path) - assert tbx_output.returncode == 0 - - -def test_security_issues_fails_when_imports_noxconfig(tmp_path, monkeypatch): - """ - Reproduces the failure mode where a toolbox runtime module imports - `noxconfig`, which is not available in non-Python projects. - """ - source_root = PROJECT_CONFIG.root_path - project_copy = tmp_path / "python-toolbox-copy" - shutil.copytree( - source_root, - project_copy, - ignore=shutil.ignore_patterns( - ".git", ".venv", "dist", "__pycache__", ".pytest_cache" - ), - ) - - security_py = project_copy / "exasol" / "toolbox" / "tools" / "security.py" - security_text = security_py.read_text() - security_py.write_text( - security_text.replace( - "from __future__ import annotations\n", - "from __future__ import annotations\n\nfrom noxconfig import PROJECT_CONFIG\n", - 1, - ) - ) - - build_output = subprocess.run( - ["poetry", "build", "--output", tmp_path], cwd=project_copy - ) - assert build_output.returncode == 0 - - venv_output = subprocess.run(["python", "-m", "venv", "venv"], cwd=tmp_path) - assert venv_output.returncode == 0 - - set_venv_env(monkeypatch, tmp_path) - wheel = min(tmp_path.glob("exasol_toolbox-*.whl")) - pip_output = subprocess.run( - ["pip", "install", "--no-deps", str(wheel)], cwd=tmp_path - ) - assert pip_output.returncode == 0 - - tbx_output = subprocess.run( - ["tbx", "security", "cve", "--help"], - cwd=tmp_path, - capture_output=True, - text=True, - ) - assert tbx_output.returncode != 0 - assert "No module named 'noxconfig'" in tbx_output.stderr diff --git a/test/integration/tools/security_integration_test.py b/test/integration/tools/security_integration_test.py deleted file mode 100644 index 6532c013e..000000000 --- a/test/integration/tools/security_integration_test.py +++ /dev/null @@ -1,132 +0,0 @@ -from unittest.mock import patch - -from exasol.toolbox.tools.security import ( - CVE_CLI, - Filter, - Format, -) - -JSON_RESULTS = { - "results": [ - { - "code": '555 subprocess.check_call(\n556 config.smv_postbuild_command, cwd=current_cwd, shell=True\n557 )\n558 if config.smv_postbuild_export_pattern != "":\n559 matches = find_matching_files_and_dirs(\n', - "col_offset": 16, - "end_col_offset": 17, - "filename": "exasol/toolbox/sphinx/multiversion/main.py", - "issue_confidence": "HIGH", - "issue_cwe": { - "id": 78, - "link": "https://cwe.mitre.org/data/definitions/78.html", - }, - "issue_severity": "HIGH", - "issue_text": "subprocess call with shell=True identified, security issue.", - "line_number": 556, - "line_range": [555, 556, 557], - "more_info": "https://bandit.readthedocs.io/en/1.7.10/plugins/b602_subprocess_popen_with_shell_equals_true.html", - "test_id": "B602", - "test_name": "subprocess_popen_with_shell_equals_true", - }, - { - "code": "156 )\n157 subprocess.check_call(cmd, cwd=gitroot, stdout=fp)\n158 fp.seek(0)\n", - "col_offset": 8, - "end_col_offset": 58, - "filename": "exasol/toolbox/sphinx/multiversion/git.py", - "issue_confidence": "HIGH", - "issue_cwe": { - "id": 78, - "link": "https://cwe.mitre.org/data/definitions/78.html", - }, - "issue_severity": "LOW", - "issue_text": "subprocess call - check for execution of untrusted input.", - "line_number": 157, - "line_range": [157], - "more_info": "https://bandit.readthedocs.io/en/1.7.10/plugins/b603_subprocess_without_shell_equals_true.html", - "test_id": "B603", - "test_name": "subprocess_without_shell_equals_true", - }, - { - "code": "159 with tarfile.TarFile(fileobj=fp) as tarfp:\n160 tarfp.extractall(dst)\n", - "col_offset": 12, - "end_col_offset": 33, - "filename": "exasol/toolbox/sphinx/multiversion/git.py", - "issue_confidence": "HIGH", - "issue_cwe": { - "id": 22, - "link": "https://cwe.mitre.org/data/definitions/22.html", - }, - "issue_severity": "HIGH", - "issue_text": "tarfile.extractall used without any validation. Please check and discard dangerous members.", - "line_number": 160, - "line_range": [160], - "more_info": "https://bandit.readthedocs.io/en/1.7.10/plugins/b202_tarfile_unsafe_members.html", - "test_id": "B202", - "test_name": "tarfile_unsafe_members", - }, - ] -} - - -class TestConvert: - @staticmethod - def test_with_filled_file(cli_runner, tmp_path, sample_maven_vulnerabilities): - json_path = tmp_path / "input.json" - json_path.write_text(sample_maven_vulnerabilities.report_json) - - result = cli_runner.invoke( - CVE_CLI, ["convert", Format.Maven.value, str(json_path)] - ) - - assert result.exit_code == 0 - assert result.output.strip() == sample_maven_vulnerabilities.issues_json - - -class TestFilter: - @staticmethod - def test_without_existing_github_issue_passes_through( - cli_runner, tmp_path, sample_maven_vulnerabilities - ): - json_path = tmp_path / "input.json" - json_path.write_text(sample_maven_vulnerabilities.issues_json) - - result = cli_runner.invoke( - CVE_CLI, ["filter", Filter.GitHubIssues.value, str(json_path)] - ) - - assert result.exit_code == 0 - assert result.output.strip() == sample_maven_vulnerabilities.issues_json - - @staticmethod - def test_with_existing_github_issue_is_filtered_out( - cli_runner, tmp_path, sample_maven_vulnerabilities - ): - json_path = tmp_path / "input.json" - json_path.write_text(sample_maven_vulnerabilities.issues_json) - - with patch( - "exasol.toolbox.tools.security.gh_security_issues", - return_value=sample_maven_vulnerabilities.gh_security_issues, - ): - result = cli_runner.invoke( - CVE_CLI, ["filter", Filter.GitHubIssues.value, str(json_path)] - ) - - assert result.exit_code == 0 - assert result.output.strip() == "" - - -class TestCreate: - @staticmethod - def test_works_as_expected_with_mocked_create_security_issue( - cli_runner, tmp_path, sample_maven_vulnerabilities - ): - json_path = tmp_path / "input.json" - json_path.write_text(sample_maven_vulnerabilities.issues_json) - - with patch( - "exasol.toolbox.tools.security.create_security_issue", - return_value=("", sample_maven_vulnerabilities.github_issue_url), - ): - result = cli_runner.invoke(CVE_CLI, ["create", str(json_path)]) - - assert result.exit_code == 0 - assert result.output.strip() == sample_maven_vulnerabilities.create_issues_json diff --git a/test/unit/security_test.py b/test/unit/security_test.py index c9ae49aa5..e69de29bb 100644 --- a/test/unit/security_test.py +++ b/test/unit/security_test.py @@ -1,315 +0,0 @@ -import json -import os -import subprocess -from contextlib import contextmanager -from inspect import cleandoc -from unittest import mock - -import pytest - -from exasol.toolbox.tools import security - - -@contextmanager -def empty_path(): - """Make sure the PATH environment variable is empty.""" - old_path = os.environ["PATH"] - os.environ["PATH"] = "" - yield - os.environ["PATH"] = old_path - - -class TestCreateSecurityIssue: - @pytest.mark.parametrize( - "expected,issue", - [ - ( - "CVE-2023-39410: pkg:maven/fr.turri/aXMLRPC@1.13.0", - security.Issue( - cve="CVE-2023-39410", - cwe="None", - description="None", - coordinates="pkg:maven/fr.turri/aXMLRPC@1.13.0", - references=tuple(), - ), - ) - ], - ) - def test_security_issue_title_template(self, expected, issue): - actual = security.security_issue_title(issue) - assert actual == expected - - @pytest.mark.parametrize( - "expected,issue", - [ - ( - cleandoc(""" - ## Summary - Random Multiline - Description - ;) - - CVE: CVE-2023-39410 - CWE: CWE-XYZ - - ## References - - https://www.example.com - - https://www.foobar.com - """), - security.Issue( - cve="CVE-2023-39410", - cwe="CWE-XYZ", - description="Random Multiline\nDescription\n;)", - coordinates="pkg:maven/fr.turri/aXMLRPC@1.13.0", - references=("https://www.example.com", "https://www.foobar.com"), - ), - ) - ], - ) - def test_security_issue_body_template(self, expected, issue): - actual = security.security_issue_body(issue) - assert actual == expected - - def test_gh_cli_is_not_available(self): - with empty_path(): - with pytest.raises(FileNotFoundError) as exec_info: - set(security.gh_security_issues()) - - actual = f"{exec_info.value}" - expected = "Command 'gh' not found. Please make sure you have installed the github cli." - - assert actual == expected - - @mock.patch( - "subprocess.run", - side_effect=subprocess.CalledProcessError( - returncode=1, - cmd=[ - "gh", - "issue", - "create", - "--label", - "security", - "--title", - "", - "--body", - "<body>", - ], - ), - ) - def test_gh_cli_failed(self, _): - with pytest.raises(subprocess.CalledProcessError) as exec_info: - set(security.gh_security_issues()) - - actual = f"{exec_info.value}" - expected = str( - subprocess.CalledProcessError( - returncode=1, - cmd=[ - "gh", - "issue", - "create", - "--label", - "security", - "--title", - "<title>", - "--body", - "<body>", - ], - ) - ) - assert actual == expected - - @mock.patch("subprocess.run") - def test_query_gh_security_issues(self, run_mock): - result = mock.MagicMock(subprocess.CompletedProcess) - result.returncode = 0 - result.stdout = b"https://github.com/exasol/some-project/issues/16" - result.stderr = b"Creating Issue" - run_mock.return_value = result - - issues = security.Issue( - cve="CVE-2023-39410", - cwe="None", - description="None", - coordinates="pkg:maven/fr.turri/aXMLRPC@1.13.0", - references=tuple(), - ) - - expected = ( - "Creating Issue", - "https://github.com/exasol/some-project/issues/16", - ) - actual = security.create_security_issue(issues) - assert actual == expected - - -class TestGhSecurityIssues: - def test_gh_cli_is_not_available(self): - with empty_path(): - with pytest.raises(FileNotFoundError) as exec_info: - set(security.gh_security_issues()) - - actual = f"{exec_info.value}" - expected = "Command 'gh' not found. Please make sure you have installed the github cli." - - assert actual == expected - - @mock.patch( - "subprocess.run", - side_effect=subprocess.CalledProcessError( - returncode=1, - cmd=[ - "gh", - "issue", - "list", - "--label", - "security", - "--search", - "CVE", - "--json", - "id,title", - "1000", - ], - ), - ) - def test_gh_cli_failed(self, _): - with pytest.raises(subprocess.CalledProcessError) as exec_info: - set(security.gh_security_issues()) - - actual = f"{exec_info.value}" - expected = str( - subprocess.CalledProcessError( - returncode=1, - cmd=[ - "gh", - "issue", - "list", - "--label", - "security", - "--search", - "CVE", - "--json", - "id,title", - "1000", - ], - ) - ) - assert actual == expected - - @mock.patch("subprocess.run") - def test_query_gh_security_issues(self, run_mock): - result = mock.MagicMock(subprocess.CompletedProcess) - result.returncode = 0 - result.stdout = ( - b'[{"id":"I_kwDOIRnUks5zutba","title":"\xf0\x9f\x90\x9e CVE-2023-41105: Fix build scripts "},' - b'{"id":"I_kwDOIRnUks5clFdR","title":"\xf0\x9f\x90\x9e CVE-2023-40217: Version check issues"}]\n' - ) - run_mock.return_value = result - - expected = { - ("I_kwDOIRnUks5zutba", "CVE-2023-41105"), - ("I_kwDOIRnUks5clFdR", "CVE-2023-40217"), - } - actual = set(security.gh_security_issues()) - assert actual == expected - - -class TestConvertMavenInput: - @staticmethod - def test_with_filled_input(sample_maven_vulnerabilities): - actual = set(security.from_maven(sample_maven_vulnerabilities.report_json)) - assert actual == sample_maven_vulnerabilities.issues - - @staticmethod - def test_with_empty_input(): - actual = set(security.from_maven("{}")) - assert actual == set() - - -def test_format_jsonl(): - issue = security.Issue( - coordinates="coordinates", - cve="cve", - cwe="cwe", - description="description", - references=(), - ) - expected = json.dumps( - { - "cve": "cve", - "cwe": "cwe", - "description": "description", - "coordinates": "coordinates", - "references": [], - "issue_url": "my_issue_url", - } - ) - actual = security.format_jsonl("my_issue_url", issue) - assert actual == expected - - -def test_format_jsonl_removes_newline(): - issue = security.Issue( - coordinates="coordinates", - cve="cve", - cwe="cwe", - description="description", - references=(), - ) - expected = json.dumps( - { - "cve": "cve", - "cwe": "cwe", - "description": "description", - "coordinates": "coordinates", - "references": [], - "issue_url": "my_issue_url", - } - ) - actual = security.format_jsonl("my_issue_url\n", issue) - assert actual == expected - - -@pytest.mark.parametrize( - "reference, expected", - [ - pytest.param( - "CVE-2025-27516", - (["CVE-2025-27516"], []), - id="CVE_identified_with_link", - ), - pytest.param( - "CWE-611", - ([], ["CWE-611"]), - id="CWE_identified_with_link", - ), - pytest.param( - "GHSA-cpwx-vrp4-4pq7", - ([], []), - id="GHSA_link", - ), - pytest.param( - "PYSEC-2025-9", - ([], []), - id="PYSEC_link", - ), - ], -) -def test_identify_pypi_references(reference: str, expected): - actual = security.identify_pypi_references([reference]) - assert actual == expected - - -class TestFromPipAudit: - @staticmethod - def test_no_vulnerability_returns_empty_list(): - actual = set(security.from_pip_audit("{}")) - assert actual == set() - - @staticmethod - def test_convert_vulnerability_to_issue(sample_vulnerability): - actual = next( - security.from_pip_audit(sample_vulnerability.nox_dependencies_audit) - ) - assert actual == sample_vulnerability.security_issue