diff --git a/cyclonedx_py/_internal/utils/poetry.py b/cyclonedx_py/_internal/utils/poetry.py index 78adbb90..aba9a62c 100644 --- a/cyclonedx_py/_internal/utils/poetry.py +++ b/cyclonedx_py/_internal/utils/poetry.py @@ -37,6 +37,7 @@ if TYPE_CHECKING: from cyclonedx.model.component import ComponentType + from cyclonedx.model.license import License def poetry2extrefs(poetry: dict[str, Any]) -> Generator['ExternalReference', None, None]: @@ -62,6 +63,17 @@ def poetry2extrefs(poetry: dict[str, Any]) -> Generator['ExternalReference', Non pass +def poetry2licenses(poetry: dict[str, Any], lfac: 'LicenseFactory') -> Generator['License', None, None]: + lack = LicenseAcknowledgement.DECLARED + if 'classifiers' in poetry: + yield from classifiers2licenses(poetry['classifiers'], lfac, lack) + if 'license' in poetry: + # per spec(https://python-poetry.org/docs/pyproject#license): + # the `license` is intended to be the name of a license, not the license text itself. + yield lfac.make_from_string(poetry['license'], + license_acknowledgement=lack) + + def poetry2component(poetry: dict[str, Any], *, ctype: 'ComponentType') -> 'Component': component = Component( type=ctype, @@ -72,15 +84,7 @@ def poetry2component(poetry: dict[str, Any], *, ctype: 'ComponentType') -> 'Comp # TODO add more properties according to spec ) # region licenses - lfac = LicenseFactory() - lack = LicenseAcknowledgement.DECLARED - if 'classifiers' in poetry: - component.licenses.update(classifiers2licenses(poetry['classifiers'], lfac, lack)) - if 'license' in poetry: - # per spec(https://python-poetry.org/docs/pyproject#license): - # the `license` is intended to be the name of a license, not the license text itself. - component.licenses.add(lfac.make_from_string(poetry['license'], - license_acknowledgement=lack)) + component.licenses.update(poetry2licenses(poetry, LicenseFactory())) licenses_fixup(component) # endregion licenses return component @@ -97,7 +101,9 @@ def poetry2dependencies(poetry: dict[str, Any]) -> Generator['Requirement', None ) ): req = Requirement(name) - if isinstance(spec, dict) and 'extras' in spec: - req.extras = set(spec['extras']) + specs = spec if isinstance(spec, list) else (spec,) + req.extras = set(chain.from_iterable( + s.get('extras', ()) for s in specs if isinstance(s, dict) + )) # add other optional properties as soon as they were needed yield req diff --git a/cyclonedx_py/_internal/utils/pyproject.py b/cyclonedx_py/_internal/utils/pyproject.py index 127c0619..b4df5170 100644 --- a/cyclonedx_py/_internal/utils/pyproject.py +++ b/cyclonedx_py/_internal/utils/pyproject.py @@ -31,7 +31,7 @@ project2licenses as pep621_project2licenses, ) from .pep639 import project2licenses as pep639_project2licenses -from .poetry import poetry2component, poetry2dependencies +from .poetry import poetry2component, poetry2dependencies, poetry2extrefs, poetry2licenses from .toml import toml_loads if TYPE_CHECKING: # pragma: no cover @@ -41,29 +41,57 @@ from packaging.requirements import Requirement +def _merge_poetry_into_component(component: 'Component', + project: dict[str, Any], + poetry: dict[str, Any], + lfac: 'LicenseFactory', + has_pep639_licenses: bool) -> None: + if component.version is None: + component.version = poetry.get('version') + if component.description is None: + component.description = poetry.get('description') + + existing_extrefs = {(er.type, er.url) for er in component.external_references} + for er in poetry2extrefs(poetry): + if (er.type, er.url) not in existing_extrefs: + component.external_references.add(er) + existing_extrefs.add((er.type, er.url)) + + if not has_pep639_licenses: + fallback_keys = ('license', 'classifiers') + poetry_fallback = {k: poetry[k] for k in fallback_keys if k not in project and k in poetry} + component.licenses.update(poetry2licenses(poetry_fallback, lfac)) + + def pyproject2component(data: dict[str, Any], *, ctype: 'ComponentType', fpath: str, gather_license_texts: bool, logger: 'Logger' ) -> 'Component': - tool = data.get('tool', {}) - if poetry := tool.get('poetry'): - return poetry2component(poetry, ctype=ctype) - if project := data.get('project'): + project: dict[str, Any] = data.get('project', {}) + poetry: dict[str, Any] = data.get('tool', {}).get('poetry', {}) + if project: + if 'name' not in project and 'name' in poetry: + project = {**project, 'name': poetry['name']} component = pep621_project2component(project, ctype=ctype) # region licenses lfac = LicenseFactory() component.licenses.update(pep639_project2licenses(project, lfac, gather_license_texts, fpath=fpath, logger=logger)) - if len(component.licenses) == 0: + has_pep639_licenses = len(component.licenses) > 0 + if not has_pep639_licenses: # According to PEP 639 spec, if licenses are declared in the "new" style, # all other license declarations MUST be ignored. # https://peps.python.org/pep-0639/#converting-legacy-metadata component.licenses.update(pep621_project2licenses(project, lfac, gather_license_texts, fpath=fpath)) + if poetry: + _merge_poetry_into_component(component, project, poetry, lfac, has_pep639_licenses) licenses_fixup(component) # endregion licenses return component + if poetry: + return poetry2component(poetry, ctype=ctype) raise ValueError('Unable to build component from pyproject: pyproject.toml is not PEP 621-compliant') @@ -90,9 +118,7 @@ def pyproject_file2component(pyproject_file: str, *, def pyproject2dependencies(data: dict[str, Any]) -> Iterator['Requirement']: - tool = data.get('tool', {}) - if 'poetry' in tool: - return poetry2dependencies(tool['poetry']) - if 'project' in data: - return pep621_project2dependencies(data['project']) - return iter(()) + if project := data.get('project'): + yield from pep621_project2dependencies(project) + if poetry := data.get('tool', {}).get('poetry'): + yield from poetry2dependencies(poetry) diff --git a/tests/integration/test_cli_requirements.py b/tests/integration/test_cli_requirements.py index f47b38d7..62ff2e9d 100644 --- a/tests/integration/test_cli_requirements.py +++ b/tests/integration/test_cli_requirements.py @@ -20,7 +20,9 @@ import random from collections.abc import Generator from glob import glob +from json import loads as json_loads from os.path import basename, join, splitext +from tempfile import TemporaryDirectory from typing import Any from unittest import TestCase @@ -134,6 +136,44 @@ def test_with_index_auth(self, infile: str, sv: SchemaVersion, of: OutputFormat) self.assertEqual(0, res, err) self.assertEqualSnapshot(out, 'index_auth', infile, sv, of) + def test_with_hybrid_poetry_v2_pyproject(self) -> None: + pyproject_toml = """\ +[project] +name = "hybrid-poetry-v2-app" +dynamic = ["version"] +description = "Hybrid Poetry v2 manifest" +license = "Apache-2.0" + +[tool.poetry] +version = "1.4.0" +repository = "https://github.com/example/hybrid-poetry-v2-app" + +[tool.poetry.group.dev.dependencies] +ddt = "^1.7.2" +""" + with TemporaryDirectory() as tmpdir: + pyp = join(tmpdir, 'pyproject.toml') + req = join(tmpdir, 'requirements.txt') + with open(pyp, 'w', encoding='utf8') as f: + f.write(pyproject_toml) + with open(req, 'w', encoding='utf8') as f: + f.write('toml==0.10.2\n') + res, out, err = run_cli( + 'requirements', + '-vvv', + '--sv', '1.6', + '--of', OutputFormat.JSON.name, + '--output-reproducible', + '--pyproject', pyp, + '-o=-', + req) + self.assertEqual(0, res, err) + bom = json_loads(out) + root = bom['metadata']['component'] + self.assertEqual('hybrid-poetry-v2-app', root['name']) + self.assertEqual('1.4.0', root['version']) + self.assertEqual([{'license': {'acknowledgement': 'declared', 'id': 'Apache-2.0'}}], root['licenses']) + def assertEqualSnapshot(self, actual: str, # noqa:N802 purpose: str, reqfile: str, diff --git a/tests/unit/test_utils_pyproject.py b/tests/unit/test_utils_pyproject.py new file mode 100644 index 00000000..af74ad38 --- /dev/null +++ b/tests/unit/test_utils_pyproject.py @@ -0,0 +1,220 @@ +# This file is part of CycloneDX Python +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) OWASP Foundation. All Rights Reserved. + + +import logging +from typing import Any +from unittest import TestCase + +from cyclonedx.model import ExternalReferenceType +from cyclonedx.model.component import ComponentType +from cyclonedx.model.license import DisjunctiveLicense + +from cyclonedx_py._internal.utils.pyproject import pyproject2component, pyproject2dependencies + + +class TestUtilsPyproject(TestCase): + + def setUp(self) -> None: + self._logger = logging.getLogger('test_utils_pyproject') + + def test_pure_pep621_with_pep639_license(self) -> None: + data: dict[str, Any] = { + 'project': { + 'name': 'pep621-pkg', + 'version': '2.0.0', + 'description': 'Pure PEP 621 package', + 'license': 'Apache-2.0', + 'urls': { + 'Homepage': 'https://example.org/pep621-pkg', + }, + }, + } + c = pyproject2component( + data, + ctype=ComponentType.APPLICATION, + fpath='pyproject.toml', + gather_license_texts=False, + logger=self._logger, + ) + self.assertEqual('pep621-pkg', c.name) + self.assertEqual('2.0.0', c.version) + self.assertEqual('Pure PEP 621 package', c.description) + licenses = tuple(c.licenses) + self.assertEqual(1, len(licenses)) + self.assertIsInstance(licenses[0], DisjunctiveLicense) + assert isinstance(licenses[0], DisjunctiveLicense) + self.assertEqual('Apache-2.0', licenses[0].id) + extrefs = {(er.type, er.url.uri) for er in c.external_references} + self.assertEqual({(ExternalReferenceType.WEBSITE, 'https://example.org/pep621-pkg')}, extrefs) + + def test_hybrid_project_and_poetry_merges_dynamic_and_deduplicates_urls(self) -> None: + data: dict[str, Any] = { + 'project': { + 'name': 'hybrid-pkg', + 'dynamic': ['version', 'description', 'license'], + 'urls': { + 'Homepage': 'https://example.org/hybrid', + }, + }, + 'tool': { + 'poetry': { + 'version': '1.2.3', + 'description': 'Fallback description from poetry', + 'license': 'MIT', + 'homepage': 'https://example.org/hybrid', + 'repository': 'https://github.com/example/hybrid', + }, + }, + } + c = pyproject2component( + data, + ctype=ComponentType.LIBRARY, + fpath='pyproject.toml', + gather_license_texts=False, + logger=self._logger, + ) + self.assertEqual('hybrid-pkg', c.name) + self.assertEqual('1.2.3', c.version) + self.assertEqual('Fallback description from poetry', c.description) + licenses = tuple(c.licenses) + self.assertEqual(1, len(licenses)) + assert isinstance(licenses[0], DisjunctiveLicense) + self.assertEqual('MIT', licenses[0].id) + extrefs = [(er.type, er.url.uri) for er in c.external_references] + self.assertEqual(2, len(extrefs)) + self.assertIn((ExternalReferenceType.WEBSITE, 'https://example.org/hybrid'), extrefs) + self.assertIn((ExternalReferenceType.VCS, 'https://github.com/example/hybrid'), extrefs) + + def test_hybrid_pep639_license_ignores_legacy_poetry_license(self) -> None: + data: dict[str, Any] = { + 'project': { + 'name': 'pep639-hybrid', + 'version': '1.0.0', + 'license': 'MIT', + }, + 'tool': { + 'poetry': { + 'license': 'Apache-2.0', + 'classifiers': ['License :: OSI Approved :: BSD License'], + }, + }, + } + c = pyproject2component( + data, + ctype=ComponentType.APPLICATION, + fpath='pyproject.toml', + gather_license_texts=False, + logger=self._logger, + ) + licenses = tuple(c.licenses) + self.assertEqual(1, len(licenses)) + assert isinstance(licenses[0], DisjunctiveLicense) + self.assertEqual('MIT', licenses[0].id) + + def test_hybrid_pep621_license_does_not_pull_poetry_license(self) -> None: + data: dict[str, Any] = { + 'project': { + 'name': 'pep621-hybrid', + 'version': '1.0.0', + 'license': {'text': 'MIT'}, + }, + 'tool': { + 'poetry': { + 'license': 'Apache-2.0', + }, + }, + } + c = pyproject2component( + data, + ctype=ComponentType.APPLICATION, + fpath='pyproject.toml', + gather_license_texts=False, + logger=self._logger, + ) + licenses = tuple(c.licenses) + self.assertEqual(1, len(licenses)) + assert isinstance(licenses[0], DisjunctiveLicense) + self.assertEqual('MIT', licenses[0].id) + + def test_legacy_poetry_only_still_supported(self) -> None: + data: dict[str, Any] = { + 'tool': { + 'poetry': { + 'name': 'legacy-pkg', + 'version': '0.1.0', + 'license': 'ISC', + }, + }, + } + c = pyproject2component( + data, + ctype=ComponentType.APPLICATION, + fpath='pyproject.toml', + gather_license_texts=False, + logger=self._logger, + ) + self.assertEqual('legacy-pkg', c.name) + self.assertEqual('0.1.0', c.version) + + def test_invalid_empty_pyproject_raises_value_error(self) -> None: + with self.assertRaisesRegex(ValueError, 'Unable to build component from pyproject'): + pyproject2component( + {}, + ctype=ComponentType.APPLICATION, + fpath='pyproject.toml', + gather_license_texts=False, + logger=self._logger, + ) + + def test_pyproject2dependencies_combines_project_and_poetry(self) -> None: + data: dict[str, Any] = { + 'project': { + 'name': 'hybrid-deps', + 'dependencies': ['requests[security] (>=2.28,<3)'], + 'optional-dependencies': { + 'extra-a': ['tomli (>=2.0)'], + }, + }, + 'tool': { + 'poetry': { + 'dependencies': { + 'multi': [ + {'version': '>=1', 'extras': ['foo']}, + {'version': '<1', 'extras': ['bar']}, + ], + }, + 'group': { + 'dev': { + 'dependencies': { + 'ddt': '^1.7.2', + }, + }, + }, + }, + }, + } + reqs = {req.name: req.extras for req in pyproject2dependencies(data)} + self.assertEqual({ + 'requests': {'security'}, + 'tomli': set(), + 'multi': {'foo', 'bar'}, + 'ddt': set(), + }, reqs) + + def test_pyproject2dependencies_empty_returns_empty(self) -> None: + self.assertEqual([], list(pyproject2dependencies({})))