From 7cc11025d00086e53fe2f2f3334bc7bceef9b8ca Mon Sep 17 00:00:00 2001 From: Rafael Caricio Date: Tue, 28 Jun 2016 10:38:07 +0200 Subject: [PATCH] Use safe_load to avoid code invocation from YAML files --- connexion/api.py | 5 ++++- tests/test_api.py | 15 +++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/connexion/api.py b/connexion/api.py index f80711d55..67ac75b75 100644 --- a/connexion/api.py +++ b/connexion/api.py @@ -36,6 +36,9 @@ def compatibility_layer(spec): """Make specs compatible with older versions of Connexion.""" + if not isinstance(spec, dict): + return spec + # Make all response codes be string for path_name, methods_available in spec.get('paths', {}).items(): for method_name, method_def in methods_available.items(): @@ -92,7 +95,7 @@ def __init__(self, swagger_yaml_path, base_url=None, arguments=None, swagger_template = contents.decode('utf-8', 'replace') swagger_string = jinja2.Template(swagger_template).render(**arguments) - self.specification = yaml.load(swagger_string) # type: dict + self.specification = yaml.safe_load(swagger_string) # type: dict logger.debug('Read specification', extra={'spec': self.specification}) diff --git a/tests/test_api.py b/tests/test_api.py index c16761f02..92fd7551a 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -3,10 +3,10 @@ import pathlib import tempfile +import pytest from connexion.api import Api from swagger_spec_validator.common import SwaggerValidationError - -import pytest +from yaml import YAMLError TEST_FOLDER = pathlib.Path(__file__).parent @@ -53,3 +53,14 @@ def test_invalid_encoding(): f.write(u"swagger: '2.0'\ninfo:\n title: Foo 整\n version: v1\npaths: {}".encode('gbk')) f.flush() Api(pathlib.Path(f.name), "/api/v1.0") + + +def test_use_of_safe_load_for_yaml_swagger_specs(): + with pytest.raises(YAMLError): + with tempfile.NamedTemporaryFile() as f: + f.write('!!python/object:object {}\n'.encode()) + f.flush() + try: + Api(pathlib.Path(f.name), "/api/v1.0") + except SwaggerValidationError: + pytest.fail("Could load invalid YAML file, use yaml.safe_load!")