Skip to content
Merged
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
50 changes: 50 additions & 0 deletions cyclonedx_py/_internal/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from json import JSONDecodeError, loads as json_loads
from os import getcwd, name as os_name
from os.path import exists, isdir, join
from platform import python_version
from subprocess import run # nosec
from sys import executable, path as sys_path
from textwrap import dedent
Expand Down Expand Up @@ -128,6 +129,11 @@ def make_argument_parser(**kwargs: Any) -> 'ArgumentParser':
action='store_true',
dest='gather_license_texts',
help='Enable license text gathering.')
p.add_argument('--add-python-runtime',
action='store_true',
dest='add_python_runtime',
help='Add the Python runtime of the analyzed environment as an external component.\n'
'The `isExternal` marker is only available in CycloneDX 1.7 and later.')
add_argument_pyproject(p)
add_argument_mc_type(p)
# TODO possible additional switch:
Expand All @@ -145,9 +151,11 @@ def make_argument_parser(**kwargs: Any) -> 'ArgumentParser':
def __init__(self, *,
logger: 'Logger',
gather_license_texts: bool,
add_python_runtime: bool,
**__: Any) -> None:
self._logger = logger
self._gather_license_texts = gather_license_texts
self._add_python_runtime = add_python_runtime

def __call__(self, *, # type:ignore[override]
import_site: bool,
Expand Down Expand Up @@ -182,8 +190,31 @@ def __call__(self, *, # type:ignore[override]

bom = make_bom()
self.__add_components(bom, rc, path=path)
if self._add_python_runtime:
py_version = self.__version4python(python, import_site, honor_py_env_vars) \
if python \
else python_version()
self.__add_python_runtime_component(bom, py_version)
return bom

def __add_python_runtime_component(self, bom: 'Bom', py_version: str) -> None:
# the runtime is expected to be provided by the deployment environment, it is not bundled.
# the implementation (CPython, PyPy, etc.) is intentionally not part of the SBOM.
runtime_c = Component(
type=ComponentType.PLATFORM,
bom_ref='python-runtime',
name='python',
version=py_version,
is_external=True,
)
self._logger.info('add component for Python runtime %r', py_version)
self._logger.debug('add component: %r', runtime_c)
bom.components.add(runtime_c)
if bom.metadata.component is None:
bom.register_dependency(runtime_c)
else:
bom.register_dependency(bom.metadata.component, (runtime_c,))

def __add_components(self, bom: 'Bom',
rc: Optional[tuple['Component', Iterable['Requirement']]],
**kwargs: Any) -> None:
Expand Down Expand Up @@ -306,6 +337,25 @@ def __py_interpreter(value: str) -> str:
raise ValueError(f'Failed to find python in directory: {value}')
return value

def __version4python(self, python: str, import_site: bool, honor_py_env_vars: bool) -> str:
Comment thread
jkowalleck marked this conversation as resolved.
Resolved
cmd = [self.__py_interpreter(python),
'-c', 'import platform,sys;sys.stdout.write(platform.python_version())']
if not import_site:
cmd.insert(1, '-S')
if not honor_py_env_vars:
cmd.insert(1, '-E')

self._logger.debug('fetch `version` from python interpreter cmd: %r', cmd)
res = run(cmd, capture_output=True, encoding='utf8', shell=False) # nosec
version = res.stdout.strip()
if res.returncode != 0 or len(version) == 0:
raise RuntimeError('Fail fetching `version` from Python interpreter.\n'
f'returncode: {res.returncode}\n'
f'stdout: {res.stdout}\n'
f'stderr: {res.stderr}\n')
self._logger.debug('got `version` from Python interpreter: %r', version)
return version

def __path4python(self, python: str, import_site: bool, honor_py_env_vars: bool) -> list[str]:
cmd = [self.__py_interpreter(python),
'-c', 'import json,sys;json.dump(sys.path,sys.stdout)']
Expand Down
9 changes: 9 additions & 0 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,20 @@ For Python (virtual) environment
By analyzing the actually installed packages, this will produce the most accurate and complete CycloneDX BOM.
The generated CycloneDX SBOM will include metadata, licenses, dependency graph, and more.

With ``--add-python-runtime``, the Python runtime of the analyzed environment is added as a component
of type ``platform`` with ``isExternal=true``, named ``python`` and versioned like ``3.13.5``.
The ``isExternal`` marker is only available in CycloneDX 1.7 and later (``--spec-version 1.7``).
If a root component is known (``--pyproject``), it depends on this runtime component.
The specific implementation (CPython, PyPy, etc.) is intentionally not part of the SBOM.

The full documentation can be issued by running with ``environment --help``:

.. code-block:: shell-session

$ cyclonedx-py environment --help
usage: cyclonedx-py environment [-h] [-v]
[--gather-license-texts]
[--add-python-runtime]
[--short-PURLs] [--output-reproducible]
[--validate | --no-validate]
[-o <file>] [--sv <version>] [--of <format>]
Expand All @@ -82,6 +89,8 @@ The full documentation can be issued by running with ``environment --help``:
flag.
--gather-license-texts
Enable license text gathering.
--add-python-runtime Add the Python runtime of the analyzed environment as an external component.
The `isExternal` marker is only available in CycloneDX 1.7 and later.
--pyproject <file> Path to the root component's `pyproject.toml` file.
This should point to a file compliant with PEP 621 (Storing project metadata in pyproject.toml). Supports PEP 639 (Improving License Clarity with Better Package Metadata).
--mc-type <type> Type of the main component.
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ cyclonedx-py = "cyclonedx_py._internal.cli:run"

[tool.poetry.dependencies]
python = ">=3.9, <4"
cyclonedx-python-lib = { version = ">=8, <12", extras = ["validation"] }
cyclonedx-python-lib = { version = ">=11.12, <12", extras = ["validation"] }
Comment thread
jkowalleck marked this conversation as resolved.
Resolved
packageurl-python = ">=0.11, <2" # keep in sync with same dep in `cyclonedx-python-lib`
pip-requirements-parser = ">=32, <33"
packaging = ">=22, <27"
Expand Down
57 changes: 57 additions & 0 deletions tests/integration/test_cli_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from json import loads as json_loads
from os import environ, mkdir, name as os_name
from os.path import basename, dirname, join
from platform import python_version
from subprocess import run # nosec:B404
from sys import executable, path as sys_path, stderr
from tempfile import TemporaryDirectory
Expand Down Expand Up @@ -306,6 +307,62 @@ def test_texts_as_expected(self, projectdir: str, sv: SchemaVersion, of: OutputF
self.assertEqual(0, res, err)
self.assertEqualSnapshot(out, 'texts', projectdir, sv, of)

def test_python_runtime_as_external_platform(self) -> None:
projectdir = join(INFILES_DIRECTORY, 'environment', 'no-deps')
res, out, err = run_cli(
'environment',
'-vvv',
'--add-python-runtime',
'--sv', '1.7',
'--of', OutputFormat.JSON.name,
'--output-reproducible',
'-o=-',
'--pyproject', join(projectdir, 'pyproject.toml'),
join(projectdir, '.venv'))
self.assertEqual(0, res, err)
venv_python = join(projectdir, '.venv', 'Scripts', 'python.exe') \
if os_name == 'nt' \
else join(projectdir, '.venv', 'bin', 'python')
expected_version = run(
(venv_python, '-c', 'import platform,sys;sys.stdout.write(platform.python_version())'),
capture_output=True, encoding='utf8', check=True, shell=False # nosec:B603
).stdout
bom = json_loads(out)
runtime = [c for c in bom['components'] if c.get('bom-ref') == 'python-runtime']
self.assertEqual([{
'bom-ref': 'python-runtime',
'isExternal': True,
'name': 'python',
'type': 'platform',
'version': expected_version,
}], runtime)
root_deps = next(d for d in bom['dependencies'] if d['ref'] == 'root-component')
self.assertIn('python-runtime', root_deps['dependsOn'])

def test_python_runtime_of_current_interpreter(self) -> None:
res, out, err = run_cli(
'environment', '--add-python-runtime', '--sv', '1.7', '--of', 'JSON', '-o=-')
self.assertEqual(0, res, err)
bom = json_loads(out)
runtime = next(c for c in bom['components'] if c.get('bom-ref') == 'python-runtime')
self.assertEqual(python_version(), runtime['version'])
self.assertIn('python-runtime', {d['ref'] for d in bom['dependencies']})

@named_data(('JSON', OutputFormat.JSON), ('XML', OutputFormat.XML))
def test_python_runtime_omitted_by_default(self, of: OutputFormat) -> None:
projectdir = join(INFILES_DIRECTORY, 'environment', 'no-deps')
res, out, err = run_cli(
'environment',
'-vvv',
'--sv', '1.7',
'--of', of.name,
'--output-reproducible',
'-o=-',
'--pyproject', join(projectdir, 'pyproject.toml'),
join(projectdir, '.venv'))
self.assertEqual(0, res, err)
self.assertNotIn('python-runtime', out)

def assertEqualSnapshot( # noqa:N802
self, actual: str,
purpose: str,
Expand Down
Loading