Skip to content

Cleanup: delete yaml_load_safely #11285

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

Merged
merged 1 commit into from
Apr 17, 2024
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
28 changes: 0 additions & 28 deletions readthedocs/config/tests/test_yaml_loader.py

This file was deleted.

62 changes: 2 additions & 60 deletions readthedocs/doc_builder/backends/mkdocs.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ def get_final_doctype(self):
allow_symlinks=True,
base_path=self.project_path,
) as fh:
config = yaml_load_safely(fh)
# Use ``.safe_load()`` since ``mkdocs.yml`` is an untrusted source.
config = yaml.safe_load(fh)
use_directory_urls = config.get("use_directory_urls", True)
return MKDOCS if use_directory_urls else MKDOCS_HTML

Expand Down Expand Up @@ -119,62 +120,3 @@ def build(self):
class MkdocsHTML(BaseMkdocs):
builder = "build"
build_dir = "_readthedocs/html"


class ProxyPythonName(yaml.YAMLObject):
def __init__(self, value):
self.value = value

def __eq__(self, other):
return self.value == other.value


class SafeLoader(yaml.SafeLoader): # pylint: disable=too-many-ancestors

"""
Safe YAML loader.

This loader parses special ``!!python/name:`` tags without actually
importing or executing code. Every other special tag is ignored.

Borrowed from https://stackoverflow.com/a/57121993
Issue https://github.com/readthedocs/readthedocs.org/issues/7461
"""

def ignore_unknown(self, node): # pylint: disable=unused-argument
return None

def construct_python_name(self, suffix, node): # pylint: disable=unused-argument
return ProxyPythonName(suffix)


class SafeDumper(yaml.SafeDumper):

"""
Safe YAML dumper.

This dumper allows to avoid losing values of special tags that
were parsed by our safe loader.
"""

def represent_name(self, data):
return self.represent_scalar("tag:yaml.org,2002:python/name:" + data.value, "")


SafeLoader.add_multi_constructor(
"tag:yaml.org,2002:python/name:", SafeLoader.construct_python_name
)
SafeLoader.add_constructor(None, SafeLoader.ignore_unknown)
SafeDumper.add_representer(ProxyPythonName, SafeDumper.represent_name)


def yaml_load_safely(content):
"""
Uses ``SafeLoader`` loader to skip unknown tags.

When a YAML contains ``!!python/name:int`` it will store the ``int``
suffix temporarily to be able to re-dump it later. We need this to avoid
executing random code, but still support these YAML files without
information loss.
"""
return yaml.load(content, Loader=SafeLoader)