|
1 | 1 | """Rendering mixin - render, render_depth, get_contacts, observation helpers.""" |
2 | 2 |
|
| 3 | +import contextlib |
3 | 4 | import io |
4 | 5 | import logging |
| 6 | +import os |
| 7 | +import tempfile |
| 8 | +from pathlib import Path |
5 | 9 | from typing import TYPE_CHECKING, Any |
6 | 10 |
|
7 | 11 | from strands_robots.simulation.mujoco.backend import ( |
|
13 | 17 |
|
14 | 18 | logger = logging.getLogger(__name__) |
15 | 19 |
|
| 20 | +# render(output_path=...) is an LLM-callable tool: the path is attacker-influenced. |
| 21 | +# Confine writes to a sandbox root, reject shell metacharacters / traversal / |
| 22 | +# symlinked targets, cap the payload size, and write atomically so a crash mid-write |
| 23 | +# cannot corrupt an existing file. See docs and the STRANDS_ROBOTS_RENDER_* env vars. |
| 24 | +_RENDER_PATH_BAD_CHARS = frozenset({";", "|", "$", "`", ">", "<", "\n", "\r", "\x00"}) |
| 25 | +_DEFAULT_MAX_RENDER_BYTES = 50 * 1024 * 1024 # 50 MB |
| 26 | + |
| 27 | + |
| 28 | +def _render_sandbox_root() -> Path: |
| 29 | + """Resolve the directory render() may write into (read at call time). |
| 30 | +
|
| 31 | + Defaults to ``~/.strands_robots/renders``; override with the |
| 32 | + ``STRANDS_ROBOTS_RENDER_ROOT`` env var. |
| 33 | + """ |
| 34 | + raw = os.getenv("STRANDS_ROBOTS_RENDER_ROOT") or str(Path.home() / ".strands_robots" / "renders") |
| 35 | + return Path(raw).expanduser().resolve(strict=False) |
| 36 | + |
| 37 | + |
| 38 | +def _max_render_bytes() -> int: |
| 39 | + """Maximum PNG payload render() will persist (``STRANDS_ROBOTS_RENDER_MAX_BYTES``).""" |
| 40 | + raw = os.getenv("STRANDS_ROBOTS_RENDER_MAX_BYTES") |
| 41 | + if not raw: |
| 42 | + return _DEFAULT_MAX_RENDER_BYTES |
| 43 | + try: |
| 44 | + val = int(raw) |
| 45 | + except ValueError as e: |
| 46 | + raise ValueError(f"invalid STRANDS_ROBOTS_RENDER_MAX_BYTES {raw!r}: not an integer") from e |
| 47 | + if val <= 0: |
| 48 | + raise ValueError(f"invalid STRANDS_ROBOTS_RENDER_MAX_BYTES {raw!r}: must be positive") |
| 49 | + return val |
| 50 | + |
| 51 | + |
| 52 | +def _validate_render_output_path(output_path: str) -> Path: |
| 53 | + """Validate and resolve an LLM-supplied render output path. |
| 54 | +
|
| 55 | + Rejects shell metacharacters, backslash (Windows-style) separators, paths |
| 56 | + that resolve outside the render sandbox root, and symlinked targets. Returns |
| 57 | + the fully-resolved destination ``Path``. |
| 58 | +
|
| 59 | + Args: |
| 60 | + output_path: Caller-supplied destination path. |
| 61 | +
|
| 62 | + Returns: |
| 63 | + The resolved, sandbox-confined destination path. |
| 64 | +
|
| 65 | + Raises: |
| 66 | + ValueError: If the path is unsafe (the caller maps this to a tool error). |
| 67 | + """ |
| 68 | + if any(b in output_path for b in _RENDER_PATH_BAD_CHARS): |
| 69 | + raise ValueError("unsafe output_path: shell metacharacters") |
| 70 | + # Backslash is not a POSIX separator, so "..\..\etc" would survive a |
| 71 | + # "/"-only traversal check. Reject it outright rather than guess intent. |
| 72 | + if "\\" in output_path: |
| 73 | + raise ValueError("unsafe output_path: backslash separators not allowed") |
| 74 | + if not output_path.strip(): |
| 75 | + raise ValueError("unsafe output_path: empty") |
| 76 | + |
| 77 | + raw = Path(output_path).expanduser() |
| 78 | + # Refuse to follow a symlink planted at the target (arbitrary-write vector). |
| 79 | + if raw.is_symlink(): |
| 80 | + raise ValueError(f"output_path {output_path!r} is a symlink - refusing to follow") |
| 81 | + |
| 82 | + # resolve() normalizes "..", expands the chain, and follows any intermediate |
| 83 | + # symlinks, so the sandbox check below sees the true on-disk destination. |
| 84 | + resolved = raw.resolve(strict=False) |
| 85 | + |
| 86 | + allow_abs = (os.getenv("STRANDS_ROBOTS_RENDER_ALLOW_ABS") or "").strip().lower() in ("1", "true", "yes") |
| 87 | + if not allow_abs: |
| 88 | + root = _render_sandbox_root() |
| 89 | + try: |
| 90 | + resolved.relative_to(root) |
| 91 | + except ValueError as e: |
| 92 | + raise ValueError( |
| 93 | + f"output_path {resolved} is outside the render sandbox {root} " |
| 94 | + "(set STRANDS_ROBOTS_RENDER_ALLOW_ABS=1 to allow absolute paths)" |
| 95 | + ) from e |
| 96 | + return resolved |
| 97 | + |
| 98 | + |
| 99 | +def _atomic_write_png(path: Path, data: bytes) -> None: |
| 100 | + """Write ``data`` to ``path`` atomically with restrictive permissions. |
| 101 | +
|
| 102 | + Writes to a temp file in the destination directory then ``os.replace``s it |
| 103 | + into place, so a crash mid-write cannot truncate or corrupt an existing file |
| 104 | + at ``path``. Created directories are ``0o700`` and the final file is ``0o600`` |
| 105 | + (owner-only; the render sandbox is private to the running user). |
| 106 | + """ |
| 107 | + parent = path.parent |
| 108 | + parent_existed = parent.exists() |
| 109 | + parent.mkdir(parents=True, exist_ok=True) |
| 110 | + if not parent_existed: |
| 111 | + with contextlib.suppress(OSError): |
| 112 | + os.chmod(parent, 0o700) |
| 113 | + |
| 114 | + fd, tmp = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=parent) |
| 115 | + try: |
| 116 | + with os.fdopen(fd, "wb") as f: |
| 117 | + f.write(data) |
| 118 | + os.replace(tmp, path) |
| 119 | + except BaseException: |
| 120 | + with contextlib.suppress(OSError): |
| 121 | + os.unlink(tmp) |
| 122 | + raise |
| 123 | + os.chmod(path, 0o600) |
| 124 | + |
| 125 | + |
| 126 | +def _save_render_png(output_path: str, png_bytes: bytes) -> str: |
| 127 | + """Validate ``output_path``, enforce the size cap, and atomically persist ``png_bytes``. |
| 128 | +
|
| 129 | + Returns the resolved saved path as a string. |
| 130 | +
|
| 131 | + Raises: |
| 132 | + ValueError: On an unsafe path or an oversized payload. |
| 133 | + """ |
| 134 | + safe = _validate_render_output_path(output_path) |
| 135 | + max_bytes = _max_render_bytes() |
| 136 | + if len(png_bytes) > max_bytes: |
| 137 | + raise ValueError(f"png is {len(png_bytes)} bytes, exceeds limit {max_bytes}") |
| 138 | + _atomic_write_png(safe, png_bytes) |
| 139 | + return str(safe) |
| 140 | + |
16 | 141 |
|
17 | 142 | class RenderingMixin: |
18 | 143 | """Rendering + observation helpers mixed into ``Simulation``. |
@@ -580,10 +705,19 @@ def render( |
580 | 705 | """Render a camera view to a PNG image. |
581 | 706 |
|
582 | 707 | When ``output_path`` is given the PNG is ALSO written to that file path |
583 | | - (parent dirs created) and the saved path is reported in the ``json`` |
584 | | - block as ``saved_path`` and in the text summary. This lets an agent (or |
585 | | - a human) persist a render for independent verification instead of only |
586 | | - receiving the bytes inline. |
| 708 | + and the saved path is reported in the ``json`` block as ``saved_path`` |
| 709 | + and in the text summary. This lets an agent (or a human) persist a render |
| 710 | + for independent verification instead of only receiving the bytes inline. |
| 711 | +
|
| 712 | + ``output_path`` is treated as untrusted (LLM-callable tool): writes are |
| 713 | + confined to the render sandbox (``STRANDS_ROBOTS_RENDER_ROOT``, default |
| 714 | + ``~/.strands_robots/renders``); paths with shell metacharacters, |
| 715 | + backslash separators, ``..`` escapes, or a symlinked target, and PNGs |
| 716 | + larger than ``STRANDS_ROBOTS_RENDER_MAX_BYTES`` (default 50 MB) are |
| 717 | + rejected with ``status=error``. Set ``STRANDS_ROBOTS_RENDER_ALLOW_ABS=1`` |
| 718 | + to permit absolute paths outside the sandbox. The write is atomic |
| 719 | + (temp file + ``os.replace``), so a crash mid-write cannot corrupt an |
| 720 | + existing file at the destination. |
587 | 721 |
|
588 | 722 |
|
589 | 723 | Returns an agent-tool dict with ``status`` and a ``content`` list; on |
@@ -675,20 +809,12 @@ def render( |
675 | 809 |
|
676 | 810 | saved_path: str | None = None |
677 | 811 | if output_path: |
678 | | - import os as _os |
679 | | - |
680 | | - # Validate against shell/path-traversal injection (LLM-supplied). |
681 | | - bad = {";", "|", "$", "`", ">", "<", "\n", "\r", "\x00"} |
682 | | - if any(b in output_path for b in bad) or ".." in output_path.split("/"): |
683 | | - return { |
684 | | - "status": "error", |
685 | | - "content": [{"text": f"render: unsafe output_path {output_path!r}"}], |
686 | | - } |
687 | | - _dir = _os.path.dirname(_os.path.abspath(output_path)) |
688 | | - _os.makedirs(_dir, exist_ok=True) |
689 | | - with open(output_path, "wb") as _f: |
690 | | - _f.write(png_bytes) |
691 | | - saved_path = _os.path.abspath(output_path) |
| 812 | + # output_path is LLM-supplied: validate against traversal / |
| 813 | + # symlink / oversize and write atomically (see _save_render_png). |
| 814 | + try: |
| 815 | + saved_path = _save_render_png(output_path, png_bytes) |
| 816 | + except ValueError as e: |
| 817 | + return {"status": "error", "content": [{"text": f"render: {e}"}]} |
692 | 818 |
|
693 | 819 | summary = f"{w}x{h} from '{label}' at t={self._world.sim_time:.3f}s" |
694 | 820 | if saved_path: |
|
0 commit comments