From 4299c956119ceda5a44c62254e8248ab1bdb16c8 Mon Sep 17 00:00:00 2001 From: Alexander Loechel Date: Thu, 17 May 2018 11:29:16 +0200 Subject: [PATCH] disallow imports from modules starting with '_' --- docs/CHANGES.rst | 2 ++ src/RestrictedPython/transformer.py | 7 +++++++ tests/transformer/test_import.py | 25 ++++++++++++++++++++++--- 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/docs/CHANGES.rst b/docs/CHANGES.rst index 3d00820..e489829 100644 --- a/docs/CHANGES.rst +++ b/docs/CHANGES.rst @@ -23,6 +23,8 @@ Changes protected build-ins. (`#102 `_) +- Imports like `from _a import b` or `from a._b import x` are now forbidden. + 4.0b3 (2018-04-12) ------------------ diff --git a/src/RestrictedPython/transformer.py b/src/RestrictedPython/transformer.py index c3b0cf9..89ae156 100644 --- a/src/RestrictedPython/transformer.py +++ b/src/RestrictedPython/transformer.py @@ -451,6 +451,13 @@ def check_import_names(self, node): => 'from _a import x' is ok, because '_a' is not added to the scope. """ + if (isinstance(node, ast.ImportFrom) + and not node.module == '__future__' + and any( + [name.startswith('_') for name in node.module.split('.')] + )): + self.error(node, 'module name starts "_", which is forbidden.') + for name in node.names: if '*' in name.name: self.error(node, '"*" imports are not allowed.') diff --git a/tests/transformer/test_import.py b/tests/transformer/test_import.py index 868ae15..e44aa30 100644 --- a/tests/transformer/test_import.py +++ b/tests/transformer/test_import.py @@ -45,11 +45,30 @@ def test_RestrictingNodeTransformer__visit_Import__5(c_exec): @pytest.mark.parametrize(*c_exec) -def test_RestrictingNodeTransformer__visit_Import_6(c_exec): +def test_RestrictingNodeTransformer__visit_Import__6_1(c_exec): """It allows importing from a module starting with `_`.""" result = c_exec('from _a import m') - assert result.errors == () - assert result.code is not None + assert result.errors == ( + 'Line 1: module name starts "_", which is forbidden.', + ) + + +@pytest.mark.parametrize(*c_exec) +def test_RestrictingNodeTransformer__visit_Import__6_2(c_exec): + """It allows importing from a module starting with `_`.""" + result = c_exec('from a._b import m') + assert result.errors == ( + 'Line 1: module name starts "_", which is forbidden.', + ) + + +@pytest.mark.parametrize(*c_exec) +def test_RestrictingNodeTransformer__visit_Import__6_3(c_exec): + """It allows importing from a module starting with `_`.""" + result = c_exec('from _a.b import m') + assert result.errors == ( + 'Line 1: module name starts "_", which is forbidden.', + ) @pytest.mark.parametrize(*c_exec)