Skip to content

Commit

Permalink
disallow imports from modules starting with '_'
Browse files Browse the repository at this point in the history
  • Loading branch information
loechel authored and Michael Howitz committed May 17, 2018
1 parent 2c4af14 commit 4299c95
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
2 changes: 2 additions & 0 deletions docs/CHANGES.rst
Expand Up @@ -23,6 +23,8 @@ Changes
protected build-ins.
(`#102 <https://github.com/zopefoundation/RestrictedPython/issues/102>`_)

- Imports like `from _a import b` or `from a._b import x` are now forbidden.


4.0b3 (2018-04-12)
------------------
Expand Down
7 changes: 7 additions & 0 deletions src/RestrictedPython/transformer.py
Expand Up @@ -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.')
Expand Down
25 changes: 22 additions & 3 deletions tests/transformer/test_import.py
Expand Up @@ -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)
Expand Down

0 comments on commit 4299c95

Please sign in to comment.