|
| 1 | +#[cfg_attr(target_os = "linux", path = "linux.rs")] |
| 2 | +#[cfg_attr(not(target_os = "linux"), path = "unsupported.rs")] |
| 3 | +mod sandbox_impl; |
| 4 | + |
| 5 | +use pyo3::{create_exception, exceptions::PyException, prelude::*, types::PyTuple}; |
| 6 | + |
| 7 | +#[derive(Clone, Debug)] |
| 8 | +pub enum AccessFS { |
| 9 | + Read(String), |
| 10 | + ReadWrite(String), |
| 11 | + MakeReg(String), |
| 12 | + MakeDir(String), |
| 13 | +} |
| 14 | + |
| 15 | +/// Enforces access restrictions |
| 16 | +#[pyfunction(name = "restrict_access", signature=(*rules))] |
| 17 | +fn py_restrict_access(rules: &PyTuple) -> PyResult<()> { |
| 18 | + sandbox_impl::restrict_access( |
| 19 | + &rules |
| 20 | + .iter() |
| 21 | + .map(|r| Ok(r.extract::<PyAccessFS>()?.access)) |
| 22 | + .collect::<PyResult<Vec<_>>>()?, |
| 23 | + ) |
| 24 | + .map_err(|err| SandboxError::new_err(err.to_string())) |
| 25 | +} |
| 26 | + |
| 27 | +create_exception!(unblob_native.sandbox, SandboxError, PyException); |
| 28 | + |
| 29 | +#[pyclass(name = "AccessFS", module = "unblob_native.sandbox")] |
| 30 | +#[derive(Clone)] |
| 31 | +struct PyAccessFS { |
| 32 | + access: AccessFS, |
| 33 | +} |
| 34 | + |
| 35 | +impl PyAccessFS { |
| 36 | + fn new(access: AccessFS) -> Self { |
| 37 | + Self { access } |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +#[pymethods] |
| 42 | +impl PyAccessFS { |
| 43 | + #[staticmethod] |
| 44 | + fn read(dir: String) -> Self { |
| 45 | + Self::new(AccessFS::Read(dir)) |
| 46 | + } |
| 47 | + |
| 48 | + #[staticmethod] |
| 49 | + fn read_write(dir: String) -> Self { |
| 50 | + Self::new(AccessFS::ReadWrite(dir)) |
| 51 | + } |
| 52 | + |
| 53 | + #[staticmethod] |
| 54 | + fn make_reg(dir: String) -> Self { |
| 55 | + Self::new(AccessFS::MakeReg(dir)) |
| 56 | + } |
| 57 | + |
| 58 | + #[staticmethod] |
| 59 | + fn make_dir(dir: String) -> Self { |
| 60 | + Self::new(AccessFS::MakeDir(dir)) |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +pub fn init_module(py: Python, root_module: &PyModule) -> PyResult<()> { |
| 65 | + let module = PyModule::new(py, "sandbox")?; |
| 66 | + module.add_function(wrap_pyfunction!(py_restrict_access, module)?)?; |
| 67 | + module.add_class::<PyAccessFS>()?; |
| 68 | + |
| 69 | + root_module.add_submodule(module)?; |
| 70 | + |
| 71 | + let sys = PyModule::import(py, "sys")?; |
| 72 | + let modules = sys.getattr("modules")?; |
| 73 | + modules.call_method( |
| 74 | + "__setitem__", |
| 75 | + ("unblob_native.sandbox".to_string(), module), |
| 76 | + None, |
| 77 | + )?; |
| 78 | + |
| 79 | + Ok(()) |
| 80 | +} |
0 commit comments