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
studio: add in-app updates for debian installs (#11338)
Maheswar Kumar2430036e2bde
diff --git a/.github/workflows/desktop-app-clean-machine-ci.yml b/.github/workflows/desktop-app-clean-machine-ci.ymlindex 67524a0135e..b7f64a3b46e 100644--- a/.github/workflows/desktop-app-clean-machine-ci.yml+++ b/.github/workflows/desktop-app-clean-machine-ci.yml@@ -447,6 +447,26 @@ jobs:ficat "$apt_log"BIN="$(dpkg -L "$(dpkg-deb -f dl/*.deb Package)" | grep -E '/usr/bin/' | head -1)"+ # In-app .deb updates run the installed binary through a polkit action, so the+ # package has to carry the action file. tauri ships it via bundle.linux.deb.files,+ # a mapping nothing else validates: drop the entry and updates fall back to the+ # release page silently, with no failing test anywhere.+ POLICY=/usr/share/polkit-1/actions/ai.unsloth.studio.update.policy+ if ! dpkg -L "$(dpkg-deb -f dl/*.deb Package)" | grep -qx "$POLICY"; then+ echo "::error::the .deb no longer ships $POLICY, so in-app Debian updates cannot authenticate"+ exit 1+ fi+ # auth_admin on all three implicit cases is what makes the update prompt, rather+ # than either silently elevating or refusing outright.+ if [ "$(stat -c '%U:%G %a' "$POLICY")" != "root:root 644" ]; then+ echo "::error::$POLICY has the wrong owner or mode: $(stat -c '%U:%G %a' "$POLICY")"+ exit 1+ fi+ grep -c 'auth_admin' "$POLICY" | grep -qx 3 || {+ echo "::error::$POLICY no longer requires auth_admin for all three implicit cases"+ exit 1+ }+ echo "polkit action shipped: $(stat -c '%U:%G %a %n' "$POLICY")"elsesudo apt-get install -y -qq --no-install-recommends \libfuse2 libgles2 libgl1 libegl1 libgbm1 libwayland-client0 \diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.ymlindex 1b6c1c0de7a..12c65728740 100644--- a/.github/workflows/release-desktop.yml+++ b/.github/workflows/release-desktop.yml@@ -42,7 +42,7 @@ env:**Windows**: Download `Unsloth-Desktop-Windows.exe`, or `Unsloth-Desktop-Windows-ARM64.exe` on a Windows on ARM machine.**Linux**: Download `Unsloth-Desktop-Ubuntu.deb` for Ubuntu/Debian. `.AppImage` is experimental.- > Linux in-app updates are AppImage-oriented. Package installs should update by downloading a new package.+ > Linux in-app updates cover `.deb` and AppImage installs. A `.deb` installed before in-app updates shipped needs one manual update first.> Linux AppImage can show a blank window on some Tauri/WebKitGTK + Wayland/Mesa stacks; use `.deb` when available.> Linux AppImage on Ubuntu 24.04+ may require: `sudo apt install libfuse2t64`> First-run system dependency elevation is supported on Ubuntu/Debian. Other Linux distributions should install system packages manually.@@ -1668,6 +1668,7 @@ jobs:('-setup.exe.sig', f'{windows_name}.exe.sig'),('-setup.exe', f'{windows_name}.exe'),('.dmg', f'{base_name}-MacOS.dmg'),+ ('.deb.sig', f'{base_name}-Ubuntu.deb.sig'),('.deb', f'{base_name}-Ubuntu.deb'),)staged = []@@ -1837,6 +1838,7 @@ jobs:f'{base_name}-Linux.AppImage',f'{base_name}-Linux.AppImage.sig',f'{base_name}-Ubuntu.deb',+ f'{base_name}-Ubuntu.deb.sig',f'{base_name}-Windows.exe',f'{base_name}-Windows.exe.sig',f'{base_name}-Windows-ARM64.exe',@@ -1956,6 +1958,7 @@ jobs:darwin = entry('.app.tar.gz.sig')linux = entry('.AppImage.sig')+ debian = entry('.deb.sig')# Both Windows bundles end in .exe.sig, and exactly_one() refuses an ambiguous# match, so name them in full. -Windows.exe.sig does not match -Windows-ARM64.exe.sig# under endswith, which is what keeps the two entries distinct.@@ -1973,6 +1976,7 @@ jobs:'darwin-aarch64-app': darwin,'linux-x86_64': linux,'linux-x86_64-appimage': linux,+ 'linux-x86_64-deb': debian,'windows-x86_64': windows,'windows-x86_64-nsis': windows,# Tauri asks for {os}-{arch}; without these an ARM64 install eitherdiff --git a/studio/frontend/src/hooks/use-tauri-update.ts b/studio/frontend/src/hooks/use-tauri-update.tsindex 2a2553242c2..11048b92c85 100644--- a/studio/frontend/src/hooks/use-tauri-update.ts+++ b/studio/frontend/src/hooks/use-tauri-update.ts@@ -272,13 +272,16 @@ export function useTauriUpdate(isExternalServer = false) {// Self-gates on the real target_os, so it is authoritative even if policy is a guess.if (await checkManualUpdate(policy)) return;if (resolved) {- // latest.json has no deb/rpm key, so the in-app updater would offer an AppImage this install cannot apply.+ // Reaching here means the Rust side resolved the mode and still said manual, so this+ // install has no in-app path: rpm, a plain tarball, or a .deb whose updater checks+ // failed. latest.json carries linux-x86_64-deb now, but only linux-x86_64 otherwise,+ // and that is an AppImage none of those installs can apply.updateRef.current = null;replaceInfo(null);updateStatus("idle");return;}- // Guessed policy, no manual offer: macOS, Windows and AppImage do have an in-app path.+ // Guessed policy, no manual offer: macOS, Windows, AppImage and .deb do have an in-app path.}const update = await checkDesktopUpdate();diff --git a/studio/src-tauri/Cargo.lock b/studio/src-tauri/Cargo.lockindex 6f21df7f81e..6ed6d2582cb 100644--- a/studio/src-tauri/Cargo.lock+++ b/studio/src-tauri/Cargo.lock@@ -5733,6 +5733,7 @@ dependencies = ["hmac","libc","log",+ "minisign-verify","objc2","objc2-app-kit","objc2-foundation",@@ -5741,6 +5742,7 @@ dependencies = ["rand 0.10.2","regex","reqwest",+ "semver","serde","serde_json","sha2 0.11.0",diff --git a/studio/src-tauri/Cargo.toml b/studio/src-tauri/Cargo.tomlindex b2eabfaa3d2..fa12c13f99a 100644--- a/studio/src-tauri/Cargo.toml+++ b/studio/src-tauri/Cargo.toml@@ -22,6 +22,8 @@ tauri-plugin-process = "2"serde = { version = "1", features = ["derive"] }serde_json = "1"base64 = "0.23"+minisign-verify = "0.2.5"+semver = "1"hmac = "0.13"sha2 = "0.11"reqwest = { version = "0.13", features = ["json"] }diff --git a/studio/src-tauri/linux/ai.unsloth.studio.update.policy b/studio/src-tauri/linux/ai.unsloth.studio.update.policynew file mode 100644index 00000000000..4653b69978a--- /dev/null+++ b/studio/src-tauri/linux/ai.unsloth.studio.update.policy@@ -0,0 +1,18 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD polkit Policy Configuration 1.0//EN" "http://www.freedesktop.org/software/polkit/policyconfig-1.dtd">+<policyconfig>+ <vendor>Unsloth AI</vendor>+ <vendor_url>https://unsloth.ai/</vendor_url>+ <icon_name>unsloth-studio</icon_name>+ <action id="ai.unsloth.studio.update">+ <description>Update Unsloth</description>+ <message>Authentication is required to update Unsloth.</message>+ <defaults>+ <allow_any>auth_admin</allow_any>+ <allow_inactive>auth_admin</allow_inactive>+ <allow_active>auth_admin</allow_active>+ </defaults>+ <annotate key="org.freedesktop.policykit.exec.path">/usr/bin/unsloth-studio</annotate>+ <annotate key="org.freedesktop.policykit.exec.argv1">--install-debian-update</annotate>+ </action>+</policyconfig>diff --git a/studio/src-tauri/src/debian_update.rs b/studio/src-tauri/src/debian_update.rsnew file mode 100644index 00000000000..752631c2c68--- /dev/null+++ b/studio/src-tauri/src/debian_update.rs@@ -0,0 +1,338 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++use std::fs;+use std::io::{Read, Write};+use std::os::unix::fs::{MetadataExt, PermissionsExt};+use std::path::Path;+use std::process::{Command, Output, Stdio};++const INSTALL_ARGUMENT: &str = "--install-debian-update";+const INSTALLED_BINARY: &str = "/usr/bin/unsloth-studio";+const PACKAGE_NAME: &str = "unsloth";+const MAX_PACKAGE_BYTES: u64 = 512 * 1024 * 1024;++pub(crate) fn is_debian_bundle() -> bool {+ matches!(+ tauri::utils::platform::bundle_type(),+ Some(tauri::utils::config::BundleType::Deb)+ )+}++pub(crate) fn is_supported_install() -> bool {+ is_debian_bundle()+ && tauri::utils::platform::current_exe()+ .is_ok_and(|path| path == Path::new(INSTALLED_BINARY))+ && fs::metadata(INSTALLED_BINARY)+ .is_ok_and(|metadata| metadata.uid() == 0 && metadata.mode() & 0o022 == 0)+ && Path::new("/usr/bin/pkexec").is_file()+ // bundle_type() is baked into the binary, so a .deb unpacked onto a non-apt distro by+ // hand or by alien still reports Deb: without this the app offers an update that dies+ // on the first dpkg-query. install.rs checks apt-get before elevating for the same reason.+ && Path::new("/usr/bin/apt-get").is_file()+}++pub(crate) fn install(bytes: &[u8], signature: &str, version: &str) -> Result<(), String> {+ if !is_supported_install() {+ return Err("The installed Debian updater or system authentication is unavailable. Install the package from the release page.".into());+ }+ let mut command = Command::new("/usr/bin/pkexec");+ command.args([+ "--disable-internal-agent",+ INSTALLED_BINARY,+ INSTALL_ARGUMENT,+ version,+ signature,+ ]);+ send_package(command, bytes)+}++fn send_package(mut command: Command, bytes: &[u8]) -> Result<(), String> {+ let mut child = command+ .stdin(Stdio::piped())+ .stdout(Stdio::null())+ .stderr(Stdio::piped())+ .spawn()+ .map_err(|error| format!("Could not request administrator authentication: {error}"))?;+ let write_result = child+ .stdin+ .take()+ .ok_or("The installer input is unavailable.")?+ .write_all(bytes);+ let output = child+ .wait_with_output()+ .map_err(|error| format!("Could not wait for the Debian installer: {error}"))?;+ match output.status.code() {+ Some(126) => return Err("Update cancelled at the administrator prompt.".into()),+ Some(127) => return Err("Administrator authentication was unavailable or denied. Use the release page to install the Debian package manually.".into()),+ _ => {}+ }+ require_success(output, "Debian package installation")?;+ write_result.map_err(|error| format!("Could not send the update to the installer: {error}"))+}++pub(crate) fn run_installer() -> Option<Result<(), String>> {+ let mut args = std::env::args_os().skip(1);+ if args.next().as_deref() != Some(std::ffi::OsStr::new(INSTALL_ARGUMENT)) {+ return None;+ }+ Some((|| {+ // this entry point must run before logging, shell discovery, or gui initialization.+ if unsafe { libc::geteuid() } != 0 {+ return Err("Debian updates require system administrator authentication.".into());+ }+ let version = args+ .next()+ .and_then(|value| value.into_string().ok())+ .ok_or("The update version is missing.")?;+ let signature = args+ .next()+ .and_then(|value| value.into_string().ok())+ .ok_or("The update signature is missing.")?;+ if args.next().is_some() || version.len() > 128 || signature.len() > 4096 {+ return Err("Invalid Debian installer arguments.".into());+ }+ let bytes = read_package(std::io::stdin().lock())?;+ install_verified_package(bytes, &signature, &version)+ })())+}++fn install_verified_package(bytes: Vec<u8>, signature: &str, version: &str) -> Result<(), String> {+ crate::desktop_updater::verify_bundle_signature(&bytes, signature)?;+ // Stated, not inherited: tempfile creates directories 0777 masked by the umask, and pkexec+ // passes the calling session's umask through untouched. At umask 000 another local user can+ // unlink the verified package and put their own there before apt reads it back.+ let directory = tempfile::Builder::new()+ .prefix("unsloth-update-")+ .permissions(fs::Permissions::from_mode(0o700))+ .tempdir_in("/var/tmp")+ .map_err(|error| error.to_string())?;+ let package = directory.path().join("unsloth.deb");+ fs::write(&package, bytes).map_err(|error| error.to_string())?;+ fs::set_permissions(&package, fs::Permissions::from_mode(0o600))+ .map_err(|error| error.to_string())?;+ let (debian_version_override, installed_version) = validate_package(&package, version)?;+ let mut command = system_command("/usr/bin/apt-get");+ if debian_version_override {+ // tauri writes raw semver, so debian sorts a stable release below its own prerelease.+ command.arg("--allow-downgrades");+ }+ // apt holds its frontend lock when this hook checks the previously validated version.+ command.arg("-o").arg(format!(+ "DPkg::Pre-Invoke::={}",+ installed_version_guard(&installed_version)+ ));+ let output = command+ .args([+ "--assume-yes",+ "--no-remove",+ "-o",+ "DPkg::Lock::Timeout=0",+ "install",+ ])+ .arg(&package)+ .output()+ .map_err(|error| format!("Could not start the Debian package manager: {error}"))?;+ require_success(output, "Debian package installation")?;+ let installed = installed_package()?;+ if installed+ != [+ "install ok installed",+ version,+ &package_field(&package, "Architecture")?,+ ]+ {+ return Err(+ "The package manager did not finish installing the requested Unsloth version.".into(),+ );+ }+ Ok(())+}++fn read_package(input: impl Read) -> Result<Vec<u8>, String> {+ let mut bytes = Vec::new();+ input+ .take(MAX_PACKAGE_BYTES + 1)+ .read_to_end(&mut bytes)+ .map_err(|error| format!("Could not read the Debian update: {error}"))?;+ if bytes.is_empty() || bytes.len() as u64 > MAX_PACKAGE_BYTES {+ return Err("The Debian update is empty or exceeds the 512 MiB limit.".into());+ }+ Ok(bytes)+}++fn system_command(program: &str) -> Command {+ let mut command = Command::new(program);+ command+ .env_clear()+ .env("PATH", "/usr/sbin:/usr/bin:/sbin:/bin")+ .env("LANG", "C")+ .env("DEBIAN_FRONTEND", "noninteractive")+ .current_dir("/")+ .stdin(Stdio::null());+ command+}++fn require_success(output: Output, operation: &str) -> Result<String, String> {+ if !output.status.success() {+ return Err(format!(+ "{operation} failed ({}): {}",+ output.status,+ String::from_utf8_lossy(&output.stderr).trim()+ ));+ }+ String::from_utf8(output.stdout)+ .map(|value| value.trim().to_owned())+ .map_err(|error| format!("Invalid {operation} output: {error}"))+}++fn package_field(package: &Path, field: &str) -> Result<String, String> {+ let output = system_command("/usr/bin/dpkg-deb")+ .arg("--field")+ .arg(package)+ .arg(field)+ .output()+ .map_err(|error| error.to_string())?;+ require_success(output, "Debian package inspection")+}++fn installed_package() -> Result<Vec<String>, String> {+ let output = system_command("/usr/bin/dpkg-query")+ .args([+ "--show",+ "--showformat=${Status}\n${Version}\n${Architecture}",+ PACKAGE_NAME,+ ])+ .output()+ .map_err(|error| error.to_string())?;+ Ok(require_success(output, "Installed package inspection")?+ .lines()+ .map(str::to_owned)+ .collect())+}++fn validate_identity(+ name: &str,+ version: &str,+ architecture: &str,+ expected_version: &str,+ installed: &[String],+) -> Result<(), String> {+ if name != PACKAGE_NAME+ || version != expected_version+ || installed.len() != 3+ || architecture != installed[2]+ {+ return Err("The signed update does not match the installed Unsloth package, version, or architecture.".into());+ }+ if installed[0] != "install ok installed" {+ return Err(+ "Repair the existing Unsloth package with the system package manager before updating."+ .into(),+ );+ }+ Ok(())+}++fn validate_package(package: &Path, expected_version: &str) -> Result<(bool, String), String> {+ let installed = installed_package()?;+ let version = package_field(package, "Version")?;+ validate_identity(+ &package_field(package, "Package")?,+ &version,+ &package_field(package, "Architecture")?,+ expected_version,+ &installed,+ )?;+ let override_version = needs_debian_version_override(&version, &installed[1])?;+ Ok((override_version, installed[1].clone()))+}++fn installed_version_guard(installed_version: &str) -> String {+ // the version has passed semver parsing, which excludes shell metacharacters.+ format!(+ "test \"$(/usr/bin/dpkg-query --show --showformat='${{Version}}' unsloth)\" = '{installed_version}' || \+ {{ echo 'Installed Unsloth changed during the update. Retry the update.' >&2; exit 1; }}"+ )+}++fn needs_debian_version_override(version: &str, installed: &str) -> Result<bool, String> {+ let next = semver::Version::parse(version).map_err(|error| error.to_string())?;+ let current = semver::Version::parse(installed).map_err(|error| error.to_string())?;+ if !next.cmp_precedence(¤t).is_gt() {+ return Err("The Debian update must be newer than the installed Unsloth package.".into());+ }+ let status = system_command("/usr/bin/dpkg")+ .args(["--compare-versions", version, "lt", installed])+ .status()+ .map_err(|error| error.to_string())?;+ match status.code() {+ Some(0) => Ok(true),+ Some(1) => Ok(false),+ _ => Err("Could not compare Debian package versions.".into()),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_package_manager_guard_rejects_a_concurrently_changed_version() {+ let directory = tempfile::tempdir().unwrap();+ let status = directory.path().join("status");+ let guard = installed_version_guard("0.1.811-beta").replacen(+ "/usr/bin/dpkg-query",+ &format!(+ "/usr/bin/dpkg-query --admindir='{}'",+ directory.path().display()+ ),+ 1,+ );+ for (version, accepted) in [("0.1.811-beta", true), ("0.1.812-beta", false)] {+ fs::write(+ &status,+ format!(+ "Package: unsloth\nStatus: install ok installed\nVersion: {version}\n\+ Architecture: amd64\nMaintainer: Test <[email protected]>\n\+ Description: Update fixture\n\n"+ ),+ )+ .unwrap();+ let output = Command::new("/bin/sh")+ .args(["-c", &guard])+ .output()+ .unwrap();+ assert_eq!(output.status.success(), accepted);+ if !accepted {+ assert!(String::from_utf8_lossy(&output.stderr)+ .contains("Installed Unsloth changed during the update"));+ }+ }+ }++ #[test]+ fn semver_upgrades_allow_stable_promotion_but_never_a_rollback() {+ assert!(needs_debian_version_override("0.1.811", "0.1.811-beta").unwrap());+ assert!(!needs_debian_version_override("0.1.811-beta", "0.1.810-beta").unwrap());+ assert!(needs_debian_version_override("0.1.811-beta", "0.1.811").is_err());+ assert!(needs_debian_version_override("0.1.810", "0.1.811").is_err());+ assert!(needs_debian_version_override("0.1.811", "0.1.811").is_err());+ }++ #[test]+ fn authentication_failures_take_precedence_over_a_closed_input_pipe() {+ for (code, message) in [+ (126, "Update cancelled at the administrator prompt."),+ (+ 127,+ "Administrator authentication was unavailable or denied.",+ ),+ ] {+ let mut command = Command::new("/bin/sh");+ command.args(["-c", &format!("exit {code}")]);+ let error = send_package(command, &vec![0; 131072]).unwrap_err();+ assert!(error.starts_with(message), "{error}");+ }+ }+}diff --git a/studio/src-tauri/src/desktop_update_policy.rs b/studio/src-tauri/src/desktop_update_policy.rsindex 724ede196cf..d1b1c8c33b9 100644--- a/studio/src-tauri/src/desktop_update_policy.rs+++ b/studio/src-tauri/src/desktop_update_policy.rs@@ -150,7 +150,7 @@ fn validate_channel_metadata(fn desktop_update_mode() -> DesktopUpdateMode {#[cfg(target_os = "linux")]{- if std::env::var_os("APPIMAGE").is_some() {+ if std::env::var_os("APPIMAGE").is_some() || crate::debian_update::is_supported_install() {DesktopUpdateMode::InApp} else {DesktopUpdateMode::ManualLinuxPackagediff --git a/studio/src-tauri/src/desktop_updater.rs b/studio/src-tauri/src/desktop_updater.rsindex 110fb51cfdc..8dcd4e62987 100644--- a/studio/src-tauri/src/desktop_updater.rs+++ b/studio/src-tauri/src/desktop_updater.rs@@ -1,3 +1,4 @@+use base64::Engine;use serde::{Deserialize, Serialize};use sha2::{Digest, Sha256};use std::fs::{self, File};@@ -7,6 +8,30 @@ use std::sync::{Arc, Mutex};use tauri::{AppHandle, Emitter, Manager};use tauri_plugin_updater::{Update, UpdaterExt};+pub(crate) fn verify_bundle_signature(bytes: &[u8], signature: &str) -> Result<(), String> {+ let config: serde_json::Value = serde_json::from_str(include_str!("../tauri.conf.json"))+ .map_err(|error| error.to_string())?;+ let key = config["plugins"]["updater"]["pubkey"]+ .as_str()+ .ok_or("The desktop updater public key is missing.")?;+ verify_signature_with_key(bytes, signature, key)+}++fn verify_signature_with_key(bytes: &[u8], signature: &str, key: &str) -> Result<(), String> {+ let decode = |value: &str| -> Result<String, String> {+ let bytes = base64::engine::general_purpose::STANDARD+ .decode(value)+ .map_err(|error| format!("Invalid updater signature encoding: {error}"))?;+ String::from_utf8(bytes).map_err(|error| error.to_string())+ };+ let key = minisign_verify::PublicKey::decode(&decode(key)?)+ .map_err(|error| format!("Invalid updater public key: {error}"))?;+ let signature = minisign_verify::Signature::decode(&decode(signature)?)+ .map_err(|error| format!("Invalid updater signature: {error}"))?;+ key.verify(bytes, &signature, true)+ .map_err(|error| format!("Desktop update signature verification failed: {error}"))+}+const DOWNLOAD_EVENT: &str = "desktop-update-download";const DOWNLOAD_EVENT_STEP: u64 = 512 * 1024;const BUNDLE_FILE: &str = ".desktop-update-bundle";@@ -213,6 +238,12 @@ pub(crate) async fn check_desktop_update(app.cleanup_before_exit();});+ #[cfg(target_os = "linux")]+ let builder = if crate::debian_update::is_debian_bundle() {+ builder.target(format!("linux-{}-deb", std::env::consts::ARCH))+ } else {+ builder+ };let updater = builder.build().map_err(|error| error.to_string())?;let update = updater.check().await.map_err(|error| error.to_string())?;let mut guard = state.lock().map_err(|error| error.to_string())?;@@ -328,9 +359,22 @@ pub(crate) async fn install_desktop_update(return Err(format!("Prepared update is invalid: {error}"));}};- if let Err(error) = update.install(&bundle) {+ if let Err(error) = verify_bundle_signature(&bundle, &update.signature) {+ discard_prepared_bundle(&path, &metadata);+ return Err(error);+ }+ let result = tokio::task::spawn_blocking(move || {+ #[cfg(target_os = "linux")]+ if crate::debian_update::is_debian_bundle() {+ return crate::debian_update::install(&bundle, &update.signature, &update.version);+ }+ update.install(&bundle).map_err(|error| error.to_string())+ })+ .await+ .map_err(|error| format!("Desktop installer task failed: {error}"))?;+ if let Err(error) = result {discard_prepared_bundle(&path, &metadata);- return Err(error.to_string());+ return Err(error);}discard_prepared_bundle(&path, &metadata);Ok(())@@ -352,6 +396,23 @@ pub(crate) fn desktop_update_bundle_status(mod tests {use super::*;+ const TEST_PUBLIC_KEY: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXkgOEVDM0EzRDFDODFDNjZDNgpSV1RHWmh6STBhUERqdC9BQXhnMEJIcGFLYlVFc2pQbDBid1llM0tRc3FDdERKNVVTbEpZNHQ1bwo=";+ const TEST_SIGNATURE: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUlVUR1poekkwYVBEamxUdGdMVDl5VG1NbWJ0ZEYzcE40UGNRU0VBV3MyNiswOGVpclovSGRkbXBTVDI4Y3MzY3JaaHAyYXlrZUtaREVqYytGUXl1Rm1MWHBVRVpCbE5PNUE4PQp0cnVzdGVkIGNvbW1lbnQ6IHRlc3QgZml4dHVyZQpCeWlPRW53ZzF4azBBdHh4WVhOWENDOGJzMjRFM2Zvc1lTM1BKU1JhV2Z1TzJac0ZmVXhMS1J1TnY4aWl1S2xrWTRMMkd6Wis2ZWloT0pmM2NlOXBBdz09Cg==";++ #[test]+ fn a_rewritten_cache_and_hash_do_not_bypass_the_release_signature() {+ let directory = tempfile::tempdir().unwrap();+ let bundle = directory.path().join(BUNDLE_FILE);+ let metadata = directory.path().join(BUNDLE_METADATA_FILE);+ let original = b"verified update fixture";+ assert!(verify_signature_with_key(original, TEST_SIGNATURE, TEST_PUBLIC_KEY).is_ok());+ persist_prepared_bundle(&bundle, &metadata, "0.1.811-beta", b"substituted package")+ .unwrap();+ let replaced = read_prepared_bundle(&bundle, &metadata, "0.1.811-beta").unwrap();+ assert!(verify_signature_with_key(&replaced, TEST_SIGNATURE, TEST_PUBLIC_KEY).is_err());+ assert!(verify_bundle_signature(original, TEST_SIGNATURE).is_err());+ }+#[test]fn a_prepared_bundle_survives_state_recreation() {let directory = tempfile::tempdir().unwrap();diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rsindex 06284894de3..5fe58264c69 100644--- a/studio/src-tauri/src/main.rs+++ b/studio/src-tauri/src/main.rs@@ -2,6 +2,8 @@mod app_layout;mod commands;+#[cfg(target_os = "linux")]+mod debian_update;mod desktop_auth;mod desktop_backend_owner;mod desktop_update_policy;@@ -2048,6 +2050,17 @@ fn extend_csp_with_hf_endpoints<R: tauri::Runtime>(context: &mut tauri::Context<}fn main() {+ #[cfg(target_os = "linux")]+ if let Some(result) = debian_update::run_installer() {+ match result {+ Ok(()) => std::process::exit(0),+ Err(error) => {+ eprintln!("{error}");+ std::process::exit(1);+ }+ }+ }+// Must precede any Xlib call: GTK3 never calls XInitThreads and this// process drives X from several threads. See x11_threads for the crash.x11_threads::init_x11_threads();diff --git a/studio/src-tauri/tauri.conf.json b/studio/src-tauri/tauri.conf.jsonindex 6001944b065..81ffebdfb81 100644--- a/studio/src-tauri/tauri.conf.json+++ b/studio/src-tauri/tauri.conf.json@@ -89,6 +89,9 @@},"deb": {"desktopTemplate": "./linux/unsloth.desktop",+ "files": {+ "/usr/share/polkit-1/actions/ai.unsloth.studio.update.policy": "./linux/ai.unsloth.studio.update.policy"+ },"provides": ["unsloth-studio-desktop"],"conflicts": ["unsloth-studio-desktop"],"replaces": ["unsloth-studio-desktop"],diff --git a/tests/security/test_release_desktop_appimage.py b/tests/security/test_release_desktop_appimage.pyindex 9a31d030a04..61e59b9d98e 100644--- a/tests/security/test_release_desktop_appimage.py+++ b/tests/security/test_release_desktop_appimage.py@@ -697,6 +697,45 @@ def test_managed_appimage_children_preserve_host_library_paths():assert source_path.read_text(encoding = "utf-8").count(call) == expected+def test_the_deb_ships_the_polkit_action_in_app_debian_updates_authenticate_with():+ # Only this files mapping puts the polkit action on disk, and dropping it fails nothing:+ # is_supported_install() still returns true and every update silently falls back to the+ # release page. The dpkg -L check in desktop-app-clean-machine-ci.yml is stronger but runs+ # only on a non-fork pull request, so it cannot gate a staging replica.+ config = json.loads(+ (REPO_ROOT / "studio/src-tauri/tauri.conf.json").read_text(encoding = "utf-8")+ )+ assert "deb" in config["bundle"]["targets"]+ files = config["bundle"]["linux"]["deb"]["files"]+ action = "/usr/share/polkit-1/actions/ai.unsloth.studio.update.policy"+ assert files[action].endswith("/ai.unsloth.studio.update.policy")++ policy = REPO_ROOT / "studio/src-tauri/linux" / files[action].removeprefix("./linux/")+ source = policy.read_text(encoding = "utf-8")+ assert '<action id="ai.unsloth.studio.update">' in source+ # auth_admin on all three implicit cases is what prompts instead of elevating silently.+ assert source.count("auth_admin") == 3+ # The annotations are what makes this narrower than a plain pkexec call: polkit pins the+ # program and its first argument, so the action cannot run anything else.+ assert (+ '<annotate key="org.freedesktop.policykit.exec.path">/usr/bin/unsloth-studio</annotate>'+ in source+ )+ assert (+ '<annotate key="org.freedesktop.policykit.exec.argv1">--install-debian-update</annotate>'+ in source+ )+ # Those two pins must match what tauri derives from the crate name and what main.rs+ # dispatches on, or polkit refuses every update.+ cargo = (REPO_ROOT / "studio/src-tauri/Cargo.toml").read_text(encoding = "utf-8")+ assert 'name = "unsloth-studio"' in cargo+ debian_update = (REPO_ROOT / "studio/src-tauri/src/debian_update.rs").read_text(+ encoding = "utf-8"+ )+ assert 'const INSTALL_ARGUMENT: &str = "--install-debian-update";' in debian_update+ assert 'const INSTALLED_BINARY: &str = "/usr/bin/unsloth-studio";' in debian_update++def test_release_notes_recommend_native_deb_without_claiming_universality():notes = _workflow()["env"]["DESKTOP_RELEASE_NOTES"]assert "`.AppImage` is experimental." in notesdiff --git a/tests/security/test_release_desktop_integrity.py b/tests/security/test_release_desktop_integrity.pyindex 0562a6e1619..41364b33b3c 100644--- a/tests/security/test_release_desktop_integrity.py+++ b/tests/security/test_release_desktop_integrity.py@@ -159,6 +159,7 @@ def _stage_assets(tmp_path: Path) -> None:for name, payload in (("Unsloth-Desktop-MacOS.dmg", b"disk image"),("Unsloth-Desktop-Ubuntu.deb", b"package"),+ ("Unsloth-Desktop-Ubuntu.deb.sig", signature),("Unsloth-Desktop-ARM64.app.tar.gz", b"mac updater"),("Unsloth-Desktop-ARM64.app.tar.gz.sig", signature),("Unsloth-Desktop-Linux.AppImage", b"linux updater"),@@ -176,9 +177,12 @@ def _run_create_release(tmp_path: Path,*,invalid_signature = False,+ missing_debian_signature = False,**kwargs,):_stage_assets(tmp_path)+ if missing_debian_signature:+ (tmp_path / "desktop-release-assets" / "Unsloth-Desktop-Ubuntu.deb.sig").unlink()if invalid_signature:(tmp_path / "desktop-release-assets" / "Unsloth-Desktop-Linux.AppImage.sig").write_text("Tauri signer diagnostic, not a signature\n", encoding = "utf-8"@@ -318,6 +322,33 @@ def test_publish_rejects_signer_diagnostics_as_updater_signatures(tmp_path):assert not [line for line in commands if line.startswith("gh release create")]+def test_linux_release_stages_the_debian_signature(tmp_path):+ bundles = tmp_path / "bundles"+ bundles.mkdir()+ files = []+ for suffix in ("deb", "deb.sig", "AppImage", "AppImage.sig"):+ path = bundles / f"Unsloth_0.1.50_amd64.{suffix}"+ path.write_text(suffix, encoding = "utf-8")+ files.append(str(path))+ result, _ = _run_step(+ _workflow(),+ "build",+ "Stage release assets",+ tmp_path,+ extra_env = {"ARTIFACT_PATHS": json.dumps(files), "MATRIX_ARTIFACT": "linux"},+ )+ assert result.returncode == 0, result.stderr+ staged = tmp_path / "desktop-release-assets"+ assert (staged / "Unsloth-Desktop-Ubuntu.deb.sig").read_text() == "deb.sig"+ assert (staged / "Unsloth-Desktop-Linux.AppImage.sig").read_text() == "AppImage.sig"+++def test_a_missing_debian_signature_prevents_manifest_publication(tmp_path):+ result, _ = _run_create_release(_workflow(), tmp_path, missing_debian_signature = True)+ assert result.returncode != 0+ assert "Expected exactly one .deb.sig updater asset" in result.stderr++def test_the_publish_sequence_never_rewrites_the_release_body(tmp_path):workflow = _workflow()result, commands = _run_create_release(workflow, tmp_path)@@ -334,6 +365,13 @@ def test_the_publish_sequence_never_rewrites_the_release_body(tmp_path):latest = tmp_path / "latest.json"assert latest.is_file()metadata = yaml.safe_load(latest.read_text(encoding = "utf-8"))+ platforms = metadata["platforms"]+ debian = platforms["linux-x86_64-deb"]+ assert debian["url"].endswith("/Unsloth-Desktop-Ubuntu.deb")+ signature = tmp_path / "desktop-release-assets" / "Unsloth-Desktop-Ubuntu.deb.sig"+ assert debian["signature"] == signature.read_text().strip()+ assert platforms["linux-x86_64-appimage"]["url"].endswith(".AppImage")+ assert platforms["linux-x86_64"] == platforms["linux-x86_64-appimage"]for platform in metadata["platforms"].values():decoded = base64.b64decode(platform["signature"], validate = True)assert decoded.startswith(b"untrusted comment:")diff --git a/tests/studio/test_tauri_branding_contract.py b/tests/studio/test_tauri_branding_contract.pyindex d076a8ace02..5e58f476852 100644--- a/tests/studio/test_tauri_branding_contract.py+++ b/tests/studio/test_tauri_branding_contract.py@@ -183,6 +183,7 @@ def test_desktop_release_asset_names_are_human_readable() -> None:"Linux.AppImage","Linux.AppImage.sig","Ubuntu.deb",+ "Ubuntu.deb.sig","Windows.exe","Windows.exe.sig","Windows-ARM64.exe",