]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-98354: Add unicode check for 'name' attribute in _imp_create_builtin (GH-98412)
authorchgnrdv <52372310+chgnrdv@users.noreply.github.com>
Thu, 20 Oct 2022 00:25:10 +0000 (03:25 +0300)
committerGitHub <noreply@github.com>
Thu, 20 Oct 2022 00:25:10 +0000 (17:25 -0700)
Fixes #98354

Lib/test/test_imp.py
Misc/NEWS.d/next/Core and Builtins/2022-10-19-18-03-28.gh-issue-98354.GRGta3.rst [new file with mode: 0644]
Python/import.c

index 35b6afa91ebd4f804fbbd245b605b28445ab0afe..446e913e5bf3837b3cac8a4ec357c5a5bff8f79f 100644 (file)
@@ -378,6 +378,40 @@ class ImportTests(unittest.TestCase):
             mod = imp.load_module('mymod', file, path, description)
         self.assertEqual(mod.x, 42)
 
+    def test_issue98354(self):
+        # _imp.create_builtin should raise TypeError
+        # if 'name' attribute of 'spec' argument is not a 'str' instance
+
+        create_builtin = support.get_attribute(_imp, "create_builtin")
+
+        class FakeSpec:
+            def __init__(self, name):
+                self.name = self
+        spec = FakeSpec("time")
+        with self.assertRaises(TypeError):
+            create_builtin(spec)
+
+        class FakeSpec2:
+            name = [1, 2, 3, 4]
+        spec = FakeSpec2()
+        with self.assertRaises(TypeError):
+            create_builtin(spec)
+
+        import builtins
+        class UnicodeSubclass(str):
+            pass
+        class GoodSpec:
+            name = UnicodeSubclass("builtins")
+        spec = GoodSpec()
+        bltin = create_builtin(spec)
+        self.assertEqual(bltin, builtins)
+
+        class UnicodeSubclassFakeSpec(str):
+            def __init__(self, name):
+                self.name = self
+        spec = UnicodeSubclassFakeSpec("builtins")
+        bltin = create_builtin(spec)
+        self.assertEqual(bltin, builtins)
 
 class ReloadTests(unittest.TestCase):
 
diff --git a/Misc/NEWS.d/next/Core and Builtins/2022-10-19-18-03-28.gh-issue-98354.GRGta3.rst b/Misc/NEWS.d/next/Core and Builtins/2022-10-19-18-03-28.gh-issue-98354.GRGta3.rst
new file mode 100644 (file)
index 0000000..a600f3e
--- /dev/null
@@ -0,0 +1 @@
+Added unicode check for ``name`` attribute of ``spec`` argument passed in :func:`_imp.create_builtin` function.
index 698ef37ce0a1311e8035c559ebd577532456db5d..9d35d261774211bf44ce7293bb8a6239ba49ef44 100644 (file)
@@ -1021,6 +1021,14 @@ _imp_create_builtin(PyObject *module, PyObject *spec)
         return NULL;
     }
 
+    if (!PyUnicode_Check(name)) {
+        PyErr_Format(PyExc_TypeError,
+                     "name must be string, not %.200s",
+                     Py_TYPE(name)->tp_name);
+        Py_DECREF(name);
+        return NULL;
+    }
+
     PyObject *mod = create_builtin(tstate, name, spec);
     Py_DECREF(name);
     return mod;