Skip to content

Commit

Permalink
deny * imports (#106)
Browse files Browse the repository at this point in the history
* deny * imports
  • Loading branch information
loechel committed May 17, 2018
1 parent 8b9af72 commit 5cdd3f4
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
5 changes: 4 additions & 1 deletion docs/CHANGES.rst
Expand Up @@ -4,7 +4,10 @@ Changes
4.0b4 (unreleased)
------------------

- Nothing changed yet.
- Imports like `from a import *` (so called star imports) are now forbidden as
they allow to import names starting with an underscore which could override
protected build-ins.
(`#102 <https://github.com/zopefoundation/RestrictedPython/issues/102>`_)


4.0b3 (2018-04-12)
Expand Down
10 changes: 6 additions & 4 deletions src/RestrictedPython/transformer.py
Expand Up @@ -427,10 +427,12 @@ def check_import_names(self, node):
=> 'from _a import x' is ok, because '_a' is not added to the scope.
"""
for alias in node.names:
self.check_name(node, alias.name)
if alias.asname:
self.check_name(node, alias.asname)
for name in node.names:
if '*' in name.name:
self.error(node, '"*" imports are not allowed.')
self.check_name(node, name.name)
if name.asname:
self.check_name(node, name.asname)

return self.node_contents_visit(node)

Expand Down
16 changes: 16 additions & 0 deletions tests/transformer/test_import.py
Expand Up @@ -71,3 +71,19 @@ def test_RestrictingNodeTransformer__visit_Import__9(c_exec):
"""It denies relative from importing as something starting with `_`."""
result = c_exec('from .x import y as _leading_underscore')
assert result.errors == (import_errmsg % '_leading_underscore',)


@pytest.mark.parametrize(*c_exec)
def test_RestrictingNodeTransformer__visit_Import_star__1(c_exec):
"""Importing `*` is a SyntaxError in Python itself."""
result = c_exec('import *')
assert result.errors == ('Line 1: SyntaxError: invalid syntax in on statement: import *',) # NOQA: E501
assert result.code is None


@pytest.mark.parametrize(*c_exec)
def test_RestrictingNodeTransformer__visit_Import_star__2(c_exec):
"""It denies importing `*` from a module."""
result = c_exec('from a import *')
assert result.errors == ('Line 1: "*" imports are not allowed.',)
assert result.code is None

0 comments on commit 5cdd3f4

Please sign in to comment.