Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(linux): keychain commands store through the Secret Service, else a 0600 file (#226)

purple8b6ee70df71e
diff --git a/e2e/hf-token-linux-file.spec.ts b/e2e/hf-token-linux-file.spec.ts
new file mode 100644
index 00000000..eca65440
--- /dev/null
+++ b/e2e/hf-token-linux-file.spec.ts
@@ -0,0 +1,44 @@
+import { test, expect } from '@playwright/test'
+import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME } from './support/tauri-mock'
+import { seedOnboardingDone } from './support/cloud-mock'
+
+/**
+ * GitHub #226: on a Linux without a Secret Service the Hugging Face token is
+ * saved into a 0600 file by Rust, and the field says so and names the file.
+ * Before 3.1.0 the same click ended in "keychain unsupported on this platform".
+ */
+const SHOTS = process.env.LU_SHOTS_DIR
+const FILE = '/home/you/.local/share/lu-labs/secrets.json'
+
+for (const kind of ['file', 'os'] as const) {
+ test(`the Hugging Face token saves and says where it went (${kind})`, async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 900 })
+ await page.addInitScript(tauriMockInit, {
+ assistantReply: DEFAULT_ASSISTANT_REPLY,
+ modelName: DEFAULT_MODEL_NAME,
+ secretStore: kind === 'file' ? { kind: 'file' as const, path: FILE } : { kind: 'os' as const },
+ })
+ await seedOnboardingDone(page)
+ await page.goto('/')
+ await page.getByRole('banner').getByRole('button', { name: 'Settings', exact: true }).click()
+ const field = page.getByLabel('Hugging Face token')
+ for (const tab of ['General', 'AI Backends', 'Agent', 'Voice & Remote']) {
+ if (await field.isVisible()) break
+ await page.getByRole('button', { name: tab }).first().click()
+ const section = page.getByRole('button', { name: 'Hugging Face token' })
+ if ((await section.count()) && (await section.first().getAttribute('aria-expanded')) === 'false') await section.first().click()
+ }
+ await field.fill('hf_e2e_token')
+ await page.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect(page.getByRole('button', { name: 'Saved' })).toBeVisible()
+ await expect(page.getByRole('alert')).toHaveCount(0)
+ const note = page.getByRole('status').filter({ hasText: 'No system keyring answered' })
+ if (kind === 'file') {
+ await expect(note).toContainText(FILE)
+ await note.scrollIntoViewIfNeeded()
+ if (SHOTS) await page.screenshot({ path: `${SHOTS}/226-hf-token-datei-hinweis.png` })
+ } else {
+ await expect(note).toHaveCount(0)
+ }
+ })
+}
diff --git a/e2e/support/tauri-mock.ts b/e2e/support/tauri-mock.ts
index 29e48973..4075b109 100644
--- a/e2e/support/tauri-mock.ts
+++ b/e2e/support/tauri-mock.ts
@@ -165,6 +165,8 @@ export interface TauriMockOptions {
* behaviour must pin it; the default matches the historical CI target.
*/
platform?: 'mac' | 'windows'
+ /** What `secret_store_info` answers (GitHub #226). Default: the OS store. */
+ secretStore?: { kind: 'os' | 'file' | 'none'; path?: string | null }
/**
* Deliver `assistantReply` as N separate SSE frames, `replyChunkDelayMs`
* apart, instead of one. A real engine emits a frame per token, which is what
@@ -2019,6 +2021,8 @@ export function tauriMockInit(opts: TauriMockOptions) {
if (w.__E2E_SECRETS__) delete w.__E2E_SECRETS__[args?.account]
return Promise.resolve(null)
}
+ case 'secret_store_info':
+ return Promise.resolve(opts.secretStore ?? { kind: 'os' })
// ── agent file/shell tools ────────────────────────────────────
// Enough of the bridge for the ReAct loop to actually complete a step.
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index f9541040..41efbfc9 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -8,6 +8,17 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aes"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1"
+dependencies = [
+ "cipher",
+ "cpubits",
+ "cpufeatures 0.3.1",
+]
+
[[package]]
name = "aho-corasick"
version = "1.1.4"
@@ -412,7 +423,7 @@ version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
dependencies = [
- "digest",
+ "digest 0.10.7",
]
[[package]]
@@ -424,6 +435,24 @@ dependencies = [
"generic-array",
]
+[[package]]
+name = "block-buffer"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "block-padding"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"
+dependencies = [
+ "hybrid-array",
+]
+
[[package]]
name = "block2"
version = "0.6.2"
@@ -581,6 +610,15 @@ dependencies = [
"toml 0.9.12+spec-1.1.0",
]
+[[package]]
+name = "cbc"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"
+dependencies = [
+ "cipher",
+]
+
[[package]]
name = "cc"
version = "1.2.61"
@@ -676,6 +714,16 @@ dependencies = [
"windows-link 0.2.1",
]
+[[package]]
+name = "cipher"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
+dependencies = [
+ "crypto-common 0.2.2",
+ "inout",
+]
+
[[package]]
name = "clang-sys"
version = "1.9.1"
@@ -696,6 +744,12 @@ dependencies = [
"cc",
]
+[[package]]
+name = "cmov"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
+
[[package]]
name = "combine"
version = "4.6.7"
@@ -715,6 +769,12 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "const-oid"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
+
[[package]]
name = "const-random"
version = "0.1.18"
@@ -807,6 +867,12 @@ dependencies = [
"libc",
]
+[[package]]
+name = "cpubits"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
+
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -884,6 +950,15 @@ dependencies = [
"typenum",
]
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "hybrid-array",
+]
+
[[package]]
name = "cssparser"
version = "0.29.6"
@@ -934,6 +1009,15 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "ctutils"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
+dependencies = [
+ "cmov",
+]
+
[[package]]
name = "curve25519-dalek"
version = "4.1.3"
@@ -1127,11 +1211,23 @@ version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
- "block-buffer",
- "crypto-common",
+ "block-buffer 0.10.4",
+ "crypto-common 0.1.7",
"subtle",
]
+[[package]]
+name = "digest"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
+dependencies = [
+ "block-buffer 0.12.1",
+ "const-oid",
+ "crypto-common 0.2.2",
+ "ctutils",
+]
+
[[package]]
name = "dirs"
version = "6.0.0"
@@ -2193,6 +2289,24 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+[[package]]
+name = "hkdf"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
+dependencies = [
+ "hmac",
+]
+
+[[package]]
+name = "hmac"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
+dependencies = [
+ "digest 0.11.3",
+]
+
[[package]]
name = "home"
version = "0.5.12"
@@ -2292,6 +2406,15 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
+[[package]]
+name = "hybrid-array"
+version = "0.4.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3944cf8cf766b40e2a1a333ee5e9b563f854d5fa49d6a8ca2764e97c6eddb214"
+dependencies = [
+ "typenum",
+]
+
[[package]]
name = "hyper"
version = "1.8.1"
@@ -2579,6 +2702,16 @@ dependencies = [
"cfb",
]
+[[package]]
+name = "inout"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
+dependencies = [
+ "block-padding",
+ "hybrid-array",
+]
+
[[package]]
name = "ipnet"
version = "2.12.0"
@@ -3032,10 +3165,11 @@ dependencies = [
"reqwest 0.12.28",
"rfd",
"ring",
+ "secret-service",
"serde",
"serde_json",
"serde_yaml",
- "sha2",
+ "sha2 0.10.9",
"snow",
"socket2 0.5.10",
"sysinfo",
@@ -3389,6 +3523,20 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "num"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
+dependencies = [
+ "num-bigint",
+ "num-complex",
+ "num-integer",
+ "num-iter",
+ "num-rational",
+ "num-traits",
+]
+
[[package]]
name = "num-bigint"
version = "0.4.6"
@@ -3399,6 +3547,15 @@ dependencies = [
"num-traits",
]
+[[package]]
+name = "num-complex"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "num-conv"
version = "0.2.1"
@@ -3414,6 +3571,27 @@ dependencies = [
"num-traits",
]
+[[package]]
+name = "num-iter"
+version = "0.1.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-rational"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
+dependencies = [
+ "num-bigint",
+ "num-integer",
+ "num-traits",
+]
+
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -5094,6 +5272,25 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "secret-service"
+version = "5.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8"
+dependencies = [
+ "aes",
+ "cbc",
+ "futures-util",
+ "getrandom 0.4.2",
+ "hkdf",
+ "hybrid-array",
+ "num",
+ "once_cell",
+ "serde",
+ "sha2 0.11.1",
+ "zbus",
+]
+
[[package]]
name = "security-framework"
version = "2.11.1"
@@ -5388,7 +5585,7 @@ checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
- "digest",
+ "digest 0.10.7",
]
[[package]]
@@ -5399,7 +5596,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
- "digest",
+ "digest 0.10.7",
+]
+
+[[package]]
+name = "sha2"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.1",
+ "digest 0.11.3",
]
[[package]]
@@ -5511,7 +5719,7 @@ dependencies = [
"getrandom 0.3.4",
"ring",
"rustc_version",
- "sha2",
+ "sha2 0.10.9",
"subtle",
]
@@ -5944,7 +6152,7 @@ dependencies = [
"semver",
"serde",
"serde_json",
- "sha2",
+ "sha2 0.10.9",
"syn 2.0.117",
"tauri-utils",
"thiserror 2.0.18",
@@ -6030,7 +6238,7 @@ dependencies = [
"reqwest 0.12.28",
"serde",
"serde_json",
- "sha2",
+ "sha2 0.10.9",
"tauri",
"tauri-plugin",
"tokio",
@@ -6362,6 +6570,7 @@ dependencies = [
"signal-hook-registry",
"socket2 0.6.3",
"tokio-macros",
+ "tracing",
"windows-sys 0.61.2",
]
@@ -8163,7 +8372,7 @@ dependencies = [
"once_cell",
"percent-encoding",
"raw-window-handle",
- "sha2",
+ "sha2 0.10.9",
"soup3",
"tao-macros",
"thiserror 2.0.18",
@@ -8338,6 +8547,7 @@ dependencies = [
"rustix 1.1.4",
"serde",
"serde_repr",
+ "tokio",
"tracing",
"uds_windows",
"uuid",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index f3b2e65d..f4dcb094 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -319,6 +319,15 @@ x11rb = { version = "0.13", features = ["randr"] }
# The web view on Linux, already in Cargo.lock through tauri and wry. Only for
# answering its microphone requests (src/linux_media.rs, GitHub #162).
webkit2gtk = "=2.0.2"
+# The Secret Service client for the keychain commands on Linux (GitHub #226):
+# GNOME Keyring, KWallet 6, KeePassXC and every other org.freedesktop.secrets
+# provider. MIT OR Apache-2.0, by the keyring-rs maintainers. Pure Rust over the
+# zbus 5 that rfd and the single-instance plugin already bring, so no libdbus
+# or libsecret at build or run time. crypto-rust: the secret crosses the bus
+# encrypted (dh-ietf1024-sha256-aes128-cbc-pkcs7), as libsecret does it.
+# keyring 3's own Linux features were no option: its async backend wants zbus 4
+# (a second copy of the bus stack), its sync one links libdbus.
+secret-service = { version = "=5.2.0", default-features = false, features = ["rt-tokio-crypto-rust"] }
[profile.release]
panic = "abort"
diff --git a/src-tauri/src/commands/mobile_guard.rs b/src-tauri/src/commands/mobile_guard.rs
index f31d69ec..2d95e3b7 100644
--- a/src-tauri/src/commands/mobile_guard.rs
+++ b/src-tauri/src/commands/mobile_guard.rs
@@ -249,6 +249,8 @@ pub const ALLOWED: &[&str] = &[
"secret_delete",
"secret_park_set",
"secret_park_get",
+ // Where secrets land; on a phone always "os" (Keystore / Keychain), reads nothing.
+ "secret_store_info",
"secret_park_delete",
// Remote client: private addresses and *.trycloudflare.com only. The
// plain one only in the Wi-Fi (and the bare status over the tunnel).
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index 5e118fba..bbc48b52 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -105,6 +105,13 @@ pub mod saved_characters_backup;
pub mod search;
pub mod search_tiers;
pub mod secret;
+// Where the keychain commands keep values on Linux (GitHub #226). The file
+// store is built for the tests everywhere, it is plain std.
+#[cfg(any(all(desktop, target_os = "linux"), test))]
+#[cfg_attr(not(all(desktop, target_os = "linux")), allow(dead_code))]
+pub mod secret_file;
+#[cfg(all(desktop, target_os = "linux"))]
+pub mod secret_linux;
pub mod shell;
pub mod system;
pub mod torch_wheels;
diff --git a/src-tauri/src/commands/secret.rs b/src-tauri/src/commands/secret.rs
index d37d7d72..5c73e2a3 100644
--- a/src-tauri/src/commands/secret.rs
+++ b/src-tauri/src/commands/secret.rs
@@ -16,11 +16,10 @@
//! short values are stored identically on both platforms, and plain values
//! written by older builds read back unchanged.
//!
-//! Linux desktop and the web build have no robust uniform secret store here
-//! (the secret-service backend needs libdbus/gnome-keyring and breaks on
-//! headless/minimal setups), so those keep the obfuscated-localStorage path:
-//! on those targets the commands compile to a stub that reports "unsupported",
-//! and the frontend (providerStore.hydrateProviderKeys) falls back.
+//! Linux desktop (since 3.1.0, GitHub #226) stores through the desktop's
+//! Secret Service, with a 0600 file in the app's data folder where none
+//! answers: `secret_linux` and `secret_file`. The web build has no Rust side;
+//! there the frontend keeps its obfuscated-localStorage path.
/// Keychain service name. The "account" is the provider id (ollama / openai /
/// anthropic). Keep this stable: changing it would orphan stored keys.
@@ -30,7 +29,7 @@
/// mehr und legt beim nächsten Speichern einen zweiten Satz daneben. Deshalb
/// kommt er aus `crate::app_identity`, wo ein Test seinen Wert festhält, und
/// nicht als Literal aus dieser Datei.
-#[cfg(any(target_os = "windows", target_os = "macos"))]
+#[cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))]
const SERVICE: &str = crate::app_identity::KEYCHAIN_SERVICE;
// ── T-61: the account name is an argument, so it needs an allowlist ─────────
@@ -328,7 +327,7 @@ mod chunked {
/// so a same-user process cannot drop `~/.lu-no-keychain` (or set the env var) to
/// silently downgrade the Supabase session + provider keys to plaintext
/// localStorage. Only builds made with `--features insecure-test-keychain` honor it.
-#[cfg(any(target_os = "windows", target_os = "macos"))]
+#[cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))]
fn keychain_disabled() -> bool {
#[cfg(not(feature = "insecure-test-keychain"))]
{
@@ -549,47 +548,158 @@ pub async fn secret_park_delete(app: tauri::AppHandle, backend_id: String) -> Re
crate::commands::mobile_native::vault(app, move |v| v.secret_delete(&account)).await
}
-// ── Non-keychain platforms (Linux desktop) ──────────────────────────────
-// The commands still exist so `invoke('secret_get', …)` resolves, but they
-// report unsupported. The frontend treats any error here as "no keychain" and
-// keeps using the obfuscated-localStorage path — identical to today's behavior.
+// ── Linux desktop (GitHub #226) ─────────────────────────────────────────
+// The Secret Service, or the 0600 file where none answers. One async lock
+// serializes the operations, as KEYCHAIN_LOCK does on Windows and macOS: the
+// file is read, changed and written back whole.
+
+#[cfg(all(desktop, target_os = "linux"))]
+static LINUX_VAULT_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+
+#[cfg(all(desktop, target_os = "linux"))]
+fn linux_vault() -> super::secret_linux::LinuxVault {
+ super::secret_linux::LinuxVault::new(
+ SERVICE,
+ super::secret_file::FileStore::new(crate::os_paths::data_dir().join(super::secret_file::FILE_NAME)),
+ )
+}
+
+#[cfg(all(desktop, target_os = "linux"))]
+fn linux_disabled() -> Result<(), String> {
+ if keychain_disabled() {
+ return Err("keychain unavailable (LU_NO_KEYCHAIN test mode)".into());
+ }
+ Ok(())
+}
+
+#[cfg(all(desktop, target_os = "linux"))]
+#[tauri::command]
+pub async fn secret_set(account: String, value: String) -> Result<(), String> {
+ check_account(&account)?;
+ linux_disabled()?;
+ let _serialized = LINUX_VAULT_LOCK.lock().await;
+ linux_vault().set(&account, &value).await.map(|_| ())
+}
+
+#[cfg(all(desktop, target_os = "linux"))]
+#[tauri::command]
+pub async fn secret_get(account: String) -> Result<Option<String>, String> {
+ check_account(&account)?;
+ linux_disabled()?;
+ let _serialized = LINUX_VAULT_LOCK.lock().await;
+ linux_vault().get(&account).await
+}
+
+#[cfg(all(desktop, target_os = "linux"))]
+#[tauri::command]
+pub async fn secret_delete(account: String) -> Result<(), String> {
+ check_account(&account)?;
+ linux_disabled()?;
+ let _serialized = LINUX_VAULT_LOCK.lock().await;
+ linux_vault().delete(&account).await
+}
+
+#[cfg(all(desktop, target_os = "linux"))]
+#[tauri::command]
+pub async fn secret_park_set(backend_id: String, value: String) -> Result<(), String> {
+ let account = parked_account(&backend_id)?;
+ linux_disabled()?;
+ let _serialized = LINUX_VAULT_LOCK.lock().await;
+ linux_vault().set(&account, &value).await.map(|_| ())
+}
+
+#[cfg(all(desktop, target_os = "linux"))]
+#[tauri::command]
+pub async fn secret_park_get(backend_id: String) -> Result<Option<String>, String> {
+ let account = parked_account(&backend_id)?;
+ linux_disabled()?;
+ let _serialized = LINUX_VAULT_LOCK.lock().await;
+ linux_vault().get(&account).await
+}
+
+#[cfg(all(desktop, target_os = "linux"))]
+#[tauri::command]
+pub async fn secret_park_delete(backend_id: String) -> Result<(), String> {
+ let account = parked_account(&backend_id)?;
+ linux_disabled()?;
+ let _serialized = LINUX_VAULT_LOCK.lock().await;
+ linux_vault().delete(&account).await
+}
+
+// ── Where secrets go on this machine ────────────────────────────────────
+// For the hint under the Hugging Face token field. `kind` is "os" (the
+// platform's credential store), "file" (Linux without a Secret Service:
+// `path` names the 0600 file) or "none" (no Rust-side store at all).
+
+#[derive(serde::Serialize)]
+pub struct SecretStoreInfo {
+ kind: &'static str,
+ path: Option<String>,
+}
+
+#[cfg(all(desktop, target_os = "linux"))]
+#[tauri::command]
+pub async fn secret_store_info() -> SecretStoreInfo {
+ if keychain_disabled() {
+ return SecretStoreInfo { kind: "none", path: None };
+ }
+ let vault = linux_vault();
+ match vault.target().await {
+ super::secret_linux::Where::Keyring => SecretStoreInfo { kind: "os", path: None },
+ super::secret_linux::Where::File => SecretStoreInfo {
+ kind: "file",
+ path: Some(vault.file().path().display().to_string()),
+ },
+ }
+}
+
+#[cfg(not(all(desktop, target_os = "linux")))]
+#[tauri::command]
+pub async fn secret_store_info() -> SecretStoreInfo {
+ let kind = if cfg!(any(mobile, target_os = "windows", target_os = "macos")) { "os" } else { "none" };
+ SecretStoreInfo { kind, path: None }
+}
+
+// ── Other desktop systems ───────────────────────────────────────────────
+// LU ships for none, the stub only keeps the crate building there. The
+// frontend treats the error as "no keychain" and keeps its localStorage path.
-#[cfg(all(desktop, not(any(target_os = "windows", target_os = "macos"))))]
+#[cfg(all(desktop, not(any(target_os = "windows", target_os = "macos", target_os = "linux"))))]
#[tauri::command]
pub fn secret_set(account: String, _value: String) -> Result<(), String> {
check_account(&account)?;
Err("keychain unsupported on this platform".into())
}
-#[cfg(all(desktop, not(any(target_os = "windows", target_os = "macos"))))]
+#[cfg(all(desktop, not(any(target_os = "windows", target_os = "macos", target_os = "linux"))))]
#[tauri::command]
pub fn secret_get(account: String) -> Result<Option<String>, String> {
check_account(&account)?;
Err("keychain unsupported on this platform".into())
}
-#[cfg(all(desktop, not(any(target_os = "windows", target_os = "macos"))))]
+#[cfg(all(desktop, not(any(target_os = "windows", target_os = "macos", target_os = "linux"))))]
#[tauri::command]
pub fn secret_delete(account: String) -> Result<(), String> {
check_account(&account)?;
Err("keychain unsupported on this platform".into())
}
-#[cfg(all(desktop, not(any(target_os = "windows", target_os = "macos"))))]
+#[cfg(all(desktop, not(any(target_os = "windows", target_os = "macos", target_os = "linux"))))]
#[tauri::command]
pub fn secret_park_set(backend_id: String, _value: String) -> Result<(), String> {
parked_account(&backend_id)?;
Err("keychain unsupported on this platform".into())
}
-#[cfg(all(desktop, not(any(target_os = "windows", target_os = "macos"))))]
+#[cfg(all(desktop, not(any(target_os = "windows", target_os = "macos", target_os = "linux"))))]
#[tauri::command]
pub fn secret_park_get(backend_id: String) -> Result<Option<String>, String> {
parked_account(&backend_id)?;
Err("keychain unsupported on this platform".into())
}
-#[cfg(all(desktop, not(any(target_os = "windows", target_os = "macos"))))]
+#[cfg(all(desktop, not(any(target_os = "windows", target_os = "macos", target_os = "linux"))))]
#[tauri::command]
pub fn secret_park_delete(backend_id: String) -> Result<(), String> {
parked_account(&backend_id)?;
@@ -776,10 +886,11 @@ mod account_allowlist_tests {
}
/// Every command body checks the name before it does anything else.
- /// Eighteen commands total: the original three (account allowlist) plus
- /// the three R9 parked-key commands (backend-id pattern), each present
- /// once for the keychain platforms, once for the phones and once for the
- /// stub platforms.
+ /// Twenty-four value commands: the original three (account allowlist)
+ /// plus the three R9 parked-key commands (backend-id pattern), each
+ /// present once for Windows/macOS, once for the phones, once for Linux
+ /// (GitHub #226) and once for the stub platforms. Plus the two
+ /// `secret_store_info` variants, which take no name and touch no value.
#[test]
fn no_command_reaches_the_vault_without_the_check() {
const SECRET_RS: &str = include_str!("secret.rs");
@@ -792,13 +903,15 @@ mod account_allowlist_tests {
let parked_checks = SECRET_RS
.matches(concat!("parked_account", "(&backend_id)?;"))
.count();
- assert_eq!(commands, 18, "command count changed, recount the checks");
+ let info = SECRET_RS.matches(concat!("pub async fn secret_store", "_info()")).count();
+ assert_eq!(info, 2, "secret_store_info changed, recount the checks");
+ assert_eq!(commands - info, 24, "command count changed, recount the checks");
assert_eq!(
- account_checks, 9,
+ account_checks, 12,
"a plain secret command runs without the account name check"
);
assert_eq!(
- parked_checks, 9,
+ parked_checks, 12,
"a parked-key command runs without the backend-id check"
);
}
diff --git a/src-tauri/src/commands/secret_file.rs b/src-tauri/src/commands/secret_file.rs
new file mode 100644
index 00000000..833d509d
--- /dev/null
+++ b/src-tauri/src/commands/secret_file.rs
@@ -0,0 +1,246 @@
+//! The file the keychain commands fall back to on Linux (GitHub #226).
+//!
+//! Linux has no credential store every desktop ships. Most run a Secret
+//! Service (GNOME Keyring, KWallet 6, KeePassXC), and `secret_linux` uses it
+//! whenever one answers. A tiling-WM setup, a minimal install or a fresh
+//! Omarchy box may have none, and before this the HF token, the provider keys
+//! and the LU Cloud session could then not be stored by Rust at all.
+//!
+//! This is the same posture `huggingface-cli` takes with
+//! `~/.cache/huggingface/token`, and ssh with `~/.ssh/id_*`: one JSON object
+//! of account → value in the app's data folder, mode 0600 in a folder only
+//! the user can enter. It keeps the value from other local users, not from
+//! code running as the same user, and the Settings page says so when this
+//! file is what took the value (`secret_store_info`).
+//!
+//! Writes go to a fresh temporary file created with 0600 and are renamed over
+//! the old one, so a crash mid-write never leaves half a file or a moment
+//! with looser permissions. The caller serializes access.
+
+use std::collections::BTreeMap;
+use std::fs;
+use std::io::Write;
+use std::path::{Path, PathBuf};
+
+/// Name of the file inside the app's data folder.
+pub const FILE_NAME: &str = "secrets.json";
+
+#[derive(Debug, Clone)]
+pub struct FileStore {
+ path: PathBuf,
+}
+
+impl FileStore {
+ pub fn new(path: PathBuf) -> Self {
+ Self { path }
+ }
+
+ pub fn path(&self) -> &Path {
+ &self.path
+ }
+
+ pub fn get(&self, account: &str) -> Result<Option<String>, String> {
+ Ok(self.load()?.remove(account))
+ }
+
+ pub fn set(&self, account: &str, value: &str) -> Result<(), String> {
+ let mut map = self.load_for_write()?;
+ map.insert(account.to_string(), value.to_string());
+ self.save(&map)
+ }
+
+ pub fn delete(&self, account: &str) -> Result<(), String> {
+ let mut map = self.load_for_write()?;
+ if map.remove(account).is_none() {
+ return Ok(());
+ }
+ self.save(&map)
+ }
+
+ fn load(&self) -> Result<BTreeMap<String, String>, String> {
+ let bytes = match fs::read(&self.path) {
+ Ok(b) => b,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
+ Err(e) => return Err(format!("could not read {}: {}", self.path.display(), crate::os_error::english(&e))),
+ };
+ self.tighten();
+ serde_json::from_slice(&bytes)
+ .map_err(|e| format!("{} is not a valid secret file: {e}", self.path.display()))
+ }
+
+ /// Like `load`, but a damaged file does not block every later save
+ /// forever: it is moved aside (kept, never deleted) and the write starts
+ /// from an empty store.
+ fn load_for_write(&self) -> Result<BTreeMap<String, String>, String> {
+ match self.load() {
+ Ok(m) => Ok(m),
+ Err(e) if self.path.exists() => {
+ let aside = self.path.with_extension(format!(
+ "json.damaged-{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0)
+ ));
+ tracing::warn!(error = %e, aside = %aside.display(), "moved a damaged secret file aside");
+ fs::rename(&self.path, &aside).map_err(|e| format!("could not move the damaged secret file aside: {}", crate::os_error::english(&e)))?;
+ Ok(BTreeMap::new())
+ }
+ Err(e) => Err(e),
+ }
+ }
+
+ fn save(&self, map: &BTreeMap<String, String>) -> Result<(), String> {
+ if map.is_empty() {
+ return match fs::remove_file(&self.path) {
+ Ok(()) => Ok(()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(format!("could not remove {}: {}", self.path.display(), crate::os_error::english(&e))),
+ };
+ }
+ let dir = self
+ .path
+ .parent()
+ .ok_or_else(|| format!("{} has no parent folder", self.path.display()))?;
+ create_private_dir(dir)?;
+ let tmp = dir.join(format!(".{FILE_NAME}.{}.tmp", std::process::id()));
+ // A leftover from a crash keeps its old mode through `open`, so it goes first.
+ let _ = fs::remove_file(&tmp);
+ let json = serde_json::to_vec_pretty(map).map_err(|_| "could not encode the secret file".to_string())?;
+ let write = || -> std::io::Result<()> {
+ let mut f = private_create(&tmp)?;
+ f.write_all(&json)?;
+ f.sync_all()?;
+ fs::rename(&tmp, &self.path)
+ };
+ write().map_err(|e| {
+ let _ = fs::remove_file(&tmp);
+ format!("could not write {}: {}", self.path.display(), crate::os_error::english(&e))
+ })
+ }
+
+ /// A file copied in from elsewhere, or written by a looser umask before
+ /// this existed, is brought back to 0600 whenever it is read.
+ fn tighten(&self) {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ if let Ok(meta) = fs::metadata(&self.path) {
+ if meta.permissions().mode() & 0o077 != 0 {
+ let _ = fs::set_permissions(&self.path, fs::Permissions::from_mode(0o600));
+ }
+ }
+ }
+ }
+}
+
+fn private_create(path: &Path) -> std::io::Result<fs::File> {
+ let mut opts = fs::OpenOptions::new();
+ opts.write(true).create_new(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ opts.mode(0o600);
+ }
+ opts.open(path)
+}
+
+fn create_private_dir(dir: &Path) -> Result<(), String> {
+ if !dir.exists() {
+ fs::create_dir_all(dir).map_err(|e| format!("could not create {}: {}", dir.display(), crate::os_error::english(&e)))?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = fs::set_permissions(dir, fs::Permissions::from_mode(0o700));
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn store() -> (tempfile::TempDir, FileStore) {
+ let dir = tempfile::tempdir().unwrap();
+ let s = FileStore::new(dir.path().join("lu").join(FILE_NAME));
+ (dir, s)
+ }
+
+ #[test]
+ fn set_get_delete_round_trip() {
+ let (_d, s) = store();
+ assert_eq!(s.get("huggingface-token").unwrap(), None);
+ s.set("huggingface-token", "hf_abc").unwrap();
+ s.set("openai", "sk-1").unwrap();
+ assert_eq!(s.get("huggingface-token").unwrap().as_deref(), Some("hf_abc"));
+ s.set("huggingface-token", "hf_new").unwrap();
+ assert_eq!(s.get("huggingface-token").unwrap().as_deref(), Some("hf_new"));
+ s.delete("huggingface-token").unwrap();
+ assert_eq!(s.get("huggingface-token").unwrap(), None);
+ assert_eq!(s.get("openai").unwrap().as_deref(), Some("sk-1"));
+ s.delete("openai").unwrap();
+ assert!(!s.path().exists(), "an empty store leaves no file behind");
+ s.delete("never-there").unwrap();
+ }
+
+ #[test]
+ fn long_values_are_kept_whole() {
+ // The Cloud session JSON is several KB; nothing here chunks it.
+ let (_d, s) = store();
+ let big = "x".repeat(16 * 1024);
+ s.set("lu-cloud-session", &big).unwrap();
+ assert_eq!(s.get("lu-cloud-session").unwrap().as_deref(), Some(big.as_str()));
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn the_file_is_0600_and_a_new_folder_0700() {
+ use std::os::unix::fs::PermissionsExt;
+ let (_d, s) = store();
+ s.set("huggingface-token", "hf_abc").unwrap();
+ let mode = fs::metadata(s.path()).unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode, 0o600);
+ let dir_mode = fs::metadata(s.path().parent().unwrap()).unwrap().permissions().mode() & 0o777;
+ assert_eq!(dir_mode, 0o700);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn a_loose_file_is_tightened_on_read() {
+ use std::os::unix::fs::PermissionsExt;
+ let (_d, s) = store();
+ s.set("openai", "sk-1").unwrap();
+ fs::set_permissions(s.path(), fs::Permissions::from_mode(0o644)).unwrap();
+ assert_eq!(s.get("openai").unwrap().as_deref(), Some("sk-1"));
+ let mode = fs::metadata(s.path()).unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode, 0o600);
+ }
+
+ #[test]
+ fn a_damaged_file_is_moved_aside_not_lost() {
+ let (_d, s) = store();
+ fs::create_dir_all(s.path().parent().unwrap()).unwrap();
+ fs::write(s.path(), b"{not json").unwrap();
+ assert!(s.get("openai").is_err(), "a read reports the damage");
+ s.set("openai", "sk-2").unwrap();
+ assert_eq!(s.get("openai").unwrap().as_deref(), Some("sk-2"));
+ let kept = fs::read_dir(s.path().parent().unwrap())
+ .unwrap()
+ .filter_map(|e| e.ok())
+ .any(|e| e.file_name().to_string_lossy().contains("damaged"));
+ assert!(kept, "the damaged file is kept next to the new one");
+ }
+
+ #[test]
+ fn no_temporary_file_is_left_behind() {
+ let (_d, s) = store();
+ s.set("openai", "sk-1").unwrap();
+ let names: Vec<String> = fs::read_dir(s.path().parent().unwrap())
+ .unwrap()
+ .filter_map(|e| e.ok())
+ .map(|e| e.file_name().to_string_lossy().into_owned())
+ .collect();
+ assert_eq!(names, vec![FILE_NAME.to_string()]);
+ }
+}
diff --git a/src-tauri/src/commands/secret_linux.rs b/src-tauri/src/commands/secret_linux.rs
new file mode 100644
index 00000000..ebeff056
--- /dev/null
+++ b/src-tauri/src/commands/secret_linux.rs
@@ -0,0 +1,226 @@
+//! The keychain commands on Linux (GitHub #226).
+//!
+//! Until 3.1.0 every `secret_*` command on Linux answered "keychain
+//! unsupported on this platform". The provider keys and the Cloud session had
+//! a localStorage fallback in the frontend, the Hugging Face token had none,
+//! so on Linux it could not be saved at all.
+//!
+//! Now the store of record is the desktop's Secret Service
+//! (org.freedesktop.secrets: GNOME Keyring, KWallet 6, KeePassXC, …) over the
+//! session bus, with the secret encrypted in transit as libsecret does it.
+//! Where none answers, or it has no default collection, the value goes to
+//! `secret_file` (0600 in the app's data folder) instead, and
+//! `secret_store_info` tells the Settings page so it can say where the value
+//! went.
+//!
+//! The frontend needed no change for the move: `hydrateProviderKeys` and the
+//! Cloud storage adapter already migrate a localStorage copy into the vault
+//! the first time the vault answers, exactly as they did on Windows and macOS.
+//!
+//! Rules:
+//! * Reads ask the Secret Service first. A value found only in the file
+//! (written while no Secret Service ran) is moved into it.
+//! * A dismissed unlock prompt or a Secret Service error is reported, never
+//! answered by a silent write to the file: the user said no to the
+//! keyring, not yes to a file.
+//! * No error text here contains "keychain unavailable" or "keychain
+//! unsupported". Those two make the frontend latch onto its localStorage
+//! path for the rest of the session (`keychainMissing`), and this backend
+//! always has somewhere to put a value.
+
+use std::collections::HashMap;
+use std::time::Duration;
+
+use secret_service::{EncryptionType, Error as SsError, SecretService};
+
+use super::secret_file::FileStore;
+
+/// How long the session bus gets to hand out a Secret Service session. A
+/// missing bus or provider fails at once; this only bounds a hung one.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
+
+/// A whole operation, unlock prompt included. The prompt waits on the user.
+const OP_TIMEOUT: Duration = Duration::from_secs(180);
+
+/// Where a write lands right now.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Where {
+ /// The desktop's Secret Service.
+ Keyring,
+ /// The 0600 file.
+ File,
+}
+
+pub struct LinuxVault {
+ service: String,
+ file: FileStore,
+}
+
+fn err(e: SsError) -> String {
+ match e {
+ SsError::Prompt => "keyring locked: the unlock prompt was dismissed".into(),
+ SsError::PromptDisconnected => "keyring locked: the unlock prompt went away without an answer".into(),
+ SsError::Locked => "keyring locked".into(),
+ e => format!("keyring error: {e}"),
+ }
+}
+
+impl LinuxVault {
+ pub fn new(service: impl Into<String>, file: FileStore) -> Self {
+ Self { service: service.into(), file }
+ }
+
+ pub fn file(&self) -> &FileStore {
+ &self.file
+ }
+
+ /// Search attributes. `service` + `username` is the layout keyring-rs and
+ /// most other tools use, so `secret-tool lookup service … username …`
+ /// finds the entry too.
+ fn attrs<'a>(&'a self, account: &'a str) -> HashMap<&'a str, &'a str> {
+ HashMap::from([("service", self.service.as_str()), ("username", account)])
+ }
+
+ /// A Secret Service session, or None when there is none to be had.
+ async fn connect(&self) -> Option<SecretService<'static>> {
+ for (enc, name) in [(EncryptionType::Dh, "dh"), (EncryptionType::Plain, "plain")] {
+ match tokio::time::timeout(CONNECT_TIMEOUT, SecretService::connect(enc)).await {
+ Ok(Ok(ss)) => return Some(ss),
+ // No bus, no provider on it: nothing a second try changes.
+ Ok(Err(SsError::Unavailable)) => {
+ tracing::debug!("no Secret Service on the session bus");
+ return None;
+ }
+ Ok(Err(e)) => tracing::debug!(error = %e, session = name, "Secret Service session refused"),
+ Err(_) => {
+ tracing::warn!("Secret Service did not answer within {CONNECT_TIMEOUT:?}");
+ return None;
+ }
+ }
+ }
+ None
+ }
+
+ async fn bounded<T>(fut: impl std::future::Future<Output = Result<T, String>>) -> Result<T, String> {
+ tokio::time::timeout(OP_TIMEOUT, fut)
+ .await
+ .unwrap_or_else(|_| Err(format!("keyring did not answer within {} s", OP_TIMEOUT.as_secs())))
+ }
+
+ pub async fn get(&self, account: &str) -> Result<Option<String>, String> {
+ Self::bounded(async {
+ let Some(ss) = self.connect().await else {
+ return self.file.get(account);
+ };
+ if let Some(v) = self.keyring_get(&ss, account).await? {
+ return Ok(Some(v));
+ }
+ // Written in a session that had no Secret Service: move it over.
+ let Some(v) = self.file.get(account)? else { return Ok(None) };
+ match self.keyring_set(&ss, account, &v).await {
+ Ok(true) => {
+ if let Err(e) = self.file.delete(account) {
+ tracing::warn!(error = %e, "moved a secret into the keyring, the file copy stays");
+ }
+ }
+ Ok(false) => {}
+ Err(e) => tracing::debug!(error = %e, "could not move a secret from the file into the keyring yet"),
+ }
+ Ok(Some(v))
+ })
+ .await
+ }
+
+ /// Stores `value` (empty means delete) and says where it went.
+ pub async fn set(&self, account: &str, value: &str) -> Result<Where, String> {
+ if value.is_empty() {
+ self.delete(account).await?;
+ return Ok(self.target().await);
+ }
+ Self::bounded(async {
+ if let Some(ss) = self.connect().await {
+ if self.keyring_set(&ss, account, value).await? {
+ // An older file copy would otherwise outlive the new value.
+ self.file.delete(account)?;
+ return Ok(Where::Keyring);
+ }
+ }
+ self.file.set(account, value)?;
+ Ok(Where::File)
+ })
+ .await
+ }
+
+ pub async fn delete(&self, account: &str) -> Result<(), String> {
+ Self::bounded(async {
+ if let Some(ss) = self.connect().await {
+ let found = ss.search_items(self.attrs(account)).await.map_err(err)?;
+ for item in found.unlocked.iter().chain(found.locked.iter()) {
+ if item.is_locked().await.map_err(err)? {
+ item.unlock().await.map_err(err)?;
+ }
+ item.delete().await.map_err(err)?;
+ }
+ }
+ self.file.delete(account)
+ })
+ .await
+ }
+
+ /// Where a write would land right now, for the Settings hint.
+ pub async fn target(&self) -> Where {
+ let Some(ss) = self.connect().await else { return Where::File };
+ match tokio::time::timeout(CONNECT_TIMEOUT, ss.get_default_collection()).await {
+ Ok(Ok(_)) => Where::Keyring,
+ _ => Where::File,
+ }
+ }
+
+ async fn keyring_get(&self, ss: &SecretService<'_>, account: &str) -> Result<Option<String>, String> {
+ let found = ss.search_items(self.attrs(account)).await.map_err(err)?;
+ let item = match (found.unlocked.first(), found.locked.first()) {
+ (Some(i), _) => i,
+ (None, Some(i)) => {
+ i.unlock().await.map_err(err)?;
+ i
+ }
+ (None, None) => return Ok(None),
+ };
+ let bytes = item.get_secret().await.map_err(err)?;
+ String::from_utf8(bytes)
+ .map(Some)
+ .map_err(|_| "keyring error: the stored value is not text".into())
+ }
+
+ /// Ok(false): the Secret Service runs but has no default collection to
+ /// write into (KeePassXC with no group exposed, a keyring never set up).
+ /// Creating one would pop up a "new keyring password" dialog nobody asked
+ /// for, so the caller uses the file instead.
+ async fn keyring_set(&self, ss: &SecretService<'_>, account: &str, value: &str) -> Result<bool, String> {
+ let coll = match ss.get_default_collection().await {
+ Ok(c) => c,
+ Err(SsError::NoResult) => return Ok(false),
+ Err(e) => return Err(err(e)),
+ };
+ if coll.is_locked().await.map_err(err)? {
+ coll.unlock().await.map_err(err)?;
+ }
+ let label = format!("{}: {account}", crate::app_identity::PRODUCT_NAME);
+ let created = coll
+ .create_item(&label, self.attrs(account), value.as_bytes(), true, "text/plain")
+ .await
+ .map_err(err)?;
+ // `replace` only replaces inside the default collection. A copy in
+ // another collection would shadow the new value on the next read.
+ let created_path = created.item_path.clone();
+ let found = ss.search_items(self.attrs(account)).await.map_err(err)?;
+ for item in found.unlocked.iter().chain(found.locked.iter()) {
+ if item.item_path != created_path {
+ if let Err(e) = item.delete().await {
+ tracing::warn!(error = %e, "could not remove an older keyring copy");
+ }
+ }
+ }
+ Ok(true)
+ }
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 0661a099..e2f1fcb2 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1172,6 +1172,9 @@ pub fn run() {
commands::secret::secret_park_set,
commands::secret::secret_park_get,
commands::secret::secret_park_delete,
+ // Where those land: OS store, or the 0600 file on a Linux
+ // without a Secret Service (GitHub #226).
+ commands::secret::secret_store_info,
// Web search
commands::search::web_search,
commands::search::web_fetch,
diff --git a/src/api/backend.ts b/src/api/backend.ts
index 5b728695..10f57bb9 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -967,9 +967,10 @@ export async function downloadComfyFile(filename: string, subfolder: string = ''
// ── Provider key keychain (H5) ──────────────────────────────────
// Thin wrappers over the Rust secret_* commands (Windows Credential Manager /
-// macOS Keychain). They reject on the web build (no Tauri) and on Linux desktop
-// (the command reports unsupported), which is how providerStore detects "no
-// keychain here" and falls back to the obfuscated-localStorage path.
+// macOS Keychain / on Linux the Secret Service, else a 0600 file, GitHub
+// #226). They reject on the web build (no Tauri), which is how providerStore
+// detects "no keychain here" and falls back to the obfuscated-localStorage
+// path.
export async function secretSet(account: string, value: string): Promise<void> {
if (!isTauri()) throw new Error('keychain unavailable (web build)')
const invoke = await getInvoke()
@@ -988,6 +989,22 @@ export async function secretDelete(account: string): Promise<void> {
await invoke('secret_delete', { account })
}
+/**
+ * Where `secretSet` puts a value on this machine: the platform's credential
+ * store (`os`), a file only this user can read (`file`, Linux without a
+ * Secret Service, `path` names it), or nowhere Rust-side (`none`).
+ */
+export interface SecretStoreInfo {
+ kind: 'os' | 'file' | 'none'
+ path?: string | null
+}
+
+export async function secretStoreInfo(): Promise<SecretStoreInfo> {
+ if (!isTauri()) return { kind: 'none' }
+ const invoke = await getInvoke()
+ return (await invoke('secret_store_info')) as SecretStoreInfo
+}
+
// ── Parked provider key keychain (R9) ────────────────────────────
// Same vault as secretSet/Get/Delete above, but a second, narrower namespace
// (Rust: PARKED_PREFIX "parked-key:") for a backend that is NOT one of the
diff --git a/src/components/settings/HfTokenSetting.tsx b/src/components/settings/HfTokenSetting.tsx
index 0f4e5280..1330e4bc 100644
--- a/src/components/settings/HfTokenSetting.tsx
+++ b/src/components/settings/HfTokenSetting.tsx
@@ -13,11 +13,17 @@
* paste into support threads. The keychain is the store of record; Rust holds
* the token in memory only, so saving pushes it down at once and
* lib/rust-boot-sync pushes it again on every start.
+ *
+ * GitHub #226: on Linux the save used to fail with "keychain unsupported on
+ * this platform". Rust now stores through the Secret Service and, where none
+ * answers, in a 0600 file; when the file is what took the token, the field
+ * says so and names it, so nobody believes it sits in a keyring.
*/
import { useEffect, useState } from 'react'
import { KeyRound, Check } from 'lucide-react'
-import { secretGet, secretSet, openExternal } from '../../api/backend'
+import { secretGet, secretSet, secretStoreInfo, openExternal, type SecretStoreInfo } from '../../api/backend'
import { applyHfToken, HF_TOKEN_ACCOUNT } from '../../api/mlx-image'
+import { Hinweis } from '../ui/Hinweis'
/** Where Hugging Face issues tokens. A read token is enough. */
export const HF_TOKEN_PAGE = 'https://huggingface.co/settings/tokens'
@@ -27,6 +33,7 @@ export function HfTokenSetting() {
const [stored, setStored] = useState(false)
const [saved, setSaved] = useState(false)
const [error, setError] = useState<string | null>(null)
+ const [store, setStore] = useState<SecretStoreInfo | null>(null)
useEffect(() => {
void (async () => {
@@ -34,6 +41,7 @@ export function HfTokenSetting() {
if (!value) return
setDraft(value)
setStored(true)
+ setStore(await secretStoreInfo().catch(() => null))
})()
}, [])
@@ -45,6 +53,7 @@ export function HfTokenSetting() {
setDraft(value)
setStored(value.length > 0)
setSaved(value.length > 0)
+ setStore(value ? await secretStoreInfo().catch(() => null) : null)
} catch (e) {
setError(e instanceof Error ? e.message : String(e))
}
@@ -61,7 +70,8 @@ export function HfTokenSetting() {
Sent to huggingface.co with every model download, and nowhere else. Without it downloads go out
anonymous, which the hub throttles, and a gated repository (one whose licence you have to accept
on its page) refuses the download with HTTP 401. A free read token is enough. It goes into your
- system credential store where the OS has one and stays on this machine.
+ system credential store (on Linux the Secret Service: GNOME Keyring, KWallet, KeePassXC) and
+ stays on this machine.
</div>
<div className="flex items-center gap-2">
<input
@@ -90,6 +100,14 @@ export function HfTokenSetting() {
</button>
)}
</div>
+ {stored && store?.kind === 'file' && (
+ <Hinweis className="leading-relaxed">
+ No system keyring answered, so the token is saved in a file only your user account can read
+ {store.path ? <>: <span className="font-mono break-all">{store.path}</span></> : null}. Start a
+ keyring (GNOME Keyring, KWallet or KeePassXC with Secret Service on) and LU moves it there on
+ the next start.
+ </Hinweis>
+ )}
{error && (
<div role="alert" className="t-micro text-red-400">{error}</div>
)}
diff --git a/src/components/settings/__tests__/hf-token-field-renders.test.ts b/src/components/settings/__tests__/hf-token-field-renders.test.ts
index 2ecb49e4..b5f1aaec 100644
--- a/src/components/settings/__tests__/hf-token-field-renders.test.ts
+++ b/src/components/settings/__tests__/hf-token-field-renders.test.ts
@@ -15,6 +15,7 @@ import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/re
const secretSet = vi.fn().mockResolvedValue(undefined)
const secretGet = vi.fn().mockResolvedValue(null)
const applyHfToken = vi.fn().mockResolvedValue({ present: true })
+const secretStoreInfo = vi.fn().mockResolvedValue({ kind: 'os' })
vi.mock('../../../api/backend', () => ({
openExternal: vi.fn(),
backendCall: vi.fn(),
@@ -23,6 +24,7 @@ vi.mock('../../../api/backend', () => ({
secretGet: (...a: unknown[]) => secretGet(...a),
secretSet: (...a: unknown[]) => secretSet(...a),
secretDelete: vi.fn(),
+ secretStoreInfo: (...a: unknown[]) => secretStoreInfo(...a),
}))
vi.mock('../../../api/mlx-image', () => ({
HF_TOKEN_ACCOUNT: 'huggingface-token',
@@ -31,7 +33,12 @@ vi.mock('../../../api/mlx-image', () => ({
import { HfTokenSetting } from '../HfTokenSetting'
-beforeEach(() => { secretSet.mockClear(); secretGet.mockReset().mockResolvedValue(null); applyHfToken.mockClear() })
+beforeEach(() => {
+ secretSet.mockReset().mockResolvedValue(undefined)
+ secretGet.mockReset().mockResolvedValue(null)
+ secretStoreInfo.mockReset().mockResolvedValue({ kind: 'os' })
+ applyHfToken.mockClear()
+})
afterEach(cleanup)
describe('the Hugging Face token field', () => {
@@ -55,4 +62,50 @@ describe('the Hugging Face token field', () => {
await waitFor(() => expect(secretSet).toHaveBeenCalledWith('huggingface-token', ''))
expect(applyHfToken).toHaveBeenCalledWith('')
})
+
+ it('says nothing about a file when the OS store took the token', async () => {
+ render(createElement(HfTokenSetting))
+ fireEvent.change(screen.getByLabelText('Hugging Face token'), { target: { value: 'hf_abc' } })
+ fireEvent.click(screen.getByText('Save'))
+ expect(await screen.findByText('Saved')).toBeTruthy()
+ expect(screen.queryByText(/No system keyring answered/)).toBeNull()
+ })
+
+ // GitHub #226: Linux without a Secret Service. Rust saves into a 0600 file
+ // and the field has to say so and where, not pretend it is in a keyring.
+ it('names the file when a Linux without a keyring stored the token there', async () => {
+ secretStoreInfo.mockResolvedValue({ kind: 'file', path: '/home/u/.local/share/lu-labs/secrets.json' })
+ render(createElement(HfTokenSetting))
+ fireEvent.change(screen.getByLabelText('Hugging Face token'), { target: { value: 'hf_abc' } })
+ fireEvent.click(screen.getByText('Save'))
+ const note = await screen.findByRole('status')
+ expect(note.textContent).toContain('No system keyring answered')
+ expect(note.textContent).toContain('/home/u/.local/share/lu-labs/secrets.json')
+ expect(screen.queryByRole('alert')).toBeNull()
+ })
+
+ it('shows the file note for a token already stored there', async () => {
+ secretGet.mockResolvedValue('hf_stored')
+ secretStoreInfo.mockResolvedValue({ kind: 'file', path: '/x/secrets.json' })
+ render(createElement(HfTokenSetting))
+ expect((await screen.findByRole('status')).textContent).toContain('/x/secrets.json')
+ })
+
+ it('drops the note again once the token is removed', async () => {
+ secretGet.mockResolvedValue('hf_stored')
+ secretStoreInfo.mockResolvedValue({ kind: 'file', path: '/x/secrets.json' })
+ render(createElement(HfTokenSetting))
+ await screen.findByRole('status')
+ fireEvent.click(screen.getByText('Remove'))
+ await waitFor(() => expect(screen.queryByText(/No system keyring answered/)).toBeNull())
+ })
+
+ it('still shows a real save error', async () => {
+ secretSet.mockRejectedValue(new Error('keyring locked: the unlock prompt was dismissed'))
+ render(createElement(HfTokenSetting))
+ fireEvent.change(screen.getByLabelText('Hugging Face token'), { target: { value: 'hf_abc' } })
+ fireEvent.click(screen.getByText('Save'))
+ expect((await screen.findByRole('alert')).textContent).toContain('unlock prompt was dismissed')
+ expect(applyHfToken).not.toHaveBeenCalled()
+ })
})