Skip to content

Commit e1bd0cd

Browse files
gh-145058: Add input validation to _PyImport_LazyImportModuleLevelObject (#145068)
1 parent 0499a0c commit e1bd0cd

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

Lib/test/test_import/test_lazy_imports.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,15 @@ def test_dunder_lazy_import_used(self):
393393
import test.test_import.data.lazy_imports.dunder_lazy_import_used
394394
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
395395

396+
def test_dunder_lazy_import_invalid_arguments(self):
397+
"""__lazy_import__ should reject invalid arguments."""
398+
for invalid_name in (b"", 123, None):
399+
with self.assertRaises(TypeError):
400+
__lazy_import__(invalid_name)
401+
402+
with self.assertRaises(ValueError):
403+
__lazy_import__("sys", level=-1)
404+
396405
def test_dunder_lazy_import_builtins(self):
397406
"""__lazy_import__ should use module's __builtins__ for __import__."""
398407
from test.test_import.data.lazy_imports import dunder_lazy_import_builtins
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a crash when :func:`!__lazy_import__` is passed a non-string argument,
2+
by raising an :exc:`TypeError` instead.

Python/import.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4468,6 +4468,17 @@ _PyImport_LazyImportModuleLevelObject(PyThreadState *tstate,
44684468
PyObject *globals, PyObject *locals,
44694469
PyObject *fromlist, int level)
44704470
{
4471+
assert(name != NULL);
4472+
if (!PyUnicode_Check(name)) {
4473+
_PyErr_Format(tstate, PyExc_TypeError,
4474+
"module name must be a string, got %T", name);
4475+
return NULL;
4476+
}
4477+
if (level < 0) {
4478+
_PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
4479+
return NULL;
4480+
}
4481+
44714482
PyObject *abs_name = get_abs_name(tstate, name, globals, level);
44724483
if (abs_name == NULL) {
44734484
return NULL;

0 commit comments

Comments
 (0)