Skip to content

IPython does not respect sys.flags.safe_path (aka, PYTHONSAFEPATH or -P) #15013

@algal

Description

@algal

Summary

IPython currently ignores Python's PYTHONSAFEPATH environment variable and -P command line flag, which were introduced in Python 3.11 to prevent potentially unsafe paths from being added to sys.path. I am suggesting IPython should respect that flag.

Current Behavior

When running PYTHONSAFEPATH=1 ipython or python -P -m IPython, IPython still adds an empty string ('') to sys.path, causing it to search the current working directory for modules.

This can lead to unintended imports of local files over installed packages. It can also introduce security concerns as described in ohmyzsh/ohmyzsh#12535

IPython has its own flag (--ignore-cwd) to avoid this issue at the moment.

Therefore, right now, the easiest way to configure ipython to respect sys.flags.safe_path, is likely to configure ipython_config.py so that one flag is driven by the other, with lines like:

import sys
c.InteractiveShellApp.ignore_cwd = sys.flags.safe_path

Expected Behavior

In addition to its own flag, IPython should also respect sys.flags.safe_pathand not add the current working directory to sys.path when the safe path mode is enabled, similar to how the existing --ignore-cwd flag works.

Proposed Solution

Modify the init_path() method in /IPython/core/shellapp.py line 259 to also check sys.flags.safe_path.

At least one other tool, pdb, also respects safe_path: python/cpython#111762

Compatibility

Since IPython requires Python ≥3.11, sys.flags.safe_path is available in all supported versions.

I've created a commit which implements this, which I am happy to submit as a PR, if the maintainers see this change as desireable? Is is algal@c5e95d1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions