Skip to content

Commit f2faf92

Browse files
committed
harden: secure dynamic_imports.py
Untrusted user input in `importlib Resolves python.lang.security.audit.non-literal-import.non-literal-import
1 parent 9e4603c commit f2faf92

1 file changed

Lines changed: 5 additions & 0 deletions

File tree

‎src/openrouter/utils/dynamic_imports.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,16 @@
22

33
from importlib import import_module
44
import builtins
5+
import re
56
import sys
67

8+
_RELATIVE_MODNAME_RE = re.compile(r"^\.[A-Za-z_][A-Za-z0-9_]*$")
9+
710

811
def dynamic_import(package, modname, retries=3):
912
"""Import a module relative to package, retrying on KeyError from half-initialized modules."""
13+
if not isinstance(modname, str) or not _RELATIVE_MODNAME_RE.match(modname):
14+
raise ValueError(f"Refusing to import untrusted module name: {modname!r}")
1015
for attempt in range(retries):
1116
try:
1217
return import_module(modname, package)

0 commit comments

Comments
 (0)