Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: ask before ffmpeg or pandoc write outside the sandbox (#13942)

Nilay5e3b44dd89e8
diff --git a/studio/backend/core/inference/tool_path_approval.py b/studio/backend/core/inference/tool_path_approval.py
index 54eff400935..4bd47f6216e 100644
--- a/studio/backend/core/inference/tool_path_approval.py
+++ b/studio/backend/core/inference/tool_path_approval.py
@@ -628,8 +628,7 @@ def _credential_under_silent_root(candidate: str) -> bool:
return "/auth/" in unified + "/"
-# Commands whose file operands are READ. Deliberately narrow: only names whose operands are unambiguously paths, so a
-# command this scan does not model contributes nothing rather than a guess.
+# Commands whose file operands are READ. Deliberately narrow: only names whose operands are unambiguously paths.
# `zcat --help`: "Usage: zcat [OPTION]... [FILE]...", uncompressing each to stdout. The
# whole family reads the file it is given exactly as `cat` does.
# `iconv --help`: "Usage: iconv [OPTION...] [FILE...]", so a bare operand is a file it reads.
@@ -1216,13 +1215,130 @@ _REDIR_HEREDOC_RE = re.compile(r"^\d*<<<?-?$")
_SHELL_ASSIGN_TOKEN_RE = re.compile(r"^[A-Za-z_]\w*=")
+# `cmd /c`, `robocopy a b /E`, find's `\;`: a switch, not a path; a dot keeps `/recording.wav` a file.
+_BARE_SWITCH_RE = re.compile(r"^[/\\][^/\\.]*$")
+
+
+# `pandoc --help`: "-o FILE, --output=FILE Write output to FILE", as for most unlisted tools.
+_OUTPUT_FILE_FLAGS = frozenset({"-o", "--output"})
+
+_COMMAND_OUTPUT_FLAGS = {"pandoc": frozenset({"--extract-media", "--log"})}
+_MAGICK_OUTPUT_FLAGS = frozenset({"-write", "+write"})
+
+# ffmpeg's tee muxer: `[f=mp4]/out/a.mp4|b.mkv`.
+_FFMPEG_TEE_OPTIONS_RE = re.compile(r"^\[[^\]]*\]")
+
+# ffmpeg: any absolute operand not read by an `_FFMPEG_READ_VALUE_FLAGS` option is an output, since
+# its file-writing options (`-progress`, `-stats_enc_pre`, ...) are too many to list.
+# `compare image image [difference]`; `mogrify` overwrites its inputs or writes into `-path`.
+_POSITIONAL_OUTPUT_COMMANDS = {
+ "ffmpeg": "not_option_value",
+ "magick": "last",
+ "convert": "last",
+ "composite": "last",
+ "montage": "last",
+ "mogrify": "all",
+ "compare": "third_image",
+}
+_MAGICK_VERB_OUTPUTS = {
+ "identify": None,
+ "display": None,
+ "animate": None,
+ "compare": "third_image",
+ "mogrify": "all",
+}
+
+# Unlisted flags count as valueless, so a missed valued flag can only add a prompt.
+_MAGICK_COMPARE_VALUE_FLAGS = dict.fromkeys(
+ "-alpha -authenticate -background -channel -colorspace -compose -compress -debug -decipher "
+ "-define -density -depth -dissimilarity-threshold -encipher -extract -format -fuzz -gravity "
+ "-highlight-color -interlace -log -lowlight-color -metric -precision -quality -read-mask "
+ "-sampling-factor -seed -similarity-threshold -size -type -virtual-pixel -write-mask".split(),
+ 1,
+) | {"-limit": 2, "-set": 2}
+
+# Plus `-/opt FILE`, which loads an option's value from FILE.
+_FFMPEG_READ_VALUE_FLAGS = frozenset(
+ "-i -filter_script -filter_complex_script -attach -fpre -vpre -apre -spre -pre "
+ "-hls_key_info_file".split()
+)
+
+_MAGICK_COMMANDS = frozenset(
+ "magick convert composite montage mogrify compare display animate identify".split()
+)
+# `png:/out.png`
+_MAGICK_CODER_PREFIX_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_-]+:(?=[/\\~]|[A-Za-z]:)")
+
+
+def _segment_runs_magick(segment) -> bool:
+ command = next((t for t in segment if not _SHELL_ASSIGN_TOKEN_RE.match(t)), "")
+ return _tools._token_command_base(command) in _MAGICK_COMMANDS
+
+
+def _magick_images(args) -> "list[str]":
+ images, skip = [], 0
+ for arg in args:
+ if arg in ("(", ")"):
+ continue
+ if skip:
+ skip -= 1
+ elif len(arg) > 1 and arg[0] in "-+":
+ skip = _MAGICK_COMPARE_VALUE_FLAGS.get(arg, 0) if arg[0] == "-" else 0
+ else:
+ images.append(arg)
+ return images
+
+
+def _unlisted_command_operands(command, args) -> "list[tuple[str, bool]]":
+ outputs = _POSITIONAL_OUTPUT_COMMANDS.get(command)
+ if command == "magick" and args and args[0] in _MAGICK_VERB_OUTPUTS:
+ outputs = _MAGICK_VERB_OUTPUTS[args[0]]
+ images = _magick_images(args[1:] if command == "magick" else args)
+ output_flags = _OUTPUT_FILE_FLAGS | _COMMAND_OUTPUT_FLAGS.get(command, frozenset())
+ if command in _MAGICK_COMMANDS:
+ output_flags |= _MAGICK_OUTPUT_FLAGS
+ operands = []
+ writes_next = False
+ for index, arg in enumerate(args):
+ writing, writes_next = writes_next, False
+ value = arg
+ if arg in output_flags or arg.split(":")[0] in output_flags:
+ writes_next = True
+ continue
+ if arg.startswith("-"):
+ flag, _, value = arg.partition("=")
+ if not value and not arg.startswith("--"):
+ flag, value = arg[:2], arg[2:]
+ writing = flag in output_flags
+ elif outputs == "all":
+ writing = True
+ elif outputs == "last":
+ writing = writing or index == len(args) - 1
+ elif outputs == "third_image":
+ writing = writing or (len(images) >= 3 and index == len(args) - 1)
+ elif outputs == "not_option_value":
+ previous = args[index - 1] if index else ""
+ reads = previous.split(":")[0] in _FFMPEG_READ_VALUE_FLAGS or previous.startswith("-/")
+ writing = writing or not reads
+ if command in _MAGICK_COMMANDS and value.lower()[:5] != "file:":
+ value = _MAGICK_CODER_PREFIX_RE.sub("", value, count = 1)
+ values = [value]
+ if command == "ffmpeg" and "|" in value:
+ values = [_FFMPEG_TEE_OPTIONS_RE.sub("", part) for part in value.split("|")]
+ for value in values:
+ if _looks_absolute(value) and (writing or not _BARE_SWITCH_RE.match(value)):
+ operands.append((value, writing))
+ elif not _looks_absolute(value):
+ operands.extend((path, writing) for path in _substitution_operand_paths(value))
+ return operands
+
+
def _terminal_path_operands(tokens, text = None) -> "list[tuple[str, bool]]":
"""Absolute file operands a command list touches, as ``(path, writing)``.
- Only commands in the tables above contribute operands, and only tokens that look absolute are
- returned -- a relative operand lands in the session workdir, and a flag value that is not a path
- (``head -n 5``) cannot look absolute. Redirection targets are included whichever command owns
- them, since ``> /abs/file`` truncates that file regardless.
+ Only tokens that look absolute are returned -- a relative operand lands in the session workdir,
+ and a flag value that is not a path (``head -n 5``) cannot look absolute. Redirection targets
+ are included whichever command owns them, since ``> /abs/file`` truncates that file regardless.
"""
# Every operand this can report is absolute in some spelling, and each of those spellings needs
# one of these characters: a POSIX root or tilde, a UNC or Windows separator, or the colon of a
@@ -1269,6 +1385,10 @@ def _terminal_path_operands(tokens, text = None) -> "list[tuple[str, bool]]":
if _looks_absolute(token):
operands.append((token, writing))
continue
+ # `magick \( in.png -resize 50% \) out.png`: an image stack, not a subshell.
+ if token in ("(", ")") and _segment_runs_magick(segment):
+ segment.append(token)
+ continue
if _looks_separator_for_paths(token):
flush()
continue
@@ -1611,7 +1731,9 @@ def _segment_path_operands(segment) -> "list[tuple[str, bool]]":
read_cmd = True
dest_last = command in _PATH_DEST_LAST_COMMANDS
if not (read_cmd or write_cmd or dest_last or flag_only):
- return launched
+ if command in _classified_terminal_commands():
+ return launched
+ return launched + _unlisted_command_operands(command, args)
inplace = command in ("sed", "perl") and any(
arg in _SED_INPLACE_FLAGS or arg.startswith("--in-place") or _clusters_inplace(arg)
for arg in args
@@ -1864,6 +1986,8 @@ def _command_base_writes(base: str) -> bool:
or base in _PATH_DEST_LAST_COMMANDS
or base in _PATH_ARCHIVE_COMMANDS
or base in _EXTRA_WRITE_COMMANDS
+ or base in _POSITIONAL_OUTPUT_COMMANDS
+ or base in _COMMAND_OUTPUT_FLAGS
)
@@ -3025,7 +3149,7 @@ def _python_path_operands(tree) -> "list[tuple[str, bool]]":
# once the scan has classified the child command, `subprocess.run(["echo", "/home/x"])`
# is the same nothing `echo /home/x` is at a terminal, and prompting on one and not the
# other was a difference with no reason behind it.
- if not from_command and not any(
+ if not any(
_token_command_base(word) in _classified_terminal_commands() for word in words
):
operands.extend((word, False) for word in words if _looks_absolute(word))
diff --git a/studio/backend/tests/test_permission_mode.py b/studio/backend/tests/test_permission_mode.py
index 7caca8d0a60..7624fd87daf 100644
--- a/studio/backend/tests/test_permission_mode.py
+++ b/studio/backend/tests/test_permission_mode.py
@@ -3787,9 +3787,51 @@ _OUTSIDE_SANDBOX_INDIRECT_TERMINAL = (
# `--output-dir` is where `-O` puts the download, and `-O` itself contributes no operand.
"curl --output-dir=/media/kuser/MEDIA_SSD/private -O https://example.com/payload",
"wget --directory-prefix=/media/kuser/MEDIA_SSD/private https://example.com/payload",
+ f"ffmpeg -y -i in.wav {_OUTSIDE_DIR}/interview.wav",
+ f"pandoc notes.md -o {_OUTSIDE_DIR}/report.docx",
+ f"pandoc notes.md --output={_OUTSIDE_DIR}/report.docx",
+ f"magick in.png {_OUTSIDE_DIR}/photo.png",
+ r"ffmpeg -y -i in.wav C:\Users\alice\Documents\interview.wav",
+ f"pandoc notes.md -o{_OUTSIDE_DIR}/report.docx",
+ "pandoc notes.md -o /opt/report.docx",
+ "pandoc notes.md --output=/usr/share/doc/report.docx",
+ "ffmpeg -y -i in.wav /usr/share/sounds/out.wav",
+ "magick in.png /usr/share/pixmaps/photo.png",
+ "pandoc notes.md -o /report.docx",
+ "ffmpeg -y -i in.wav /report.wav",
+ "magick in.png -write /usr/share/pixmaps/mid.png out.png",
+ "convert in.png +write /usr/share/pixmaps/mid.png out.png",
+ "pandoc in.docx --extract-media=/usr/share/doc/assets -o out.md",
+ "pandoc in.docx --extract-media /usr/share/doc/assets -o out.md",
+ "pandoc in.md --log=/usr/share/doc/log.json -o out.html",
+ "ffmpeg -i in.wav -passlogfile /usr/share/doc/pass out.mp4",
+ "ffmpeg -i in.wav -y /out.wav",
+ "ffmpeg -i in.wav -shortest /usr/share/sounds/out.wav",
+ "magick compare a.png b.png /usr/share/pixmaps/diff.png",
+ "magick compare -metric AE /usr/share/pixmaps/a.png /usr/share/pixmaps/b.png /usr/share/pixmaps/d.png",
+ "mogrify -resize 50% /usr/share/pixmaps/a.png",
+ "magick mogrify -path /usr/share/pixmaps -resize 50% a.png",
+ "cd /usr/share/sounds && ffmpeg -f lavfi -i anullsrc -t 1 out.wav",
+ "cd /usr/share/doc && pandoc notes.md -o report.docx",
+ "ffmpeg -i in.mp4 -f hls -hls_segment_filename /usr/share/chunk%03d.ts playlist.m3u8",
+ "ffmpeg -i in.mp4 -f segment -segment_list /usr/share/doc/list.csv out%03d.ts",
+ "ffmpeg -i /recording.wav out.wav",
+ "compare a.png b.png /usr/share/pixmaps/diff.png",
+ "composite over.png base.png /usr/share/pixmaps/out.png",
+ "ffmpeg -i in.mp4 -stats_enc_pre /usr/share/doc/encode.log out.mp4",
+ "ffmpeg -i in.mp4 -benchmark /usr/share/sounds/out.mp4 -f null -",
+ "compare -respect-parentheses a.png b.png /usr/share/pixmaps/diff.png",
+ "magick in.png png:/usr/share/pixmaps/out.png",
+ "magick in.png PNG32:/home/alice/out.png",
+ 'pandoc notes.md -o "$(printf /usr/share/doc/report.docx)"',
+ "ffmpeg -i in.mp4 -map 0 -c copy -f tee '[f=mp4]/usr/share/doc/a.mp4|out.mkv'",
+ "display input.png -write /usr/share/pixmaps/copy.png",
+ r"magick \( in.png -resize 50% \) /usr/share/pixmaps/out.png",
+ r"convert in.png \( mask.png -negate \) -composite /usr/share/pixmaps/out.png",
)
_OUTSIDE_SANDBOX_INDIRECT_PYTHON = (
+ "import subprocess\nsubprocess.run(['ffmpeg', '-i', '/dev/zero', '/report.wav'])",
# The filesystem root is silent for a LISTING, not for a walk that descends the whole host.
"import os\nfor r, d, f in os.walk('/'):\n print(f)",
# `tempfile` creators write into `dir` when it is given.
@@ -4123,6 +4165,35 @@ _INDIRECT_BENIGN_TERMINAL = (
"unzip a.zip",
"cat ~/notes.txt",
"mkdir ~/.config/myapp",
+ "ffmpeg -y -i in.wav out.wav",
+ "ffprobe /usr/share/sounds/alert.wav",
+ "ffmpeg -i /usr/share/sounds/alert.wav out.wav",
+ "magick /usr/share/pixmaps/logo.png out.png",
+ "pandoc notes.md --output=report.docx",
+ "export PATH=/home/alice/bin:$PATH",
+ "robocopy src dst /E",
+ "magick in.png -resize 50% out.png",
+ "pandoc in.docx --extract-media=media -o out.md",
+ "magick identify /usr/share/pixmaps/logo.png",
+ "ffmpeg -filter_complex_script /usr/share/doc/graph.txt -i in.wav out.wav",
+ "ffmpeg -i in.mp4 -filter_script:v /usr/share/doc/f.txt out.mp4",
+ "ffmpeg -i in.mp4 -attach /usr/share/fonts/a.ttf out.mkv",
+ "ffmpeg -i in.mp4 -/filter_complex /usr/share/doc/g.txt out.mp4",
+ "ffmpeg -fpre /usr/share/ffmpeg/libvpx-360p.ffpreset -i in.y4m out.webm",
+ "ffmpeg -vpre /usr/share/ffmpeg/x.ffpreset -i in.y4m out.webm",
+ "magick compare /usr/share/pixmaps/a.png /usr/share/pixmaps/b.png",
+ "magick display /usr/share/pixmaps/logo.png",
+ "magick animate /usr/share/pixmaps/a.gif",
+ "magick compare -dissimilarity-threshold 0.1 /usr/share/pixmaps/a.png /usr/share/pixmaps/b.png",
+ "magick compare -metric AE /usr/share/pixmaps/a.png /usr/share/pixmaps/b.png null:",
+ "mogrify -resize 50% a.png",
+ "compare /usr/share/pixmaps/a.png /usr/share/pixmaps/b.png",
+ "compare -metric AE /usr/share/pixmaps/a.png /usr/share/pixmaps/b.png null:",
+ "cd /usr/share/sounds && ffprobe alert.wav",
+ "magick compare -fuzz 5% -metric AE /usr/share/pixmaps/a.png /usr/share/pixmaps/b.png",
+ "magick png:/usr/share/pixmaps/a.png out.jpg",
+ "ffmpeg -i in.mp4 -map 0 -c copy -f tee '[f=mp4]a.mp4|out.mkv'",
+ r"magick \( /usr/share/pixmaps/a.png -resize 50% \) out.png",
)
_INDIRECT_BENIGN_PYTHON = (