Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 29 additions & 5 deletions crates/bashkit-python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,18 @@ use tokio::sync::Mutex;
// ============================================================================

/// Convert serde_json::Value → Py<PyAny>
const MAX_NESTING_DEPTH: usize = 64;

fn json_to_py(py: Python<'_>, val: &serde_json::Value) -> PyResult<Py<PyAny>> {
json_to_py_inner(py, val, 0)
}

fn json_to_py_inner(py: Python<'_>, val: &serde_json::Value, depth: usize) -> PyResult<Py<PyAny>> {
if depth > MAX_NESTING_DEPTH {
return Err(pyo3::exceptions::PyValueError::new_err(
"JSON nesting depth exceeds maximum of 64",
));
}
match val {
serde_json::Value::Null => Ok(py.None()),
serde_json::Value::Bool(b) => Ok(b.into_pyobject(py)?.to_owned().into_any().unbind()),
Expand All @@ -38,23 +49,36 @@ fn json_to_py(py: Python<'_>, val: &serde_json::Value) -> PyResult<Py<PyAny>> {
serde_json::Value::Array(arr) => {
let items: Vec<Py<PyAny>> = arr
.iter()
.map(|v| json_to_py(py, v))
.map(|v| json_to_py_inner(py, v, depth + 1))
.collect::<PyResult<_>>()?;
Ok(PyList::new(py, &items)?.into_any().unbind())
}
serde_json::Value::Object(map) => {
let dict = PyDict::new(py);
for (k, v) in map {
dict.set_item(k, json_to_py(py, v)?)?;
dict.set_item(k, json_to_py_inner(py, v, depth + 1)?)?;
}
Ok(dict.into_any().unbind())
}
}
}

/// Convert Py<PyAny> → serde_json::Value (for schema dicts)
#[allow(clippy::only_used_in_recursion)]
fn py_to_json(py: Python<'_>, obj: &Bound<'_, pyo3::PyAny>) -> PyResult<serde_json::Value> {
py_to_json_inner(py, obj, 0)
}

#[allow(clippy::only_used_in_recursion)]
fn py_to_json_inner(
py: Python<'_>,
obj: &Bound<'_, pyo3::PyAny>,
depth: usize,
) -> PyResult<serde_json::Value> {
if depth > MAX_NESTING_DEPTH {
return Err(pyo3::exceptions::PyValueError::new_err(
"Python object nesting depth exceeds maximum of 64",
));
}
if obj.is_none() {
return Ok(serde_json::Value::Null);
}
Expand All @@ -73,15 +97,15 @@ fn py_to_json(py: Python<'_>, obj: &Bound<'_, pyo3::PyAny>) -> PyResult<serde_js
if let Ok(list) = obj.cast::<PyList>() {
let arr: Vec<serde_json::Value> = list
.iter()
.map(|item| py_to_json(py, &item))
.map(|item| py_to_json_inner(py, &item, depth + 1))
.collect::<PyResult<_>>()?;
return Ok(serde_json::Value::Array(arr));
}
if let Ok(dict) = obj.cast::<PyDict>() {
let mut map = serde_json::Map::new();
for (k, v) in dict.iter() {
let key: String = k.extract()?;
map.insert(key, py_to_json(py, &v)?);
map.insert(key, py_to_json_inner(py, &v, depth + 1)?);
}
return Ok(serde_json::Value::Object(map));
}
Expand Down
12 changes: 12 additions & 0 deletions crates/bashkit-python/tests/test_bashkit.py
Original file line number Diff line number Diff line change
Expand Up @@ -914,3 +914,15 @@ def test_scripted_tool_rapid_sync_calls_no_resource_exhaustion():
r = tool.execute_sync("ping")
assert r.exit_code == 0
assert r.stdout.strip() == "pong"


def test_deeply_nested_schema_rejected():
"""py_to_json rejects nesting deeper than 64 levels."""
# Build a dict nested 70 levels deep
nested = {"value": "leaf"}
for _ in range(70):
nested = {"child": nested}

tool = ScriptedTool("deep")
with pytest.raises(ValueError, match="nesting depth"):
tool.add_tool("deep", "Deep", callback=lambda p, s=None: "", schema=nested)
Loading