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.

Validate studio_install_id before baking it into the launcher (#9741)

Daniel Han698ddb34b0d5
diff --git a/install.ps1 b/install.ps1
index 7c54af7dc1d..ed48190c8dc 100644
--- a/install.ps1
+++ b/install.ps1
@@ -2137,6 +2137,14 @@ public static class UnslothStudioFinalPathV2
if ((Test-Path -LiteralPath $_studioIdFile) -and `
((Get-Item -LiteralPath $_studioIdFile).Length -gt 0)) {
$_studioRootId = ([System.IO.File]::ReadAllText($_studioIdFile)).Trim()
+ # Same contract as the backend and the desktop app: 64
+ # lowercase hex. -cnotmatch because -notmatch is case
+ # insensitive and would take uppercase the backend rejects.
+ # Anything else lands in a single-quoted assignment in the
+ # generated launcher, so a planted quote would be code.
+ if ($_studioRootId -cnotmatch '^[0-9a-f]{64}$') {
+ $_studioRootId = ""
+ }
}
if (-not $_studioRootId) {
$_idBytes = New-Object byte[] 32
@@ -2155,11 +2163,12 @@ public static class UnslothStudioFinalPathV2
try {
$_adoptedRootId = ([System.IO.File]::ReadAllText($_studioIdFile)).Trim()
} catch { }
- if ($_adoptedRootId) {
+ if ($_adoptedRootId -cmatch '^[0-9a-f]{64}$') {
$_studioRootId = $_adoptedRootId
} else {
- # Zero-length incumbent is an interrupted write, not an
- # id. Replace it with one atomic rename, no unlink.
+ # Zero-length or malformed is an interrupted write
+ # or a planted value, not an id: replace it with one
+ # atomic rename, no unlink.
Move-Item -LiteralPath $_idTmp -Destination $_studioIdFile -Force
}
} finally {
diff --git a/install.sh b/install.sh
index e4efcb16be3..396fc9ddff9 100755
--- a/install.sh
+++ b/install.sh
@@ -1031,6 +1031,56 @@ _smart_apt_install() {
fi
}
+# ── Helper: the studio_install_id contract ──
+# 64 lowercase hex, as in the backend (_STUDIO_INSTALL_ID_RE) and the desktop
+# app (is_valid_studio_root_id). Nothing else is an id: no backend reports it,
+# and the launcher holds it in a single-quoted assignment, so a planted value
+# with a quote in it would be launcher code.
+# Subshell bodies scope LC_ALL=C to the check: the classes below must mean the
+# same bytes in any inherited locale, and the contract is pure ASCII.
+_css_install_id_is_valid() (
+ LC_ALL=C
+ export LC_ALL
+ case "${1:-}" in
+ "" | *[!0123456789abcdef]*) return 1 ;;
+ esac
+ [ "${#1}" -eq 64 ]
+)
+
+# Echoes the id at $1 when it satisfies the contract, nothing otherwise.
+# Returns 1 when the path could not be READ, a different answer: a failed read
+# may still be sitting on a valid id.
+_css_read_valid_install_id() (
+ LC_ALL=C
+ export LC_ALL
+ # Regular files only: a FIFO here (or a symlink to one, or to a device)
+ # would park the installer on the open, waiting for a writer forever.
+ [ -f "$1" ] || return 0
+ # -s answers "no id" from stat, without a read, so an empty file we also
+ # cannot read is replaced as it was pre-validation instead of failing the
+ # install. A real id is 64 bytes and never reaches this.
+ [ -s "$1" ] || return 0
+ # A NUL cannot live in a shell variable, so command substitution drops it
+ # and <32 hex>\0<32 hex> would read back valid while the backend, which
+ # keeps the byte, reports "". Catch it by mapping NULs to a real character.
+ if [ -n "$({ tr -dc '\000' < "$1" | tr '\000' 'N'; } 2>/dev/null)" ]; then
+ return 0
+ fi
+ # Group the redirect, or the shell's own "cannot open" escapes 2>/dev/null.
+ # A failed read is reported, never flattened into "no id": permissions or a
+ # transient NFS/FUSE fault must not license a rewrite.
+ _cvi_id=$({ cat "$1"; } 2>/dev/null) || return 1
+ # Trim what the backend's .strip() trims, SURROUNDING whitespace only.
+ # Deleting interior whitespace would mint a 64-hex token out of bytes the
+ # backend reads otherwise, leaving the launcher holding an id it never
+ # reports.
+ _cvi_id=${_cvi_id#"${_cvi_id%%[![:space:]]*}"}
+ _cvi_id=${_cvi_id%"${_cvi_id##*[![:space:]]}"}
+ if _css_install_id_is_valid "$_cvi_id"; then
+ printf '%s' "$_cvi_id"
+ fi
+)
+
# ── Helper: create desktop shortcuts and launcher script ──
# Usage: create_studio_shortcuts <unsloth_exe> <os>
# Creates ~/.local/share/unsloth/launch-studio.sh (shared launcher),
@@ -1071,14 +1121,24 @@ create_studio_shortcuts() {
_css_id_dir="$STUDIO_HOME/share"
mkdir -p "$_css_id_dir"
_css_id_file="$_css_id_dir/studio_install_id"
- if [ ! -s "$_css_id_file" ]; then
+ # Reuse an existing id only when it matches the contract above: a re-run
+ # over a normal install is then a no-op, and a pre-populated custom root
+ # cannot reach the launcher.
+ # Unreadable is not malformed: in a shared root the id can be a good one
+ # owned by someone else and already reported by a running backend, so
+ # regenerating would break that install. Refuse, as this did pre-validation.
+ if ! _css_studio_root_id=$(_css_read_valid_install_id "$_css_id_file"); then
+ echo "[WARN] Cannot create launcher: cannot read $_css_id_file" >&2
+ return 1
+ fi
+ if [ -z "$_css_studio_root_id" ]; then
if [ -r /dev/urandom ]; then
_css_new_id=$(od -An -N32 -tx1 /dev/urandom 2>/dev/null | tr -d ' \n')
fi
- if [ -z "${_css_new_id:-}" ] && command -v python3 >/dev/null 2>&1; then
+ if ! _css_install_id_is_valid "${_css_new_id:-}" && command -v python3 >/dev/null 2>&1; then
_css_new_id=$(python3 -c 'import secrets; print(secrets.token_hex(32))' 2>/dev/null)
fi
- if [ -z "${_css_new_id:-}" ]; then
+ if ! _css_install_id_is_valid "${_css_new_id:-}"; then
echo "[WARN] Cannot create launcher: no entropy source for studio_install_id" >&2
return 1
fi
@@ -1090,18 +1150,28 @@ create_studio_shortcuts() {
_css_id_tmp="$_css_id_file.$$.$(printf '%.8s' "$_css_new_id").tmp"
if printf '%s' "$_css_new_id" > "$_css_id_tmp"; then
if ! ln "$_css_id_tmp" "$_css_id_file" 2>/dev/null; then
- # A usable incumbent always wins. A zero-length file is an
- # interrupted write, not an id, so replace it with one rename
- # (no unlink, so the path never vanishes). This branch also
- # covers filesystems without hard links (exFAT/FAT32).
- [ -s "$_css_id_file" ] || mv "$_css_id_tmp" "$_css_id_file"
+ # A usable incumbent wins, but only a valid one: zero-length
+ # or malformed is an interrupted write or a planted value, so
+ # replace it with one rename (no unlink, the path never
+ # vanishes). Also covers filesystems without hard links
+ # (exFAT/FAT32). -d because renaming onto a directory moves
+ # the temp inside it instead of replacing it.
+ if _css_incumbent=$(_css_read_valid_install_id "$_css_id_file") \
+ && [ -z "$_css_incumbent" ] && [ ! -d "$_css_id_file" ]; then
+ mv "$_css_id_tmp" "$_css_id_file" 2>/dev/null || true
+ fi
fi
fi
rm -f "$_css_id_tmp"
- chmod 600 "$_css_id_file" 2>/dev/null || true
- unset _css_new_id _css_id_tmp
+ if [ -f "$_css_id_file" ]; then
+ chmod 600 "$_css_id_file" 2>/dev/null || true
+ fi
+ # Bake what is on disk, not what we meant to write: that is what the
+ # backend reports from /api/health, whoever won the race. An unwritable
+ # or non-regular path leaves this empty and no launcher is generated.
+ _css_studio_root_id=$(_css_read_valid_install_id "$_css_id_file") || true
+ unset _css_new_id _css_id_tmp _css_incumbent
fi
- _css_studio_root_id=$(cat "$_css_id_file" 2>/dev/null)
if [ -z "$_css_studio_root_id" ]; then
echo "[WARN] Cannot create launcher: failed to read $_css_id_file" >&2
return 1
diff --git a/tests/test_studio_install_workspace_guard.py b/tests/test_studio_install_workspace_guard.py
index 5e43903720a..1ff3c8800f5 100644
--- a/tests/test_studio_install_workspace_guard.py
+++ b/tests/test_studio_install_workspace_guard.py
@@ -15,6 +15,38 @@ INSTALL_PS1 = REPO_ROOT / "install.ps1"
SETUP_PS1 = REPO_ROOT / "studio" / "setup.ps1"
SETUP_SH = REPO_ROOT / "studio" / "setup.sh"
+
+def _install_id_helpers() -> str:
+ """The shipped _css_install_id_is_valid / _css_read_valid_install_id bodies,
+ sliced out of install.sh so the shell tests below run the real validator."""
+ src = INSTALL_SH.read_text(encoding = "utf-8")
+ start = src.index("_css_install_id_is_valid() ")
+ end = src.index("# ── Helper: create desktop shortcuts", start)
+ return src[start:end]
+
+
+def _extract_create_studio_shortcuts() -> str:
+ """The shipped helpers plus the whole create_studio_shortcuts body.
+
+ Heredocs carry their own `}` at column 0, so `sh -n` picks the real one.
+ """
+ src = INSTALL_SH.read_text(encoding = "utf-8")
+ lines = src.splitlines()
+ start = next(i for i, l in enumerate(lines) if l.startswith("_css_install_id_is_valid() "))
+ fn = next(i for i, l in enumerate(lines) if l.startswith("create_studio_shortcuts() {"))
+ eof = next(i for i, l in enumerate(lines) if i > fn and l == "LAUNCHER_EOF")
+ for i, line in enumerate(lines):
+ if i <= eof or line != "}":
+ continue
+ candidate = "\n".join(lines[start : i + 1]) + "\n"
+ if (
+ subprocess.run(["sh", "-n"], input = candidate, text = True, capture_output = True).returncode
+ == 0
+ ):
+ return candidate
+ raise AssertionError("could not slice create_studio_shortcuts from install.sh")
+
+
# Stub the rollback helper with a move. The directory predicate is extracted
# from install.sh because it controls whether the guard runs.
_INSTALL_GUARD_STUBS = (
@@ -620,35 +652,38 @@ def test_install_sh_create_shortcuts_seeds_id_from_csprng_with_python_fallback(t
"""_create_shortcuts seeds ids from /dev/urandom (python3 secrets fallback) and is re-run idempotent."""
src = INSTALL_SH.read_text(encoding = "utf-8")
fn_start = src.index('_css_data_dir="$DATA_DIR"')
- block = src[fn_start : fn_start + 3000]
+ block = src[fn_start : fn_start + 4200]
urandom_idx = block.index("od -An -N32 -tx1 /dev/urandom")
py_fallback_idx = block.index("python3 -c 'import secrets;", urandom_idx)
assert (
urandom_idx < py_fallback_idx
), "/dev/urandom must be tried before the python3 secrets fallback"
- # Non-empty id file check before generation is what makes re-runs idempotent.
+ # Reusing an existing id only when it is valid is what makes re-runs
+ # idempotent -- and keeps a pre-planted value out of the launcher.
assert (
- 'if [ ! -s "$_css_id_file" ]; then' in block
- ), "install.sh must skip id generation when the file already has content"
+ '_css_studio_root_id=$(_css_read_valid_install_id "$_css_id_file")' in block
+ ), "install.sh must reuse an existing id only after validating it"
# Behavioral check: run the generation block twice to confirm idempotence.
studio_home = tmp_path / "studio"
(studio_home / "share").mkdir(parents = True)
gen_script = (
- f'STUDIO_HOME="{studio_home}"\n'
+ _install_id_helpers() + f'STUDIO_HOME="{studio_home}"\n'
'_css_id_dir="$STUDIO_HOME/share"\n'
'_css_id_file="$_css_id_dir/studio_install_id"\n'
# Replicate the generation block narrowly so it fails loud on contract drift.
"gen() {\n"
- ' if [ ! -s "$_css_id_file" ]; then\n'
+ ' _css_studio_root_id=$(_css_read_valid_install_id "$_css_id_file")\n'
+ ' if [ -z "$_css_studio_root_id" ]; then\n'
' _css_new_id=$(od -An -N32 -tx1 /dev/urandom 2>/dev/null | tr -d " \\n")\n'
' _t="$_css_id_file.$$.tmp"\n'
' printf "%s" "$_css_new_id" > "$_t"\n'
' ln "$_t" "$_css_id_file" 2>/dev/null \\\n'
' || { [ -s "$_css_id_file" ] || mv "$_t" "$_css_id_file"; }\n'
' rm -f "$_t"\n'
+ ' _css_studio_root_id="$_css_new_id"\n'
" fi\n"
- ' cat "$_css_id_file"\n'
+ ' printf "%s\\n" "$_css_studio_root_id"\n'
"}\n"
"a=$(gen); b=$(gen)\n"
'[ "$a" = "$b" ] || { echo MISMATCH; exit 1; }\n'
@@ -668,22 +703,60 @@ def test_install_sh_publishes_the_id_without_clobbering():
"""install.sh must publish the id no-clobber, so it cannot replace one the desktop app minted."""
src = INSTALL_SH.read_text(encoding = "utf-8")
fn_start = src.index('_css_id_dir="$STUDIO_HOME/share"')
- block = src[fn_start : fn_start + 2400]
+ block = src[fn_start : fn_start + 4200]
assert (
'ln "$_css_id_tmp" "$_css_id_file"' in block
), "install.sh must publish the id with ln (EEXIST on a race), not a clobbering mv"
+ _guarded_mv = 'mv "$_css_id_tmp" "$_css_id_file" 2>/dev/null || true'
assert 'mv "$_css_id_tmp" "$_css_id_file"' not in block.replace(
- '[ -s "$_css_id_file" ] || mv "$_css_id_tmp" "$_css_id_file"', ""
+ _guarded_mv, ""
), "the only remaining mv must be the no-hard-link fallback, guarded on the destination"
assert (
- '[ -s "$_css_id_file" ] || mv' in block
- ), "the mv branch must refuse to replace a usable incumbent id"
+ 'if _css_incumbent=$(_css_read_valid_install_id "$_css_id_file") \\\n'
+ ' && [ -z "$_css_incumbent" ] && [ ! -d "$_css_id_file" ]; then' in block
+ ), "the mv branch must refuse a valid incumbent, an unreadable one, or a directory"
+ assert _guarded_mv in block, "the fallback mv must not abort the installer under set -e"
assert (
'rm -f "$_css_id_file"' not in block
), "never unlink the id: an unlink opens a window where a valid id is deleted"
assert 'rm -f "$_css_id_tmp"' in block, "the temp sibling must not be left behind"
+def test_install_sh_bakes_the_id_that_is_actually_on_disk(tmp_path):
+ """The launcher must hold what the id file holds, not what we tried to write.
+
+ The backend reports the file's content, so every path where publication did
+ something else (a directory destination, so `ln` links the temp inside it;
+ a lost race; an unwritable share dir) must resolve to the on-disk value or
+ to no launcher at all.
+ """
+ src = INSTALL_SH.read_text(encoding = "utf-8")
+ fn_start = src.index('_css_id_dir="$STUDIO_HOME/share"')
+ block = src[fn_start : fn_start + 4200]
+ read_back = '_css_studio_root_id=$(_css_read_valid_install_id "$_css_id_file")'
+ assert block.count(read_back) >= 2, "the id must be re-read after publication"
+ assert block.rindex(read_back) > block.index(
+ 'rm -f "$_css_id_tmp"'
+ ), "the value baked into the launcher must be read back after the publish step"
+
+ # Behavioural: a directory at the id path must not yield a launcher.
+ studio_home = tmp_path / "studio"
+ (studio_home / "share" / "studio_install_id").mkdir(parents = True)
+ probe = (
+ _install_id_helpers() + f'_css_id_file="{studio_home}/share/studio_install_id"\n'
+ 'printf "%s" "' + "d" * 64 + '" > "$_css_id_file.tmp"\n'
+ 'ln "$_css_id_file.tmp" "$_css_id_file" 2>/dev/null || true\n'
+ 'rm -f "$_css_id_file.tmp"\n'
+ 'printf "ID=[%s]\\n" "$(_css_read_valid_install_id "$_css_id_file")"\n'
+ )
+ res = subprocess.run(["sh", "-c", probe], text = True, capture_output = True)
+ assert res.returncode == 0, res.stderr
+ assert "ID=[]" in res.stdout, (
+ "a directory at the id path must read back as no id, so the launcher is "
+ f"not generated; got {res.stdout!r}"
+ )
+
+
def test_install_sh_id_publish_adopts_the_winner_of_a_race(tmp_path):
"""A second writer must adopt the id already on disk, never replace it."""
studio_home = tmp_path / "studio"
@@ -695,12 +768,15 @@ def test_install_sh_id_publish_adopts_the_winner_of_a_race(tmp_path):
# Replicate the publish step with the guard removed, so only the publication
# primitive decides the outcome: a clobbering mv would overwrite the incumbent.
publish = (
- f'_css_id_file="{id_file}"\n'
+ _install_id_helpers() + f'_css_id_file="{id_file}"\n'
'_css_id_tmp="$_css_id_file.$$.tmp"\n'
'_css_new_id="' + "b" * 64 + '"\n'
'printf "%s" "$_css_new_id" > "$_css_id_tmp"\n'
'if ! ln "$_css_id_tmp" "$_css_id_file" 2>/dev/null; then\n'
- ' [ -s "$_css_id_file" ] || mv "$_css_id_tmp" "$_css_id_file"\n'
+ ' _css_studio_root_id=$(_css_read_valid_install_id "$_css_id_file")\n'
+ ' if [ -z "$_css_studio_root_id" ] && mv "$_css_id_tmp" "$_css_id_file"; then\n'
+ ' _css_studio_root_id="$_css_new_id"\n'
+ " fi\n"
"fi\n"
'rm -f "$_css_id_tmp"\n'
'cat "$_css_id_file"\n'
@@ -725,12 +801,15 @@ def test_install_sh_id_publish_replaces_a_blank_incumbent(tmp_path):
fresh = "c" * 64
publish = (
- f'_css_id_file="{id_file}"\n'
+ _install_id_helpers() + f'_css_id_file="{id_file}"\n'
f'_css_new_id="{fresh}"\n'
'_css_id_tmp="$_css_id_file.$$.$(printf "%.8s" "$_css_new_id").tmp"\n'
'printf "%s" "$_css_new_id" > "$_css_id_tmp"\n'
'if ! ln "$_css_id_tmp" "$_css_id_file" 2>/dev/null; then\n'
- ' [ -s "$_css_id_file" ] || mv "$_css_id_tmp" "$_css_id_file"\n'
+ ' _css_studio_root_id=$(_css_read_valid_install_id "$_css_id_file")\n'
+ ' if [ -z "$_css_studio_root_id" ] && mv "$_css_id_tmp" "$_css_id_file"; then\n'
+ ' _css_studio_root_id="$_css_new_id"\n'
+ " fi\n"
"fi\n"
'rm -f "$_css_id_tmp"\n'
'cat "$_css_id_file"\n'
@@ -740,6 +819,321 @@ def test_install_sh_id_publish_replaces_a_blank_incumbent(tmp_path):
assert res.stdout.strip() == fresh, "a blank id must be replaced, not adopted"
+def test_install_sh_trims_only_surrounding_whitespace_in_an_existing_id(tmp_path):
+ """Interior whitespace must fail the check, not be deleted into a valid id.
+
+ The backend strips then regex-matches, so `<32 hex>\\n<32 hex>` is not an id
+ to it. Deleting the newline would bake a token the backend never reports,
+ leaving the launcher rejecting its own backend forever.
+ """
+ src = INSTALL_SH.read_text(encoding = "utf-8")
+ assert (
+ "tr -d ' \\t\\r\\n'" not in src
+ ), "install.sh must not delete interior whitespace from the id"
+ assert (
+ '_cvi_id=${_cvi_id#"${_cvi_id%%[![:space:]]*}"}' in src
+ and '_cvi_id=${_cvi_id%"${_cvi_id##*[![:space:]]}"}' in src
+ ), "install.sh must trim only the surrounding whitespace, as the backend does"
+
+ id_file = tmp_path / "studio_install_id"
+ probe = (
+ _install_id_helpers()
+ + f'printf "OUT=[%s]\\n" "$(_css_read_valid_install_id "{id_file}")"\n'
+ )
+ for content, expect_reuse in [
+ ("a" * 32 + "\n" + "a" * 32, False),
+ ("a" * 32 + " " + "a" * 32, False),
+ (" " + "a" * 64 + " \n", True),
+ ("\n\n" + "a" * 64 + "\n\n", True),
+ ("\t" + "a" * 64 + "\r\n", True),
+ ]:
+ id_file.write_text(content, encoding = "utf-8")
+ res = subprocess.run(["sh", "-c", probe], text = True, capture_output = True)
+ assert res.returncode == 0, res.stderr
+ got = res.stdout.strip()[len("OUT=[") : -1]
+ assert bool(got) is expect_reuse, f"{content!r} -> {got!r}"
+ if expect_reuse:
+ assert got == "a" * 64, f"surrounding whitespace must be trimmed, got {got!r}"
+
+
+def test_install_sh_rejects_an_id_holding_a_nul_byte(tmp_path):
+ """A NUL must be caught before the shell silently drops it.
+
+ Command substitution cannot carry one, so `<32 hex>\\0<32 hex>` reads back
+ valid while the backend keeps the byte and reports "".
+ """
+ src = INSTALL_SH.read_text(encoding = "utf-8")
+ assert (
+ """tr -dc '\\000' < "$1" | tr '\\000' 'N'""" in src
+ ), "install.sh must detect NUL bytes before reading the id into a variable"
+
+ id_file = tmp_path / "studio_install_id"
+ probe = (
+ _install_id_helpers()
+ + f'printf "OUT=[%s]\\n" "$(_css_read_valid_install_id "{id_file}")"\n'
+ )
+ for content in [
+ b"a" * 32 + b"\x00" + b"a" * 32,
+ b"b" * 64 + b"\x00",
+ b"\x00" + b"c" * 64,
+ ]:
+ id_file.write_bytes(content)
+ res = subprocess.run(["sh", "-c", probe], text = True, capture_output = True)
+ assert res.returncode == 0, res.stderr
+ assert "OUT=[]" in res.stdout, f"{content!r} must not read as an id, got {res.stdout!r}"
+ id_file.write_bytes(b"d" * 64)
+ res = subprocess.run(["sh", "-c", probe], text = True, capture_output = True)
+ assert "OUT=[" + "d" * 64 + "]" in res.stdout, "a clean id must still be reused"
+
+
[email protected](os.name != "posix", reason = "PATH-shadowed cat is a POSIX shape")
+def test_install_sh_reports_a_failed_read_instead_of_regenerating(tmp_path):
+ """A read that FAILS is not the same answer as a malformed id.
+
+ `-r` can pass while the read errors, on an NFS or FUSE backed root.
+ Flattening that into "no id" let the publish path replace a valid
+ incumbent a running backend still reports.
+ """
+ src = INSTALL_SH.read_text(encoding = "utf-8")
+ assert (
+ '_cvi_id=$({ cat "$1"; } 2>/dev/null) || return 1' in src
+ ), "the read helper must report a failed read, not swallow it"
+ assert (
+ 'if ! _css_studio_root_id=$(_css_read_valid_install_id "$_css_id_file"); then' in src
+ ), "the caller must refuse on a failed read"
+
+ id_file = tmp_path / "studio_install_id"
+ good = "b" * 64
+ id_file.write_text(good, encoding = "utf-8")
+ fake_bin = tmp_path / "bin"
+ fake_bin.mkdir()
+ fake_cat = fake_bin / "cat"
+ fake_cat.write_text("#!/bin/sh\nexit 1\n", encoding = "utf-8")
+ fake_cat.chmod(0o755)
+
+ probe = (
+ _install_id_helpers() + f'if out=$(_css_read_valid_install_id "{id_file}"); then\n'
+ ' printf "READ_OK=[%s]\\n" "$out"\n'
+ "else\n"
+ ' printf "READ_FAILED\\n"\n'
+ "fi\n"
+ )
+ env = dict(os.environ, PATH = f"{fake_bin}:{os.environ['PATH']}")
+ res = subprocess.run(["sh", "-c", probe], text = True, capture_output = True, env = env)
+ assert res.returncode == 0, res.stderr
+ assert "READ_FAILED" in res.stdout, f"a failed read must be reported, got {res.stdout!r}"
+ assert id_file.read_text() == good, "the id must be left alone"
+
+
+ os.name != "posix" or os.geteuid() == 0,
+ reason = "needs POSIX mode bits, and root reads regardless of them",
+)
+def test_install_sh_replaces_an_empty_id_even_when_it_cannot_read_it(tmp_path):
+ """Zero length is an answer stat can give: that file holds no id.
+
+ Refusing would fail an install that pre-validation simply completed. The
+ protection is for ids we cannot read, and an id is 64 bytes, never zero.
+ """
+ src = INSTALL_SH.read_text(encoding = "utf-8")
+ assert '[ -s "$1" ] || return 0' in src, "an empty id file must read as no id"
+
+ id_file = tmp_path / "studio_install_id"
+ id_file.write_bytes(b"")
+ id_file.chmod(0o000)
+ probe = (
+ _install_id_helpers() + f'if out=$(_css_read_valid_install_id "{id_file}"); then\n'
+ ' printf "READ_OK=[%s]\\n" "$out"\n'
+ "else\n"
+ ' printf "READ_FAILED\\n"\n'
+ "fi\n"
+ )
+ try:
+ res = subprocess.run(["sh", "-c", probe], text = True, capture_output = True)
+ finally:
+ id_file.chmod(0o600)
+ assert res.returncode == 0, res.stderr
+ assert (
+ "READ_OK=[]" in res.stdout
+ ), f"an empty id must be regenerated, not refused; got {res.stdout!r}"
+
+
+ os.name != "posix" or os.geteuid() == 0,
+ reason = "needs POSIX mode bits, and root reads regardless of them",
+)
+def test_install_sh_refuses_an_unreadable_existing_id(tmp_path):
+ """An id we cannot READ must not be treated as malformed and replaced.
+
+ In a shared root it can be a good id owned by someone else that a running
+ backend already reports, so the step refuses, as it did before the id was
+ validated at all.
+ """
+ src = INSTALL_SH.read_text(encoding = "utf-8")
+ fn_start = src.index('_css_id_dir="$STUDIO_HOME/share"')
+ block = src[fn_start : fn_start + 4200]
+ assert (
+ 'if ! _css_studio_root_id=$(_css_read_valid_install_id "$_css_id_file"); then' in block
+ ), "install.sh must separate an unreadable id from a malformed one"
+ assert (
+ "[WARN] Cannot create launcher: cannot read" in block
+ ), "the unreadable-id branch must warn"
+
+ studio_home = tmp_path / "studio"
+ (studio_home / "share").mkdir(parents = True)
+ id_file = studio_home / "share" / "studio_install_id"
+ id_file.write_text("b" * 64, encoding = "utf-8")
+ id_file.chmod(0o000)
+ try:
+ probe = (
+ _install_id_helpers() + f'_css_id_file="{id_file}"\n'
+ 'if ! _css_studio_root_id=$(_css_read_valid_install_id "$_css_id_file"); then\n'
+ " echo REFUSED; exit 0\n"
+ "fi\n"
+ 'echo "REUSED=$_css_studio_root_id"\n'
+ )
+ res = subprocess.run(["sh", "-c", probe], text = True, capture_output = True)
+ assert res.returncode == 0, res.stderr
+ assert "REFUSED" in res.stdout, f"expected a refusal, got {res.stdout!r}"
+ finally:
+ id_file.chmod(0o600)
+ assert id_file.read_text() == "b" * 64, "the unreadable id must survive untouched"
+
+
[email protected](not hasattr(os, "mkfifo"), reason = "no FIFOs on this platform")
+def test_install_sh_never_reads_a_non_regular_id_path(tmp_path):
+ """A FIFO at the id path must not park the installer on the open.
+
+ `cat` blocks until a writer appears, so an unconditional read of a shared
+ or custom root hangs the install forever.
+ """
+ src = INSTALL_SH.read_text(encoding = "utf-8")
+ assert '[ -f "$1" ] || return 0' in src, "install.sh must read the id only from a regular file"
+
+ id_file = tmp_path / "studio_install_id"
+ os.mkfifo(id_file)
+ probe = (
+ _install_id_helpers()
+ + f'printf "OUT=[%s]\\n" "$(_css_read_valid_install_id "{id_file}")"\n'
+ )
+ res = subprocess.run(["sh", "-c", probe], text = True, capture_output = True, timeout = 20)
+ assert res.returncode == 0, res.stderr
+ assert "OUT=[]" in res.stdout, f"a FIFO must read as no id, got {res.stdout!r}"
+
+
[email protected](os.name != "posix", reason = "runs the POSIX installer function")
+def test_create_studio_shortcuts_end_to_end_never_embeds_a_planted_id(tmp_path):
+ """The REAL create_studio_shortcuts, not a reconstruction of it.
+
+ Helper-level tests cannot catch a caller that validates then embeds
+ something else, so this inspects the launcher the shipped function writes.
+ """
+ home = tmp_path / "home"
+ studio_home = tmp_path / "studio"
+ data_dir = tmp_path / "data"
+ for d in (home, studio_home / "share", data_dir, tmp_path / "bin"):
+ d.mkdir(parents = True)
+ marker = tmp_path / "PWNED"
+ (studio_home / "share" / "studio_install_id").write_text(
+ f"x'; touch {marker}; exit 0 #", encoding = "utf-8"
+ )
+ exe = tmp_path / "bin" / "unsloth"
+ exe.write_text("#!/bin/sh\nexit 0\n", encoding = "utf-8")
+ exe.chmod(0o755)
+
+ script = (
+ "set -e\n"
+ "download() { : ; }\n"
+ "substep() { : ; }\n"
+ '_LOCK_KEY="testkey"\n'
+ f'STUDIO_HOME="{studio_home}"\nDATA_DIR="{data_dir}"\n'
+ "_STUDIO_HOME_REDIRECT=default\n"
+ + _extract_create_studio_shortcuts()
+ + f'\ncreate_studio_shortcuts "{exe}" "linux"\n'
+ )
+ res = subprocess.run(
+ ["sh", "-c", script],
+ text = True,
+ capture_output = True,
+ timeout = 300,
+ env = dict(os.environ, HOME = str(home)),
+ cwd = str(tmp_path),
+ )
+ assert res.returncode == 0, f"installer step failed: {res.stderr[-400:]}"
+
+ launcher = data_dir / "launch-studio.sh"
+ assert launcher.is_file(), "no launcher was written"
+ m = re.search(r"^_EXPECTED_STUDIO_ROOT_ID='(.*)'$", launcher.read_text(), re.M)
+ assert m, "launcher has no id assignment"
+ baked = m.group(1)
+ assert re.fullmatch(r"[0-9a-f]{64}", baked), f"planted id reached the launcher: {baked!r}"
+
+ # The launcher must agree with what the backend would report from the file.
+ on_disk = (studio_home / "share" / "studio_install_id").read_text().strip()
+ assert baked == on_disk, "the launcher and the id file disagree"
+ assert subprocess.run(["bash", "-n", str(launcher)]).returncode == 0
+
+ subprocess.run(["sh", "-c", f". {launcher}"], capture_output = True, timeout = 60)
+ assert not marker.exists(), "the planted id executed as launcher code"
+
+
+def test_install_sh_never_bakes_a_planted_id_into_the_launcher(tmp_path):
+ """A pre-planted studio_install_id must be regenerated, not embedded.
+
+ The launcher holds the id in a single-quoted assignment, so a quote in it
+ runs as launcher code on every Studio start. Custom roots can live in
+ shared directories, so the file is not trusted for merely being there.
+ """
+ studio_home = tmp_path / "studio"
+ (studio_home / "share").mkdir(parents = True)
+ id_file = studio_home / "share" / "studio_install_id"
+ marker = tmp_path / "pwned"
+ id_file.write_text(f"x'; touch {marker}; exit 0 #", encoding = "utf-8")
+
+ launcher = tmp_path / "launch-studio.sh"
+ script = (
+ _install_id_helpers() + f'_css_id_file="{id_file}"\n'
+ '_css_studio_root_id=$(_css_read_valid_install_id "$_css_id_file")\n'
+ 'if [ -z "$_css_studio_root_id" ]; then\n'
+ ' _css_studio_root_id=$(od -An -N32 -tx1 /dev/urandom | tr -d " \\n")\n'
+ "fi\n"
+ # The real embedding step from install.sh.
+ f'printf "%s\\n" "_EXPECTED_STUDIO_ROOT_ID=\'@@STUDIO_ROOT_ID@@\'" > {launcher}\n'
+ f'sed -e "s|@@STUDIO_ROOT_ID@@|$_css_studio_root_id|g" {launcher} > {launcher}.tmp\n'
+ f"mv {launcher}.tmp {launcher}\n"
+ )
+ res = subprocess.run(["sh", "-c", script], text = True, capture_output = True)
+ assert res.returncode == 0, res.stderr
+
+ baked = launcher.read_text(encoding = "utf-8").strip()
+ prefix, quoted = "_EXPECTED_STUDIO_ROOT_ID='", baked[len("_EXPECTED_STUDIO_ROOT_ID='") : -1]
+ assert baked.startswith(prefix) and baked.endswith("'"), f"unexpected launcher line: {baked!r}"
+ assert len(quoted) == 64 and all(
+ c in "0123456789abcdef" for c in quoted
+ ), f"a planted id must be regenerated, got {quoted!r}"
+
+ # Belt and braces: sourcing the generated line must not run anything.
+ subprocess.run(["sh", "-c", f". {launcher}"], text = True, capture_output = True)
+ assert not marker.exists(), "the planted id executed as launcher code"
+
+
+def test_install_ps1_validates_an_existing_id_before_embedding_it():
+ """install.ps1 must reject a non-hex existing id instead of interpolating it.
+
+ -cnotmatch, not -notmatch: -match is case insensitive and would accept an
+ uppercase id the backend's regex rejects.
+ """
+ src = INSTALL_PS1.read_text(encoding = "utf-8")
+ idx = src.index('$_studioIdFile = Join-Path $_studioIdDir "studio_install_id"')
+ block = src[idx : idx + 1200]
+ assert (
+ "$_studioRootId -cnotmatch '^[0-9a-f]{64}$'" in block
+ ), "install.ps1 must validate an existing id as 64 lowercase hex before reuse"
+ assert block.index("ReadAllText($_studioIdFile)") < block.index(
+ "$_studioRootId -cnotmatch"
+ ), "the validation must follow the read and precede any use of the value"
+
+
def test_install_ps1_publishes_the_id_without_clobbering():
"""install.ps1 must publish no-clobber and adopt the winner, since it never re-reads the file."""
src = INSTALL_PS1.read_text(encoding = "utf-8")
@@ -766,8 +1160,8 @@ def test_install_ps1_publishes_the_id_without_clobbering():
"$_studioRootId = $_adoptedRootId" in block
), "the adopted id must become the value baked into the launcher"
assert (
- "if ($_adoptedRootId)" in block
- ), "install.ps1 must only adopt a non-empty id, so a blank one cannot become the expected id"
+ "if ($_adoptedRootId -cmatch '^[0-9a-f]{64}$')" in block
+ ), "install.ps1 must only adopt a valid id, so a blank or planted one cannot become the expected id"
assert (
"Remove-Item -LiteralPath $_studioIdFile" not in block
), "never unlink the id: an unlink opens a window where a valid id is deleted"
@@ -777,7 +1171,7 @@ def test_install_sh_create_shortcuts_fails_fast_when_no_entropy():
"""With no entropy source, _create_shortcuts must `return 1` not bake an empty studio_root_id."""
src = INSTALL_SH.read_text(encoding = "utf-8")
fn_start = src.index('_css_data_dir="$DATA_DIR"')
- block = src[fn_start : fn_start + 4200]
+ block = src[fn_start : fn_start + 5200]
assert (
"[WARN] Cannot create launcher: no entropy source for studio_install_id" in block
), "install.sh must warn when neither urandom nor python3 is available"