Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: bom.validate() detects invalid license constellations #452

Merged
merged 3 commits into from
Sep 25, 2023
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
11 changes: 11 additions & 0 deletions cyclonedx/exception/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,21 @@ class UnknownComponentDependencyException(CycloneDxModelException):
"""
Exception raised when a dependency has been noted for a Component that is NOT a Component BomRef in this Bom.
"""
pass


class UnknownHashTypeException(CycloneDxModelException):
"""
Exception raised when we are unable to determine the type of hash from a composite hash string.
"""
pass


class LicenseExpressionAlongWithOthersException(CycloneDxModelException):
"""
Exception raised when a LicenseExpression was detected along with other licenses.
If a LicenseExpression exists, than it must stand alone.

See https://github.com/CycloneDX/specification/pull/205
"""
pass
18 changes: 16 additions & 2 deletions cyclonedx/model/bom.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,16 @@
# Copyright (c) OWASP Foundation. All Rights Reserved.
import warnings
from datetime import datetime
from typing import TYPE_CHECKING, Iterable, Optional, Set
from itertools import chain
from typing import TYPE_CHECKING, Iterable, Optional, Set, Union
from uuid import UUID, uuid4

import serializable
from sortedcontainers import SortedSet

from cyclonedx.serialization import UrnUuidHelper

from ..exception.model import UnknownComponentDependencyException
from ..exception.model import LicenseExpressionAlongWithOthersException, UnknownComponentDependencyException
from ..parser import BaseParser
from ..schema.schema import (
SchemaVersion1Dot0,
Expand Down Expand Up @@ -573,6 +574,19 @@ def validate(self) -> bool:
UserWarning
)

# 3. If a LicenseExpression is set, then there must be no other license.
# see https://github.com/CycloneDX/specification/pull/205
elem: Union[BomMetaData, Component, Service]
for elem in chain( # type: ignore[assignment]
[self.metadata],
self.metadata.component.get_all_nested_components(include_self=True) if self.metadata.component else [],
chain.from_iterable(c.get_all_nested_components(include_self=True) for c in self.components),
self.services
):
if len(elem.licenses) > 1 and any(li.expression for li in elem.licenses):
raise LicenseExpressionAlongWithOthersException(
f'Found LicenseExpression along with others licenses in: {elem!r}')

return True

def __eq__(self, other: object) -> bool:
Expand Down
53 changes: 53 additions & 0 deletions tests/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,59 @@ def get_vulnerability_source_owasp() -> VulnerabilitySource:
return VulnerabilitySource(name='OWASP', url=XsUri('https://owasp.org'))


def get_bom_metadata_licenses_invalid() -> Bom:
return Bom(metadata=BomMetaData(licenses=[
LicenseChoice(expression='Apache-2.0 OR MIT'),
LicenseChoice(license=License(id='MIT')),
]))


def get_invalid_license_repository() -> List[LicenseChoice]:
"""
license expression and a license -- this is an invalid constellation according to schema
see https://github.com/CycloneDX/specification/pull/205
"""
return [
LicenseChoice(expression='Apache-2.0 OR MIT'),
LicenseChoice(license=License(id='GPL-2.0-only')),
]


def get_component_licenses_invalid() -> Component:
return Component(name='foo', type=ComponentType.LIBRARY,
licenses=get_invalid_license_repository())


def get_bom_metadata_component_licenses_invalid() -> Bom:
comp = get_component_licenses_invalid()
return Bom(metadata=BomMetaData(component=comp),
dependencies=[Dependency(comp.bom_ref)])


def get_bom_metadata_component_nested_licenses_invalid() -> Bom:
comp = Component(name='bar', type=ComponentType.LIBRARY,
components=[get_component_licenses_invalid()])
return Bom(metadata=BomMetaData(component=comp),
dependencies=[Dependency(comp.bom_ref)])


def get_bom_component_licenses_invalid() -> Bom:
return Bom(components=[get_component_licenses_invalid()])


def get_bom_component_nested_licenses_invalid() -> Bom:
return Bom(components=[
Component(name='bar', type=ComponentType.LIBRARY,
components=[get_component_licenses_invalid()])
])


def get_bom_service_licenses_invalid() -> Bom:
return Bom(services=[
Service(name='foo', licenses=get_invalid_license_repository())
])


T = TypeVar('T')


Expand Down
59 changes: 41 additions & 18 deletions tests/test_model_bom.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,11 @@
# encoding: utf-8

# This file is part of CycloneDX Python Lib
#
# 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 typing import Callable
from unittest import TestCase
from uuid import uuid4

from ddt import ddt, named_data

from cyclonedx.exception.model import LicenseExpressionAlongWithOthersException
from cyclonedx.model import (
License,
LicenseChoice,
Expand All @@ -33,12 +19,35 @@
from cyclonedx.model.bom_ref import BomRef
from cyclonedx.model.component import Component, ComponentType
from tests.data import (
get_bom_component_licenses_invalid,
get_bom_component_nested_licenses_invalid,
get_bom_for_issue_275_components,
get_bom_metadata_component_licenses_invalid,
get_bom_metadata_component_nested_licenses_invalid,
get_bom_metadata_licenses_invalid,
get_bom_service_licenses_invalid,
get_bom_with_component_setuptools_with_vulnerability,
get_component_setuptools_simple,
get_component_setuptools_simple_no_version,
)

# This file is part of CycloneDX Python Lib
#
# 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.


class TestBomMetaData(TestCase):

Expand Down Expand Up @@ -96,6 +105,7 @@ def test_basic_bom_metadata(self) -> None:
self.assertTrue(tools[1] in metadata.tools)


@ddt
class TestBom(TestCase):

def test_bom_metadata_tool_this_tool(self) -> None:
Expand Down Expand Up @@ -168,6 +178,19 @@ def test_bom_nested_components_issue_275(self) -> None:
self.assertEqual(2, len(bom.components))
bom.validate()

@named_data(
['metadata_licenses', get_bom_metadata_licenses_invalid],
['metadata_component_licenses', get_bom_metadata_component_licenses_invalid],
['metadata_component_nested_licenses', get_bom_metadata_component_nested_licenses_invalid],
['component_licenses', get_bom_component_licenses_invalid],
['component_nested_licenses', get_bom_component_nested_licenses_invalid],
['service_licenses', get_bom_service_licenses_invalid],
)
def test_validate_with_invalid_license_constellation_throws(self, get_bom: Callable[[], Bom]) -> None:
bom = get_bom()
with self.assertRaises(LicenseExpressionAlongWithOthersException):
bom.validate()

# def test_bom_nested_services_issue_275(self) -> None:
# """regression test for issue #275
# see https://github.com/CycloneDX/cyclonedx-python-lib/issues/275
Expand Down
2 changes: 1 addition & 1 deletion tests/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,5 @@ def test_as_expected(self, of: OutputFormat, sv: SchemaVersion) -> None:
)
@unpack
def test_fails_on_wrong_args(self, of: OutputFormat, sv: SchemaVersion, raisesRegex: Tuple) -> None:
with self.assertRaisesRegexp(*raisesRegex):
with self.assertRaisesRegex(*raisesRegex):
get_validator(of, sv)