Skip to content

Commit c74218b

Browse files
author
Saquib Saifee
committed
feat: add CPE format validation in property setter
Signed-off-by: Saquib Saifee <[email protected]>
1 parent c72d5f4 commit c74218b

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

cyclonedx/model/component.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
# See https://github.com/package-url/packageurl-python/issues/65
2525
import serializable
26+
from cpe import CPE # type:ignore
2627
from packageurl import PackageURL
2728
from sortedcontainers import SortedSet
2829

@@ -1457,7 +1458,11 @@ def cpe(self) -> Optional[str]:
14571458

14581459
@cpe.setter
14591460
def cpe(self, cpe: Optional[str]) -> None:
1460-
self._cpe = cpe
1461+
if cpe:
1462+
try:
1463+
CPE(cpe)
1464+
except NotImplementedError:
1465+
raise ValueError(f'Invalid CPE format: {cpe}')
14611466

14621467
@property
14631468
@serializable.type_mapping(PackageUrlSH)

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ sortedcontainers = "^2.4.0"
7474
license-expression = "^30"
7575
jsonschema = { version = "^4.18", extras=['format'], optional=true }
7676
lxml = { version=">=4,<6", optional=true }
77+
cpe = "^1.3.1"
7778

7879
[tool.poetry.extras]
7980
validation = ["jsonschema", "lxml"]

tests/test_model_component.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,16 @@ def test_nested_components_2(self) -> None:
283283
self.assertEqual(3, len(comp_b.get_all_nested_components(include_self=True)))
284284
self.assertEqual(2, len(comp_b.get_all_nested_components(include_self=False)))
285285

286+
def test_cpe_validation_valid_format(self) -> None:
287+
cpe = 'cpe:2.3:a:python:setuptools:50.3.2:*:*:*:*:*:*:*'
288+
c = Component(name='test-component', cpe=cpe)
289+
self.assertEqual(c.cpe, cpe)
290+
291+
def test_cpe_validation_invalid_format(self) -> None:
292+
invalid_cpe = 'invalid-cpe-string'
293+
with self.assertRaises(ValueError):
294+
Component(name='test-component', cpe=invalid_cpe)
295+
286296

287297
class TestModelComponentEvidence(TestCase):
288298

0 commit comments

Comments
 (0)