How can I do an advanced management of PyModules #2080
-
Hi, we're trying to do a sandboxing of python code within python, with a thin layer of Rust as a glue. In particular we want to have multiple python files and load them into python (passing through rust) in a sandbox-like environment (no access to os, sys, importlib, Searching on the internet I couldn't find anything related to what I wanted to do. Examples of my desires: #[pyfunction]
fn empty_module<'py> () -> PyResult<&'py PyModule> {
let gil = Python::acquire_gil();
let py = gil.python();
let modref = PyModule::new(py, "holi")?;
Ok(modref) // I can't return bc it's referencing local gil.
} #[pyfunction]
fn get_gil() -> GILGuard{
Python::acquire_gil()
} // the trait `pyo3::callback::IntoPyCallbackOutput<_>` is not implemented for `pyo3::GILGuard`rustc(E0277) #[pyfunction]
fn import_view<'py>(
gil: &'py GILGuard, // the trait `pyo3::PyClass` is not implemented for `&pyo3::GILGuard`
name: &str,
dependencies: Vec<&PyModule>,
code: &str,
) -> PyResult<&'py PyModule> {
let py = gil.python();
let module = PyModule::new(py, name)?;
for dpendency in dependencies {
module.add_submodule(dpendency)?;
}
// I want to add code to the module
// so my imports won't fail
//
// ... and I can override "os" with an
// empty module so is no usable
Ok(module)
} Is there a way to do such a thing? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
I think you want:
and
You can always take For |
Beta Was this translation helpful? Give feedback.
-
pyo3 is not meant for sandboxing. If you want to run untrusted python code, you cannot use pyo3 to do that.
This approach doesn't work, there are many, many other things an attacker can use to break out of a simple sandbox like that. Perhaps Lua would work better for you? It is more focused towards being ran in sandboxes. |
Beta Was this translation helpful? Give feedback.
I think you want:
and
You can always take
Python
as an argument to the#[pyfunction]
- this argument doesn't really exist on the Python side, and PyO3 will fill it in for you.For
get_gil
, perhaps takingpy: Python
removes the need for it?