| 1 |
import copy |
| 2 |
import json |
| 3 |
import logging |
| 4 |
import warnings |
| 5 |
|
| 6 |
import yaml |
| 7 |
from django.utils.encoding import force_bytes |
| 8 |
|
| 9 |
try: |
| 10 |
from swagger_spec_validator.common import SwaggerValidationError as SSVErr |
| 11 |
from swagger_spec_validator.validator20 import validate_spec as validate_ssv |
| 12 |
except ImportError: |
| 13 |
validate_ssv = None |
| 14 |
|
| 15 |
try: |
| 16 |
from flex.core import parse as validate_flex |
| 17 |
from flex.exceptions import ValidationError |
| 18 |
except ImportError: |
| 19 |
validate_flex = None |
| 20 |
|
| 21 |
from . import openapi |
| 22 |
from .errors import SwaggerValidationError |
| 23 |
|
| 24 |
logger = logging.getLogger(__name__) |
| 25 |
|
| 26 |
|
| 27 |
def _validate_flex(spec): |
| 28 |
try: |
| 29 |
validate_flex(spec) |
| 30 |
except ValidationError as ex: |
| 31 |
raise SwaggerValidationError(str(ex)) from ex |
| 32 |
|
| 33 |
|
| 34 |
def _validate_swagger_spec_validator(spec): |
| 35 |
try: |
| 36 |
validate_ssv(spec) |
| 37 |
except SSVErr as ex: |
| 38 |
raise SwaggerValidationError(str(ex)) from ex |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
VALIDATORS = { |
| 43 |
"flex": _validate_flex if validate_flex else lambda s: None, |
| 44 |
"ssv": _validate_swagger_spec_validator if validate_ssv else lambda s: None, |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
class _OpenAPICodec: |
| 49 |
media_type = None |
| 50 |
|
| 51 |
def __init__(self, validators): |
| 52 |
self._validators = validators |
| 53 |
|
| 54 |
@property |
| 55 |
def validators(self): |
| 56 |
"""List of validator names to apply""" |
| 57 |
return self._validators |
| 58 |
|
| 59 |
def encode(self, document): |
| 60 |
"""Transform an :class:`.Swagger` object to a sequence of bytes. |
| 61 |
|
| 62 |
Also performs validation and applies settings. |
| 63 |
|
| 64 |
:param openapi.Swagger document: Swagger spec object as generated by |
| 65 |
:class:`.OpenAPISchemaGenerator` |
| 66 |
:return: binary encoding of ``document`` |
| 67 |
:rtype: bytes |
| 68 |
""" |
| 69 |
if not isinstance(document, openapi.Swagger): |
| 70 |
raise TypeError("Expected a `openapi.Swagger` instance") |
| 71 |
|
| 72 |
spec = self.generate_swagger_object(document) |
| 73 |
errors = {} |
| 74 |
for validator in self.validators: |
| 75 |
try: |
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
VALIDATORS[validator](copy.deepcopy(spec)) |
| 80 |
except SwaggerValidationError as e: |
| 81 |
errors[validator] = str(e) |
| 82 |
|
| 83 |
if errors: |
| 84 |
exc = SwaggerValidationError( |
| 85 |
"spec validation failed: {}".format(errors), errors, spec, self |
| 86 |
) |
| 87 |
logger.warning(str(exc)) |
| 88 |
raise exc |
| 89 |
|
| 90 |
return force_bytes(self._dump_dict(spec)) |
| 91 |
|
| 92 |
def encode_error(self, err): |
| 93 |
"""Dump an error message into an encoding-appropriate sequence of bytes""" |
| 94 |
return force_bytes(self._dump_dict(err)) |
| 95 |
|
| 96 |
def _dump_dict(self, spec): |
| 97 |
"""Dump the given dictionary into its string representation. |
| 98 |
|
| 99 |
:param dict spec: a python dict |
| 100 |
:return: string representation of ``spec`` |
| 101 |
:rtype: str or bytes |
| 102 |
""" |
| 103 |
raise NotImplementedError("override this method") |
| 104 |
|
| 105 |
def generate_swagger_object(self, swagger): |
| 106 |
"""Generates the root Swagger object. |
| 107 |
|
| 108 |
:param openapi.Swagger swagger: Swagger spec object as generated by |
| 109 |
:class:`.OpenAPISchemaGenerator` |
| 110 |
:return: swagger spec as dict |
| 111 |
:rtype: dict |
| 112 |
""" |
| 113 |
return swagger.as_dict() |
| 114 |
|
| 115 |
|
| 116 |
class OpenAPICodecJson(_OpenAPICodec): |
| 117 |
media_type = "application/json" |
| 118 |
|
| 119 |
def __init__(self, validators, pretty=False, media_type="application/json"): |
| 120 |
super(OpenAPICodecJson, self).__init__(validators) |
| 121 |
self.pretty = pretty |
| 122 |
self.media_type = media_type |
| 123 |
|
| 124 |
def _dump_dict(self, spec): |
| 125 |
"""Dump ``spec`` into JSON. |
| 126 |
|
| 127 |
:rtype: str""" |
| 128 |
if self.pretty: |
| 129 |
return f"{json.dumps(spec, indent=4, separators=(',', ': '), ensure_ascii=False)}\n" |
| 130 |
else: |
| 131 |
return json.dumps(spec, ensure_ascii=False) |
| 132 |
|
| 133 |
|
| 134 |
_YamlDumper = getattr(yaml, "CSafeDumper", yaml.SafeDumper) |
| 135 |
YamlLoader = getattr(yaml, "CSafeLoader", yaml.SafeLoader) |
| 136 |
|
| 137 |
|
| 138 |
class YamlDumper(_YamlDumper): |
| 139 |
"""YamlDumper class usable for dumping ``dict`` and list instances in a |
| 140 |
standard way.""" |
| 141 |
|
| 142 |
def ignore_aliases(self, data): |
| 143 |
"""Disable YAML references.""" |
| 144 |
return True |
| 145 |
|
| 146 |
def represent_text(self, text): |
| 147 |
if "\n" in text: |
| 148 |
return self.represent_scalar("tag:yaml.org,2002:str", text, style="|") |
| 149 |
return self.represent_scalar("tag:yaml.org,2002:str", text) |
| 150 |
|
| 151 |
|
| 152 |
YamlDumper.add_representer(bytes, YamlDumper.represent_text) |
| 153 |
YamlDumper.add_representer(str, YamlDumper.represent_text) |
| 154 |
|
| 155 |
|
| 156 |
class SaneYamlDumper(YamlDumper): |
| 157 |
def __init__(self, *args, **kwargs) -> None: |
| 158 |
warnings.warn( |
| 159 |
"SaneYamlDumper has been renamed to YamlDumper", DeprecationWarning |
| 160 |
) |
| 161 |
super().__init__(*args, **kwargs) |
| 162 |
|
| 163 |
|
| 164 |
def yaml_dump(data, binary): |
| 165 |
"""Dump the given data dictionary into a format which is easier to read: |
| 166 |
|
| 167 |
* multi-line mapping style instead of json-like inline style |
| 168 |
* list elements are indented into their parents |
| 169 |
* YAML references/aliases are disabled |
| 170 |
|
| 171 |
:param dict data: the data to be dumped |
| 172 |
:param bool binary: True to return a utf-8 encoded binary object, False to return a |
| 173 |
string |
| 174 |
:return: the serialized YAML |
| 175 |
:rtype: str or bytes |
| 176 |
""" |
| 177 |
return yaml.dump( |
| 178 |
data, |
| 179 |
Dumper=YamlDumper, |
| 180 |
default_flow_style=False, |
| 181 |
encoding="utf-8" if binary else None, |
| 182 |
allow_unicode=binary, |
| 183 |
sort_keys=False, |
| 184 |
) |
| 185 |
|
| 186 |
|
| 187 |
def yaml_sane_dump(data, binary): |
| 188 |
warnings.warn("yaml_sane_dump has been renamed to yaml_dump", DeprecationWarning) |
| 189 |
return yaml_dump(data, binary) |
| 190 |
|
| 191 |
|
| 192 |
class SaneYamlLoader(YamlLoader): |
| 193 |
def __init__(self, *args, **kwargs) -> None: |
| 194 |
warnings.warn( |
| 195 |
"SaneYamlLoader is deprecated and custom loading is no longer needed. " |
| 196 |
"YamlLoader has been exported to easily import CSafeLoader and fall back " |
| 197 |
"to SafeLoader if unavailable", |
| 198 |
DeprecationWarning, |
| 199 |
) |
| 200 |
super().__init__(*args, **kwargs) |
| 201 |
|
| 202 |
|
| 203 |
def yaml_load(stream): |
| 204 |
"""Load the given YAML stream. |
| 205 |
|
| 206 |
:param stream: YAML stream (can be a string or a file-like object) |
| 207 |
:rtype: dict |
| 208 |
""" |
| 209 |
return yaml.load(stream, Loader=YamlLoader) |
| 210 |
|
| 211 |
|
| 212 |
def yaml_sane_load(stream): |
| 213 |
warnings.warn("yaml_sane_load has been renamed to yaml_load", DeprecationWarning) |
| 214 |
return yaml_load(stream) |
| 215 |
|
| 216 |
|
| 217 |
class OpenAPICodecYaml(_OpenAPICodec): |
| 218 |
media_type = "application/yaml" |
| 219 |
|
| 220 |
def __init__(self, validators, media_type="application/yaml"): |
| 221 |
super(OpenAPICodecYaml, self).__init__(validators) |
| 222 |
self.media_type = media_type |
| 223 |
|
| 224 |
def _dump_dict(self, spec): |
| 225 |
"""Dump ``spec`` into YAML. |
| 226 |
|
| 227 |
:rtype: bytes""" |
| 228 |
return yaml_dump(spec, binary=True) |