-
Notifications
You must be signed in to change notification settings - Fork 6
Description
Background
Python 3.11 introduced -P flag to prevent unsafe paths in sys.path [What's New] [PEP 587] [CLI docs].
Official Definition: Prevents Python from automatically prepending potentially unsafe paths to sys.path.
Enable via:
-Pcommand-line flag [Python docs]PYTHONSAFEPATH=1environment variable [env var]sys.flags.safe_path(runtime check) [sys.flags]
Behavior [Python docs]:
python script.py: doesn't prepend script's directorypython -m module: doesn't prepend current working directorypython -c codeandpython(REPL): doesn't prepend empty string (current directory)
Design Goals
From official proposals [PEP 587] and discussions:
- Security: Prevents malicious local modules from being accidentally imported
- Path injection protection: Stops local directories from shadowing stdlib packages [CPython #95754] [Better errors PR #113769]
- Consistency: Aligns interactive environments with command-line behavior
Historical Context
GitHub issue #57684 tracked this feature request:
- Original proposal:
--mainpath/--nomainpathcommand-line options - Evolution:
-Pflag andPYTHONSAFEENV(later renamedPYTHONSAFEPATH) [BPO #13475] - Core maintainers: Victor Stinner et al.
- Implementation: [initconfig.c] [PyConfig.safe_path]
Industry Adoption
- IPython 9.7: Added
PYTHONSAFEPATHsupport [changelog] [PR #15014] - pdb: Respects safe_path behavior [PR #111762]
- IPython aligns with Python's native security without requiring separate
--ignore_cwdconfiguration
Proposal
Add -P/--safe-path flag and PYTHONSAFEPATH support to our Python execution environment. This aligns with Python standards and improves security—critical for web-based Python consoles handling untrusted code.
Why This Matters
Python's official security enhancement prevents dependency path attacks in multi-user or untrusted environments. As an online IDE, implementing this feature would protect users from module shadowing vulnerabilities.