Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 16 additions & 10 deletions cyclonedx_py/_internal/poetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
class _LockEntry:
name: str
component: Component
dependencies: dict[str, 'T_NameDict'] # keys MUST go through `normalize_packagename()`
dependencies: dict[str, list['T_NameDict']] # keys MUST go through `normalize_packagename()`
extras: dict[str, list[str]] # keys MUST go through `normalize_packagename()`
added2bom: bool

Expand Down Expand Up @@ -295,11 +295,7 @@ def _make_bom(self, project: 'T_NameDict', locker: 'T_NameDict',
for group_name in use_groups:
for dep_name, dep_specs in po_cfg['group'][group_name].get('dependencies', {}).items():
dep_name = normalize_packagename(dep_name)
if not isinstance(dep_specs, list):
if isinstance(dep_specs, dict):
dep_specs = [dep_specs]
else:
dep_specs = [{'version': dep_specs}]
dep_specs = self._normalize_dep_specs(dep_specs)
self._logger.debug('root-component depends on %s', dep_name)
if dep_name == 'python':
continue # skip python constraint
Expand All @@ -323,6 +319,15 @@ def _make_bom(self, project: 'T_NameDict', locker: 'T_NameDict',

return bom

@staticmethod
def _normalize_dep_specs(dep_specs: Any) -> list['T_NameDict']:
if isinstance(dep_specs, list):
return [
ds if isinstance(ds, dict) else {'version': ds}
for ds in dep_specs
]
return [dep_specs if isinstance(dep_specs, dict) else {'version': dep_specs}]

def __add_dep(self, bom: 'Bom', lock_entry: _LockEntry, use_extras: Iterable[str], lock_data: 'T_LockData') -> None:
if lock_entry.added2bom:
self._logger.debug('existing component: %r', lock_entry.component)
Expand All @@ -334,20 +339,21 @@ def __add_dep(self, bom: 'Bom', lock_entry: _LockEntry, use_extras: Iterable[str
bom.components.add(lock_entry.component)
lock_entry_dep = Dependency(lock_entry.component.bom_ref)
bom.dependencies.add(lock_entry_dep)
for dep_name, dep_spec in lock_entry.dependencies.items():
for dep_name, dep_specs in lock_entry.dependencies.items():
# Actually, a best-path should be calculated here, like it is done by Poetry itself...
# This would require heavy computation and might cause false-negatives or insufficient picks.
# Instead, we pick all dependencies, just to be on the safe side.
dep_lock_entries = lock_data.get(dep_name)
if dep_lock_entries is None:
self._logger.warning('skip unlocked component: %s', dep_name)
continue
if dep_spec.get('optional'):
if bool(dep_specs) and all(ds.get('optional') for ds in dep_specs):
# optionals are not installed, per default. they may be added via `use_extras` later.
continue
dep_extras = tuple(chain.from_iterable(ds.get('extras', ()) for ds in dep_specs))
for dep_lock_entry in dep_lock_entries:
lock_entry_dep.dependencies.add(Dependency(dep_lock_entry.component.bom_ref))
self.__add_dep(bom, dep_lock_entry, dep_spec.get('extras', ()), lock_data)
self.__add_dep(bom, dep_lock_entry, dep_extras, lock_data)
if use_extras:
use_extras = frozenset(map(normalize_packagename, use_extras))
lock_entry.component.properties.update(
Expand Down Expand Up @@ -386,7 +392,7 @@ def _parse_lock(self, locker: 'T_NameDict') -> Generator[_LockEntry, None, None]
name=normalize_packagename(package['name']),
component=self.__make_component4lock(package),
dependencies={
normalize_packagename(dn): ds if isinstance(ds, dict) else {'version': ds}
normalize_packagename(dn): self._normalize_dep_specs(ds)
for dn, ds in package.get('dependencies', {}).items()
},
extras={
Expand Down
263 changes: 263 additions & 0 deletions tests/unit/test_poetry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,263 @@
# 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.


from json import loads as json_loads
from os.path import join
from tempfile import TemporaryDirectory
from textwrap import dedent
from typing import Any
from unittest import TestCase

from tests.integration import run_cli


class TestPoetryMultiConstraintLockDependencies(TestCase):

@staticmethod
def _run_poetry_json(pyproject_toml: str, poetry_lock: str, *extra_args: str) -> dict[str, Any]:
with TemporaryDirectory() as tmpdir:
with open(join(tmpdir, 'pyproject.toml'), 'w', encoding='utf8') as f:
f.write(dedent(pyproject_toml))
with open(join(tmpdir, 'poetry.lock'), 'w', encoding='utf8') as f:
f.write(dedent(poetry_lock))
res, out, err = run_cli(
'poetry',
*extra_args,
'--of', 'JSON',
'--output-reproducible',
'-o=-',
tmpdir,
)
if res != 0:
raise AssertionError(f'CLI failed ({res}): {err}')
result: dict[str, Any] = json_loads(out)
return result

def test_multi_constraint_all_optional_excluded_when_extra_unused(self) -> None:
pyproject_toml = """\
[tool.poetry]
name = "demo"
version = "0.1.0"
description = ""
authors = ["Example <[email protected]>"]

[tool.poetry.dependencies]
python = "^3.11"
ray = "2.42.1"

[tool.poetry.group.dev.dependencies]
ray = { version = "2.42.1", extras = ["serve"] }
"""
poetry_lock = """\
[[package]]
name = "ray"
version = "2.42.1"
description = ""
optional = false
python-versions = ">=3.9"
groups = ["main", "dev"]
files = []

[package.dependencies]
click = ">=7.0"
py-spy = [
{version = ">=0.2.0", optional = true, markers = 'python_version < "3.12" and extra == "serve"'},
{version = ">=0.4.0", optional = true, markers = 'python_version >= "3.12" and extra == "serve"'},
]

[package.extras]
serve = [
'py-spy (>=0.2.0) ; python_version < "3.12"',
'py-spy (>=0.4.0) ; python_version >= "3.12"',
]

[[package]]
name = "click"
version = "8.1.8"
description = ""
optional = false
python-versions = ">=3.7"
groups = ["main", "dev"]
files = []

[[package]]
name = "py-spy"
version = "0.4.0"
description = ""
optional = true
python-versions = ">=3.8"
groups = ["dev"]
files = []

[metadata]
lock-version = "2.1"
python-versions = "^3.11"
content-hash = "0000000000000000000000000000000000000000000000000000000000000000"
"""
bom_main = self._run_poetry_json(pyproject_toml, poetry_lock, '--only', 'main')
comp_refs_main = {c['bom-ref'] for c in bom_main.get('components', ())}
self.assertEqual({'[email protected]', '[email protected]'}, comp_refs_main)
ray_deps_main = next(d for d in bom_main['dependencies'] if d['ref'] == '[email protected]')
self.assertEqual(['[email protected]'], ray_deps_main.get('dependsOn', []))

bom_all = self._run_poetry_json(pyproject_toml, poetry_lock)
comp_refs_all = {c['bom-ref'] for c in bom_all.get('components', ())}
self.assertEqual({'[email protected]', '[email protected]', '[email protected]'}, comp_refs_all)
ray_deps_all = next(d for d in bom_all['dependencies'] if d['ref'] == '[email protected]')
self.assertEqual({'[email protected]', '[email protected]'}, set(ray_deps_all.get('dependsOn', [])))

def test_multi_constraint_mixed_optional_and_required_included(self) -> None:
pyproject_toml = """\
[tool.poetry]
name = "demo"
version = "0.1.0"
description = ""
authors = ["Example <[email protected]>"]

[tool.poetry.dependencies]
python = "^3.11"
parent-pkg = "1.0.0"
"""
poetry_lock = """\
[[package]]
name = "parent-pkg"
version = "1.0.0"
description = ""
optional = false
python-versions = ">=3.9"
groups = ["main"]
files = []

[package.dependencies]
helper-pkg = [
{version = ">=1.0", optional = true, markers = 'python_version < "3.12" and extra == "fast"'},
{version = ">=2.0", markers = 'python_version >= "3.12"'},
]

[[package]]
name = "helper-pkg"
version = "2.0.0"
description = ""
optional = false
python-versions = ">=3.9"
groups = ["main"]
files = []

[metadata]
lock-version = "2.1"
python-versions = "^3.11"
content-hash = "0000000000000000000000000000000000000000000000000000000000000000"
"""
bom = self._run_poetry_json(pyproject_toml, poetry_lock)
comp_refs = {c['bom-ref'] for c in bom.get('components', ())}
self.assertEqual({'[email protected]', '[email protected]'}, comp_refs)

def test_multi_constraint_extras_propagated_transitively(self) -> None:
pyproject_toml = """\
[tool.poetry]
name = "demo"
version = "0.1.0"
description = ""
authors = ["Example <[email protected]>"]

[tool.poetry.dependencies]
python = "^3.11"
app-lib = "^1.0.0"
"""
poetry_lock = """\
[[package]]
name = "app-lib"
version = "1.0.0"
description = ""
optional = false
python-versions = ">=3.10"
groups = ["main"]
files = []

[package.dependencies]
httpx = [
{version = ">=0.26", extras = ["http2"], markers = 'python_version < "3.12"'},
{version = ">=0.27", extras = ["http2", "socks"], markers = 'python_version >= "3.12"'},
]

[[package]]
name = "httpx"
version = "0.26.0"
description = ""
optional = false
python-versions = ">=3.8"
groups = ["main"]
markers = 'python_version < "3.12"'
files = []

[package.extras]
http2 = ["h2 (>=4.0)"]
socks = ["socksio (>=1.0)"]

[[package]]
name = "httpx"
version = "0.27.0"
description = ""
optional = false
python-versions = ">=3.8"
groups = ["main"]
markers = 'python_version >= "3.12"'
files = []

[package.extras]
http2 = ["h2 (>=4.0)"]
socks = ["socksio (>=1.0)"]

[[package]]
name = "h2"
version = "4.1.0"
description = ""
optional = true
python-versions = ">=3.8"
groups = ["main"]
files = []

[[package]]
name = "socksio"
version = "1.0.0"
description = ""
optional = true
python-versions = ">=3.8"
groups = ["main"]
files = []

[metadata]
lock-version = "2.1"
python-versions = "^3.11"
content-hash = "0000000000000000000000000000000000000000000000000000000000000000"
"""
bom = self._run_poetry_json(pyproject_toml, poetry_lock)
comp_refs = {c['bom-ref'] for c in bom.get('components', ())}
self.assertEqual(
{'[email protected]', '[email protected]', '[email protected]#1', '[email protected]', '[email protected]'},
comp_refs,
)
for httpx_ref in ('[email protected]', '[email protected]#1'):
httpx_comp = next(c for c in bom['components'] if c['bom-ref'] == httpx_ref)
extra_props = {
p['value'] for p in httpx_comp.get('properties', ())
if p['name'] == 'cdx:python:package:required-extra'
}
self.assertEqual({'http2', 'socks'}, extra_props)
httpx_deps = next(d for d in bom['dependencies'] if d['ref'] == httpx_ref)
self.assertEqual({'[email protected]', '[email protected]'}, set(httpx_deps.get('dependsOn', ())))