updates
This commit is contained in:
@@ -0,0 +1,121 @@
|
||||
# This file is part of CycloneDX Python Library
|
||||
#
|
||||
# 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 abc import ABC, abstractmethod
|
||||
from typing import TYPE_CHECKING, Any, Literal, Optional, Protocol, Union, overload
|
||||
|
||||
from ..schema import OutputFormat
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover
|
||||
from ..schema import SchemaVersion
|
||||
from .json import JsonValidator
|
||||
from .xml import XmlValidator
|
||||
|
||||
|
||||
class ValidationError:
|
||||
"""Validation failed with this specific error.
|
||||
|
||||
Use :attr:`~data` to access the content.
|
||||
"""
|
||||
|
||||
data: Any
|
||||
|
||||
def __init__(self, data: Any) -> None:
|
||||
self.data = data
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return repr(self.data)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return str(self.data)
|
||||
|
||||
|
||||
class SchemabasedValidator(Protocol):
|
||||
"""Schema-based Validator protocol"""
|
||||
|
||||
def validate_str(self, data: str) -> Optional[ValidationError]:
|
||||
"""Validate a string
|
||||
|
||||
:param data: the data string to validate
|
||||
:return: validation error
|
||||
:retval None: if ``data`` is valid
|
||||
:retval ValidationError: if ``data`` is invalid
|
||||
"""
|
||||
... # pragma: no cover
|
||||
|
||||
|
||||
class BaseSchemabasedValidator(ABC, SchemabasedValidator):
|
||||
"""Base Schema-based Validator"""
|
||||
|
||||
def __init__(self, schema_version: 'SchemaVersion') -> None:
|
||||
self.__schema_version = schema_version
|
||||
if not self._schema_file:
|
||||
raise ValueError(f'Unsupported schema_version: {schema_version!r}')
|
||||
|
||||
@property
|
||||
def schema_version(self) -> 'SchemaVersion':
|
||||
"""Get the schema version."""
|
||||
return self.__schema_version
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def output_format(self) -> OutputFormat:
|
||||
"""Get the format."""
|
||||
... # pragma: no cover
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def _schema_file(self) -> Optional[str]:
|
||||
"""Get the schema file according to schema version."""
|
||||
... # pragma: no cover
|
||||
|
||||
|
||||
@overload
|
||||
def make_schemabased_validator(output_format: Literal[OutputFormat.JSON], schema_version: 'SchemaVersion'
|
||||
) -> 'JsonValidator':
|
||||
... # pragma: no cover
|
||||
|
||||
|
||||
@overload
|
||||
def make_schemabased_validator(output_format: Literal[OutputFormat.XML], schema_version: 'SchemaVersion'
|
||||
) -> 'XmlValidator':
|
||||
... # pragma: no cover
|
||||
|
||||
|
||||
@overload
|
||||
def make_schemabased_validator(output_format: OutputFormat, schema_version: 'SchemaVersion'
|
||||
) -> Union['JsonValidator', 'XmlValidator']:
|
||||
... # pragma: no cover
|
||||
|
||||
|
||||
def make_schemabased_validator(output_format: OutputFormat, schema_version: 'SchemaVersion'
|
||||
) -> 'BaseSchemabasedValidator':
|
||||
"""Get the default Schema-based Validator for a certain :class:`OutputFormat`.
|
||||
|
||||
Raises error when no instance could be made.
|
||||
"""
|
||||
if TYPE_CHECKING: # pragma: no cover
|
||||
from typing import Type
|
||||
Validator: Type[BaseSchemabasedValidator] # noqa:N806
|
||||
if OutputFormat.JSON is output_format:
|
||||
from .json import JsonValidator as Validator
|
||||
elif OutputFormat.XML is output_format:
|
||||
from .xml import XmlValidator as Validator
|
||||
else:
|
||||
raise ValueError(f'Unexpected output_format: {output_format!r}')
|
||||
return Validator(schema_version)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,119 @@
|
||||
# This file is part of CycloneDX Python Library
|
||||
#
|
||||
# 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.
|
||||
|
||||
|
||||
__all__ = ['JsonValidator', 'JsonStrictValidator']
|
||||
|
||||
from abc import ABC
|
||||
from json import loads as json_loads
|
||||
from typing import TYPE_CHECKING, Any, Literal, Optional, Tuple
|
||||
|
||||
from ..schema import OutputFormat
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover
|
||||
from ..schema import SchemaVersion
|
||||
|
||||
from ..exception import MissingOptionalDependencyException
|
||||
from ..schema._res import BOM_JSON as _S_BOM, BOM_JSON_STRICT as _S_BOM_STRICT, JSF as _S_JSF, SPDX_JSON as _S_SPDX
|
||||
from . import BaseSchemabasedValidator, SchemabasedValidator, ValidationError
|
||||
|
||||
_missing_deps_error: Optional[Tuple[MissingOptionalDependencyException, ImportError]] = None
|
||||
try:
|
||||
from jsonschema.exceptions import ValidationError as JsonValidationError # type:ignore[import-untyped]
|
||||
from jsonschema.validators import Draft7Validator # type:ignore[import-untyped]
|
||||
from referencing import Registry
|
||||
from referencing.jsonschema import DRAFT7
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover
|
||||
from jsonschema.protocols import Validator as JsonSchemaValidator # type:ignore[import-untyped]
|
||||
except ImportError as err:
|
||||
_missing_deps_error = MissingOptionalDependencyException(
|
||||
'This functionality requires optional dependencies.\n'
|
||||
'Please install `cyclonedx-python-lib` with the extra "json-validation".\n'
|
||||
), err
|
||||
|
||||
|
||||
class _BaseJsonValidator(BaseSchemabasedValidator, ABC):
|
||||
@property
|
||||
def output_format(self) -> Literal[OutputFormat.JSON]:
|
||||
return OutputFormat.JSON
|
||||
|
||||
def __init__(self, schema_version: 'SchemaVersion') -> None:
|
||||
# this is the def that is used for generating the documentation
|
||||
super().__init__(schema_version)
|
||||
|
||||
if _missing_deps_error: # noqa:C901
|
||||
__MDERROR = _missing_deps_error
|
||||
|
||||
def validate_str(self, data: str) -> Optional[ValidationError]:
|
||||
raise self.__MDERROR[0] from self.__MDERROR[1]
|
||||
|
||||
else:
|
||||
def validate_str(self, data: str) -> Optional[ValidationError]:
|
||||
return self._validata_data(
|
||||
json_loads(data))
|
||||
|
||||
def _validata_data(self, data: Any) -> Optional[ValidationError]:
|
||||
validator = self._validator # may throw on error that MUST NOT be caught
|
||||
try:
|
||||
validator.validate(data)
|
||||
except JsonValidationError as error:
|
||||
return ValidationError(error)
|
||||
return None
|
||||
|
||||
__validator: Optional['JsonSchemaValidator'] = None
|
||||
|
||||
@property
|
||||
def _validator(self) -> 'JsonSchemaValidator':
|
||||
if not self.__validator:
|
||||
schema_file = self._schema_file
|
||||
if schema_file is None:
|
||||
raise NotImplementedError('missing schema file')
|
||||
with open(schema_file) as sf:
|
||||
self.__validator = Draft7Validator(
|
||||
json_loads(sf.read()),
|
||||
registry=self.__make_validator_registry(),
|
||||
format_checker=Draft7Validator.FORMAT_CHECKER)
|
||||
return self.__validator
|
||||
|
||||
@staticmethod
|
||||
def __make_validator_registry() -> Registry[Any]:
|
||||
schema_prefix = 'http://cyclonedx.org/schema/'
|
||||
with open(_S_SPDX) as spdx, open(_S_JSF) as jsf:
|
||||
return Registry().with_resources([
|
||||
(f'{schema_prefix}spdx.SNAPSHOT.schema.json', DRAFT7.create_resource(json_loads(spdx.read()))),
|
||||
(f'{schema_prefix}jsf-0.82.SNAPSHOT.schema.json', DRAFT7.create_resource(json_loads(jsf.read()))),
|
||||
])
|
||||
|
||||
|
||||
class JsonValidator(_BaseJsonValidator, BaseSchemabasedValidator, SchemabasedValidator):
|
||||
"""Validator for CycloneDX documents in JSON format."""
|
||||
|
||||
@property
|
||||
def _schema_file(self) -> Optional[str]:
|
||||
return _S_BOM.get(self.schema_version)
|
||||
|
||||
|
||||
class JsonStrictValidator(_BaseJsonValidator, BaseSchemabasedValidator, SchemabasedValidator):
|
||||
"""Strict validator for CycloneDX documents in JSON format.
|
||||
|
||||
In contrast to :class:`~JsonValidator`,
|
||||
the document must not have additional or unknown JSON properties.
|
||||
"""
|
||||
@property
|
||||
def _schema_file(self) -> Optional[str]:
|
||||
return _S_BOM_STRICT.get(self.schema_version)
|
||||
@@ -0,0 +1,22 @@
|
||||
# This file is part of CycloneDX Python Library
|
||||
#
|
||||
# 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.
|
||||
|
||||
|
||||
# nothing here, yet.
|
||||
# in the future this could be the place where model validation is done.
|
||||
# like the current `model.bom.Bom.validate()`
|
||||
# see also: https://github.com/CycloneDX/cyclonedx-python-lib/issues/455
|
||||
@@ -0,0 +1,102 @@
|
||||
# This file is part of CycloneDX Python Library
|
||||
#
|
||||
# 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.
|
||||
|
||||
|
||||
__all__ = ['XmlValidator']
|
||||
|
||||
from abc import ABC
|
||||
from typing import TYPE_CHECKING, Any, Literal, Optional, Tuple
|
||||
|
||||
from ..exception import MissingOptionalDependencyException
|
||||
from ..schema import OutputFormat
|
||||
from ..schema._res import BOM_XML as _S_BOM
|
||||
from . import BaseSchemabasedValidator, SchemabasedValidator, ValidationError
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover
|
||||
from ..schema import SchemaVersion
|
||||
|
||||
_missing_deps_error: Optional[Tuple[MissingOptionalDependencyException, ImportError]] = None
|
||||
try:
|
||||
from lxml.etree import ( # type:ignore[import-untyped] # nosec B410
|
||||
XMLParser,
|
||||
XMLSchema,
|
||||
fromstring as xml_fromstring,
|
||||
)
|
||||
except ImportError as err:
|
||||
_missing_deps_error = MissingOptionalDependencyException(
|
||||
'This functionality requires optional dependencies.\n'
|
||||
'Please install `cyclonedx-python-lib` with the extra "xml-validation".\n'
|
||||
), err
|
||||
|
||||
|
||||
class _BaseXmlValidator(BaseSchemabasedValidator, ABC):
|
||||
|
||||
@property
|
||||
def output_format(self) -> Literal[OutputFormat.XML]:
|
||||
return OutputFormat.XML
|
||||
|
||||
def __init__(self, schema_version: 'SchemaVersion') -> None:
|
||||
# this is the def that is used for generating the documentation
|
||||
super().__init__(schema_version)
|
||||
|
||||
if _missing_deps_error:
|
||||
__MDERROR = _missing_deps_error
|
||||
|
||||
def validate_str(self, data: str) -> Optional[ValidationError]:
|
||||
raise self.__MDERROR[0] from self.__MDERROR[1]
|
||||
else:
|
||||
def validate_str(self, data: str) -> Optional[ValidationError]:
|
||||
return self._validata_data(
|
||||
xml_fromstring( # nosec B320
|
||||
bytes(data, encoding='utf8'),
|
||||
parser=self.__xml_parser))
|
||||
|
||||
def _validata_data(self, data: Any) -> Optional[ValidationError]:
|
||||
validator = self._validator # may throw on error that MUST NOT be caught
|
||||
if not validator.validate(data):
|
||||
return ValidationError(validator.error_log.last_error)
|
||||
return None
|
||||
|
||||
__validator: Optional['XMLSchema'] = None
|
||||
|
||||
@property
|
||||
def __xml_parser(self) -> XMLParser:
|
||||
return XMLParser(
|
||||
attribute_defaults=False, dtd_validation=False, load_dtd=False,
|
||||
no_network=True,
|
||||
resolve_entities=False,
|
||||
huge_tree=True,
|
||||
compact=True,
|
||||
recover=False
|
||||
)
|
||||
|
||||
@property
|
||||
def _validator(self) -> 'XMLSchema':
|
||||
if not self.__validator:
|
||||
schema_file = self._schema_file
|
||||
if schema_file is None:
|
||||
raise NotImplementedError('missing schema file')
|
||||
self.__validator = XMLSchema(file=schema_file)
|
||||
return self.__validator
|
||||
|
||||
|
||||
class XmlValidator(_BaseXmlValidator, BaseSchemabasedValidator, SchemabasedValidator):
|
||||
"""Validator for CycloneDX documents in XML format."""
|
||||
|
||||
@property
|
||||
def _schema_file(self) -> Optional[str]:
|
||||
return _S_BOM.get(self.schema_version)
|
||||
Reference in New Issue
Block a user