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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
fix(studio): prevent terminal tool hangs in credential scan (#12048) (#12087)
Sourav Rajvi1499c155cdf2
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex d0629caae26..0e5c4ea2007 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -3243,8 +3243,9 @@ def _assignment_is_a_command_prefix(text: str, value_start: int) -> bool:elif char in " \t;&|\n":breakindex += 1- following = text[index:].lstrip(" \t")- return bool(following) and following[0] not in ";&|\n"+ while index < len(text) and text[index] in " \t":+ index += 1+ return index < len(text) and text[index] not in ";&|\n"def _assignment_is_inert(text: str, index: int) -> bool:@@ -3275,6 +3276,31 @@ def _assignment_is_inert(text: str, index: int) -> bool:return bool(quote) or depth > 0+def _assignment_inert_states(text: str) -> "list[bool]":+ """`_assignment_is_inert(text, i)` for every i in one pass (index len(text) included)."""+ states = []+ quote = ""+ escaped = False+ depth = 0+ for character in text:+ states.append(bool(quote) or depth > 0)+ if escaped:+ escaped = False+ elif character == "\\" and quote != "'":+ escaped = True+ elif quote:+ if character == quote:+ quote = ""+ elif character in "'\"":+ quote = character+ elif character == "(":+ depth += 1+ elif character == ")":+ depth = max(depth - 1, 0)+ states.append(bool(quote) or depth > 0)+ return states++def _rebinds_the_studio_home_first(text: str) -> bool:"""True when *text* assigns a studio home variable BEFORE any use of it.@@ -3972,6 +3998,9 @@ def _references_studio_credential_here(text: str,workdir: "str | None",_unescaped: bool = False,+ _assign_expand_depth: int = 0,+ _quoted_assignments: bool = False,+ _positional_assignments: bool = False,) -> bool:"""`_references_studio_credential`, plus the relative paths *text* would open from *workdir*.@@ -4044,12 +4073,49 @@ def _references_studio_credential_here(# One level of indirection, `r=$STUDIO_HOME; sqlite3 "$r/auth/auth.db"`. Same substitution the# sensitive-path scan uses, and it only ADDS detections.if "$" in text:- expanded = _expand_shell_assignments(text)- # The WHOLE workdir-aware analysis, not only the literal scan: `d=../..; cd "$d"` moves the- # directory every later relative path opens from, and handing the unexpanded text to the cwd- # walk read `$d` as a directory name and never moved.- if expanded != text and _references_studio_credential_here(expanded, workdir):- return True+ # Quoted bindings scanned separately: log text shaped like an assignment must not overwrite real ones.+ quoted_modes, quote_states = (_quoted_assignments,), None+ if _assign_expand_depth == 0 and ("'" in text or '"' in text):+ quote_states = _shell_quote_states(text)+ # Both modes only differ when some assignment sits inside quotes.+ if any(quote_states[m.start(1)] for m in _SHELL_ASSIGN_RE.finditer(text)):+ quoted_modes = (False, True)+ seen = {text}+ for include_quoted in quoted_modes:+ final, positional_text, saw_prefix = _shell_assignment_expansions(+ text, include_quoted = include_quoted, quote_states = quote_states+ )+ if saw_prefix and (_assign_expand_depth == 0 or _positional_assignments):+ positional_text = _shell_assignment_expansions(+ text, include_quoted = include_quoted, quote_states = quote_states, skip_prefix = True+ )[1]+ variants = (+ ((True, positional_text), (False, final))+ if _assign_expand_depth == 0+ else (+ (+ _positional_assignments,+ positional_text if _positional_assignments else final,+ ),+ )+ )+ for positional, expanded in variants:+ if expanded in seen:+ continue+ seen.add(expanded)+ # Exhausted expansion budget fails closed: unresolved aliases may still hide the auth path.+ if _assign_expand_depth >= _MAX_SHELL_ASSIGN_EXPAND_PASSES or (+ "$" in expanded and len(expanded) > max(_MAX_TERMINAL_SCAN_CHARS, len(text))+ ):+ return True+ if _references_studio_credential_here(+ expanded,+ workdir,+ _assign_expand_depth = _assign_expand_depth + 1,+ _quoted_assignments = include_quoted,+ _positional_assignments = positional,+ ):+ return True# A `cd` earlier in the command moves where every later relative path opens from.if workdir and ("cd" in text.lower() or "pushd" in text.lower()):for offset, limit, cwd in _cwds_after_cd(workdir, text):@@ -5026,7 +5092,13 @@ _SHELL_PARAM_CASE_RE = re.compile(r"\$\{(\w+)(\^\^|,,|\^|,)\}")# Indirect expansion ${!p} yields the value of the variable *named* by $p, so x=passwd; p=x; cat /etc/${!p} builds# /etc/passwd._SHELL_PARAM_INDIRECT_RE = re.compile(r"\$\{!(\w+)\}")-_SHELL_ASSIGN_RE = re.compile(r"(?:^|[\s;&|(])([A-Za-z_]\w*)=([^\s;&|)]+)")+_SHELL_PARAM_VALUE_OP_RE = re.compile(r"\$\{([A-Za-z_]\w*)(:?)([-=+])([^{}]*)\}")+# A NAME=value word is an assignment (not an argument) after one of these characters or keywords.+_SHELL_ASSIGN_POSITION_CHARS = frozenset(";&|(\n'\"`{")+_SHELL_ASSIGN_KEYWORDS = frozenset(+ ("export", "local", "declare", "typeset", "readonly", "then", "do", "else", "{", "!", "time")+)+_SHELL_ASSIGN_RE = re.compile(r"(?:^|[\s;&|(])([A-Za-z_]\w*)=([^\s;&|)]*)")# Bash ANSI-C quoting ($'\x77' -> 'w') is expanded after this classifier, so decode $'...' bodies before the# sensitive-path scan._ANSI_C_RE = re.compile(r"\$'((?:[^'\\]|\\.)*)'")@@ -5117,6 +5189,8 @@ _SHELL_PARAM_OP_RE = re.compile(r"\$\{[A-Za-z_]\w*:?[-=+]([^{}]*)\}")# path fails closed rather than spending unbounded time. Ordinary commands are far below these bounds._MAX_PATH_SCAN_CHARS = 2048_MAX_TERMINAL_SCAN_CHARS = 4096+# Each pass doubles resolved alias hops; leftover work after the cap fails closed.+_MAX_SHELL_ASSIGN_EXPAND_PASSES = 16# A glob needs one of these to expand into anything but itself; used to skip the glob scans outright._GLOB_META_RE = re.compile(r"[?*\[]")# Where the memoised node list is parked on a parsed tree (see _tree_nodes).@@ -5286,13 +5360,59 @@ def _posix_join(parts) -> str:return out-def _expand_shell_assignments(command: str) -> str:+def _shell_assign_value_self_references(name: str, value: str) -> bool:+ """True when *value* expands *name* (VAR=$VAR), which must not feed back into itself."""+ if "$" not in value:+ return False+ if any((m.group(1) or m.group(2)) == name for m in _SHELL_VAR_RE.finditer(value)):+ return True+ return any(+ m.group(1) == name+ for pattern in (+ _SHELL_PARAM_REPL_RE,+ _SHELL_PARAM_CASE_RE,+ _SHELL_PARAM_INDIRECT_RE,+ _SHELL_PARAM_VALUE_OP_RE,+ )+ for m in pattern.finditer(value)+ )+++def _expand_shell_assignments(+ command: str,+ *,+ _include_quoted: bool = True,+ _positional: bool = False,+) -> str:"""Best-effort substitution of `NAME=value ... $NAME`, so a sensitive path split across anassignment and an argument (p=/etc; cat $p/passwd) is still visible to the scan. Also appliespattern replacement. Fail-open: only adds detections."""- env = dict(_SHELL_ASSIGN_RE.findall(command))- if not env:- return command+ final, positional, _ = _shell_assignment_expansions(command, include_quoted = _include_quoted)+ return positional if _positional else final+++def _shell_assignment_expansions(+ command: str,+ *,+ include_quoted: bool = True,+ quote_states = None,+ skip_prefix: bool = False,+) -> "tuple[str, str, bool]":+ """(last binding everywhere, binding active at each use, saw a command-prefix assignment).++ `x=/tmp cat "$x"` expands the argument with the OUTER x and only hands /tmp to the child, so with+ *skip_prefix* such assignments bind nothing; the last-binding result keeps them for the child."""+ env = {}+ saw_prefix = False+ inert_states = None++ def repl_default(m):+ name, colon, op, operand = m.groups()+ value = env.get(name)+ missing = value is None or (colon and not value.strip("'\""))+ if op == "+":+ return "" if missing else operand+ return operand if missing else valuedef repl_pattern(m):var, is_global, pat, rep = m.group(1), m.group(2), m.group(3), m.group(4)@@ -5318,10 +5438,79 @@ def _expand_shell_assignments(command: str) -> str:pointed = env.get(m.group(1))return env.get(pointed, m.group(0)) if pointed is not None else m.group(0)- command = _SHELL_PARAM_INDIRECT_RE.sub(repl_indirect, command)- command = _SHELL_PARAM_REPL_RE.sub(repl_pattern, command)- command = _SHELL_PARAM_CASE_RE.sub(repl_case, command)- return _SHELL_VAR_RE.sub(lambda m: env.get(m.group(1) or m.group(2), m.group(0)), command)+ def expand(text):+ if "$" not in text:+ return text+ text = _SHELL_PARAM_INDIRECT_RE.sub(repl_indirect, text)+ text = _SHELL_PARAM_REPL_RE.sub(repl_pattern, text)+ text = _SHELL_PARAM_CASE_RE.sub(repl_case, text)+ return _SHELL_VAR_RE.sub(lambda m: env.get(m.group(1) or m.group(2), m.group(0)), text)++ # Positional: each use sees the binding active where it stands; the last binding covers loops.+ pieces, pos = [], 0+ matches = list(_SHELL_ASSIGN_RE.finditer(command))+ # An assignment run is a command prefix only when a command word ends it: `A=1 B=2 echo $A`, not `A=1 B=2;`.+ prefix = [False] * len(matches)+ for i in range(len(matches) - 1, -1, -1):+ m = matches[i]+ if (quote_states is None or not quote_states[m.start(1)]) and (+ _assignment_is_a_command_prefix(command, m.start(2))+ ):+ chained = (+ i + 1 < len(matches) and not command[m.end(2) : matches[i + 1].start(1)].strip()+ )+ prefix[i] = prefix[i + 1] if chained else True+ # `echo x=` is an argument, not an assignment: it binds nothing, so positional skips it too.+ for i, m in enumerate(matches):+ if prefix[i] or (quote_states is not None and quote_states[m.start(1)]):+ continue+ j = m.start(1) - 1+ while j >= 0 and command[j] in " \t":+ j -= 1+ if j < 0 or command[j] in _SHELL_ASSIGN_POSITION_CHARS:+ continue+ if i and matches[i - 1].end(2) == j + 1:+ prefix[i] = prefix[i - 1]+ continue+ k = j+ while k >= 0 and command[k] not in " \t;&|(\n":+ k -= 1+ if command[k + 1 : j + 1] not in _SHELL_ASSIGN_KEYWORDS:+ prefix[i] = True+ for i, match in enumerate(matches):+ if not include_quoted and ("'" in command or '"' in command):+ if quote_states is None:+ quote_states = _shell_quote_states(command)+ if quote_states[match.start(1)]:+ continue+ var, val = match.groups()+ pieces.append(expand(command[pos : match.start(2)]))+ pieces.append(expand(val))+ pos = match.end(2)+ if prefix[i]:+ saw_prefix = True+ if skip_prefix:+ continue+ if _shell_assign_value_self_references(var, val):+ # Studio home vars stay references: `H=$H; cat "$H/auth/auth.db"` must still name the install.+ if var.upper() in _STUDIO_HOME_ENV_VARS:+ env.setdefault(var, "${" + var + "}")+ val = _SHELL_PARAM_VALUE_OP_RE.sub(repl_default, val)+ env.setdefault(var, "")+ val = expand(val)+ # `a=$a$a` repeated doubles each time: past the path cap keep the earlier binding.+ if len(val) > _MAX_PATH_SCAN_CHARS:+ continue+ # Only a scoped empty assignment (`(x=)`) keeps the outer binding; a top-level `x=` clears it.+ if not val and var in env:+ if inert_states is None:+ inert_states = _assignment_inert_states(command)+ if inert_states[match.start(1)]:+ continue+ env[var] = val+ if not env:+ return command, command, saw_prefix+ return expand(command), "".join(pieces) + expand(command[pos:]), saw_prefixdef _expand_param_defaults(command: str) -> str:diff --git a/studio/backend/tests/test_studio_auth_guard.py b/studio/backend/tests/test_studio_auth_guard.pyindex 9c72144d661..8117465f102 100644--- a/studio/backend/tests/test_studio_auth_guard.py+++ b/studio/backend/tests/test_studio_auth_guard.py@@ -2387,6 +2387,195 @@ def test_a_return_reopens_the_directory_it_lands_in(studio_home):assert tools._references_studio_credential_here(ordinary, workdir) is False, ordinary+def test_two_self_referential_assignments_in_one_quoted_string_do_not_hang(studio_home):+ workdir = str(studio_home / "sandbox" / _SESSION)+ for ordinary in (+ 'echo "hb=$hb fl=$fl"',+ "echo 'A=$A B=$B'",+ 'echo "x=$x y=$y"',+ 'echo "A=${A:-x} B=${B:-y}"',+ 'echo "A=${A^^} B=${B^^}"',+ 'echo "A=${A/x/y} B=${B/x/y}"',+ ):+ assert tools._references_studio_credential_here(ordinary, workdir) is False, ordinary+++ "value", ["../..$x", "${x}../..", "../${x}/..", "${x:-../..}", "../..${x,,}"]+)+def test_self_referential_assignments_preserve_concrete_paths(studio_home, value):+ workdir = str(studio_home / "sandbox" / _SESSION)+ command = f'unset x; x={value}; cat "$x/auth/auth.db"'+ assert tools._references_studio_credential_here(command, workdir)+ harmless = command.replace("../..", "./project").replace("../${x}/..", "./${x}/project")+ assert not tools._references_studio_credential_here(harmless, workdir)+++ "value",+ [+ "$UNSLOTH_STUDIO_HOME",+ '"$UNSLOTH_STUDIO_HOME"',+ "${UNSLOTH_STUDIO_HOME}/",+ "${UNSLOTH_STUDIO_HOME:-/tmp}",+ ],+)+def test_self_referential_studio_home_still_names_the_install(studio_home, value):+ workdir = str(studio_home / "sandbox" / _SESSION)+ command = f'UNSLOTH_STUDIO_HOME={value}; cat "$UNSLOTH_STUDIO_HOME/auth/auth.db"'+ assert tools._references_studio_credential_here(command, workdir)++[email protected]("quote", ['"', "'"])[email protected]("value", ["$x/safe", "./safe"])+def test_quoted_log_text_does_not_rebind_path_variables(studio_home, quote, value):+ workdir = str(studio_home / "sandbox" / _SESSION)+ command = f'x=../..; echo {quote}log x={value}{quote}; cat "$x/auth/auth.db"'+ assert tools._references_studio_credential_here(command, workdir)+ assert not tools._references_studio_credential_here(+ command.replace("../..", "./project"), workdir+ )++[email protected]("prefix", ["", "p=./project; "])[email protected]("reader", ["cat $p/auth/auth.db", "q=$p; cat $q/auth/auth.db"])+def test_quoted_inline_shell_assignments_still_refuse_auth(studio_home, prefix, reader):+ workdir = str(studio_home / "sandbox" / _SESSION)+ command = prefix + f"bash -c ' p=../..; {reader}'"+ assert tools._references_studio_credential_here(command, workdir)+ assert not tools._references_studio_credential_here(+ command.replace("../..", "./project"), workdir+ )++[email protected]("state", ["unset", "empty", "set"])[email protected]("op", [":-", "-", ":=", "=", ":+", "+"])+def test_self_reference_parameter_operators_follow_prior_binding(studio_home, state, op):+ workdir = str(studio_home / "sandbox" / _SESSION)+ prefix = {"unset": "unset x", "empty": "x=", "set": "x=../.."}[state]+ if op.endswith("+"):+ value = "../..${x" + op + "/safe}"+ expected = state == "unset" or (state == "empty" and op.startswith(":"))+ else:+ value = "${x" + op + "../..}"+ expected = state != "empty" or op.startswith(":")+ command = prefix + f'; x={value}; cat "$x/auth/auth.db"'+ assert tools._references_studio_credential_here(command, workdir) is expected+ assert not tools._references_studio_credential_here(+ command.replace("../..", "./project"), workdir+ )++[email protected]("hops", [14, 15, 16, 32, 128])[email protected]("read", ["cat $v{hops}/auth/auth.db", "cd $v{hops}; cat auth/auth.db"])+def test_long_alias_chains_still_refuse_the_auth_directory(studio_home, hops, read):+ workdir = str(studio_home / "sandbox" / _SESSION)+ aliases = "; ".join(f"v{i}=$v{i - 1}" for i in range(1, hops + 1))+ tail = aliases + "; " + read.format(hops = hops)+ assert tools._references_studio_credential_here("v0=../..; " + tail, workdir)+ assert not tools._references_studio_credential_here("v0=./project; " + tail, workdir)+++def test_an_unfinished_alias_scan_fails_closed(studio_home, monkeypatch):+ workdir = str(studio_home / "sandbox" / _SESSION)+ monkeypatch.setattr(tools, "_MAX_SHELL_ASSIGN_EXPAND_PASSES", 1)+ command = "v0=../..; v1=$v0; v2=$v1; v3=$v2; cat $v3/auth/auth.db"+ assert tools._references_studio_credential_here(command, workdir)+ assert not tools._references_studio_credential_here('echo "A=$A B=$B"', workdir)++[email protected]("rebind", ["x=$x/safe", "x=/tmp", "x=./project"])[email protected]("reader", ['sqlite3 "$x/auth/auth.db" .dump', 'cat "$x/auth/auth.db"'])+def test_a_later_rebinding_does_not_hide_an_earlier_read(studio_home, rebind, reader):+ workdir = str(studio_home / "sandbox" / _SESSION)+ command = f"x=../..; {reader}; {rebind}"+ assert tools._references_studio_credential_here(command, workdir)+ assert not tools._references_studio_credential_here(+ command.replace("../..", "./project"), workdir+ )++[email protected]("scope", ["(x=)", "$(x=)", "echo $(x=)", "{ (x=); }"])+def test_a_scoped_empty_assignment_keeps_the_outer_binding(studio_home, scope):+ workdir = str(studio_home / "sandbox" / _SESSION)+ command = f'x=../..; {scope}; cat "$x/auth/auth.db"'+ assert tools._references_studio_credential_here(command, workdir)+ assert not tools._references_studio_credential_here(+ command.replace("../..", "./project"), workdir+ )+++def test_a_top_level_empty_assignment_clears_the_binding(studio_home):+ workdir = str(studio_home / "sandbox" / _SESSION)+ command = 'x=./project/; x=; cat "$x../../auth/auth.db"'+ assert tools._references_studio_credential_here(command, workdir)+ assert not tools._references_studio_credential_here(command.replace("../../", "./"), workdir)+++ "command",+ [+ 'x=../..; x= cat "$x/auth/auth.db"',+ 'x=../..; x= sqlite3 "$x/auth/auth.db" "select jwt_secret from auth_user"',+ 'x=../..; x=/tmp cat "$x/auth/auth.db"',+ "x=../.. bash -c 'cat \"$x/auth/auth.db\"'",+ ],+)+def test_a_command_prefix_assignment_binds_only_the_child(studio_home, command):+ workdir = str(studio_home / "sandbox" / _SESSION)+ assert tools._references_studio_credential_here(command, workdir)+ assert not tools._references_studio_credential_here(+ command.replace("../..", "./project"), workdir+ )+++ "argument", ["echo x=", "echo x=/tmp", "env x=./project true", "grep -r x= ."]+)+def test_an_assignment_shaped_argument_binds_nothing(studio_home, argument):+ workdir = str(studio_home / "sandbox" / _SESSION)+ command = f'x=../..; {argument}; cat "$x/auth/auth.db"'+ assert tools._references_studio_credential_here(command, workdir)+ assert not tools._references_studio_credential_here(+ command.replace("../..", "./project"), workdir+ )+++ "rebind", ["x=./project", "export x=./project", "{ x=./project; }", "A=1 x=./project"]+)+def test_a_real_rebinding_still_moves_the_path(studio_home, rebind):+ workdir = str(studio_home / "sandbox" / _SESSION)+ assert not tools._references_studio_credential_here(+ f'x=../..; {rebind}; cat "$x/auth/auth.db"', workdir+ )+++def test_many_empty_self_references_scan_in_linear_time(studio_home):+ import time++ workdir = str(studio_home / "sandbox" / _SESSION)+ command = 'echo "' + " ".join(f"A{i}=$A{i}" for i in range(20000)) + '"'+ started = time.perf_counter()+ assert not tools._references_studio_credential_here(command, workdir)+ assert time.perf_counter() - started < 10+++def test_self_doubling_assignments_stay_bounded(studio_home):+ workdir = str(studio_home / "sandbox" / _SESSION)+ doubling = "a=X; " + "a=$a$a; " * 40+ assert not tools._references_studio_credential_here(doubling + "echo $a", workdir)+ assert tools._references_studio_credential_here(+ "p=../..; " + doubling + "cat $p/auth/auth.db", workdir+ )+++def test_growing_unresolved_assignments_fail_closed(studio_home):+ workdir = str(studio_home / "sandbox" / _SESSION)+ command = "a=" + "$b" * 64 + "; b=" + "$a" * 64 + "; echo $a"+ assert tools._references_studio_credential_here(command, workdir)++def test_every_home_variable_is_checked_before_the_expansion(studio_home):home = studio_home# The expansion rewrites all of the studio-home names from their last assignment, so one name