From 2f7b38bc32e967c7e4780eba6f5ce4fc8f6d89a9 Mon Sep 17 00:00:00 2001 From: John Siracusa Date: Fri, 6 Nov 2026 00:12:11 -0500 Subject: [PATCH 01/12] fix(desktop): onboarding keeps an existing harness.yaml unless replaced with a backup (AC-51) Co-Authored-By: Claude Opus 5.5 --- .../src/pages/onboarding/OnboardingPage.tsx | 97 ++++++++++++++++--- .../__tests__/OnboardingPage.test.tsx | 88 +++++++++++++++++ 2 files changed, 170 insertions(+), 15 deletions(-) diff --git a/apps/desktop/src/pages/onboarding/OnboardingPage.tsx b/apps/desktop/src/pages/onboarding/OnboardingPage.tsx index b96dc93f..ddf65ec7 100644 --- a/apps/desktop/src/pages/onboarding/OnboardingPage.tsx +++ b/apps/desktop/src/pages/onboarding/OnboardingPage.tsx @@ -3,7 +3,9 @@ import { homeDir } from "@tauri-apps/api/path"; import { importMachine } from "@harness-kit/core"; import type { ImportProjectResult } from "@harness-kit/core"; import { TauriFsProvider } from "../../lib/harness-fs"; -import { writeHarnessFile, grantProjectScope } from "../../lib/tauri"; +import { Modal, Button, DiffViewer } from "@harness-kit/ui"; +import { writeHarnessFile, readHarnessFile, writeConfigFile, grantProjectScope } from "../../lib/tauri"; +import { lineDiff, collapseToHunks } from "../drift/line-diff"; import { getCurrentProjectDir } from "../../lib/project-dir"; import { errorDetails } from "../../lib/error-details"; import { OnboardingFlow, type OnboardingStep } from "./OnboardingFlow"; @@ -23,6 +25,9 @@ export interface OnboardingPageProps { * view (the same pattern used by Machine) so the flow can be * screenshot-tested with fixture data with no live backend. */ +/** Where `write_harness_file` puts the file; the only path onboarding can overwrite. */ +const WRITE_TARGET = "~/.claude/harness.yaml"; + export default function OnboardingPage({ onFinish }: OnboardingPageProps) { const [step, setStep] = useState("scan"); const [scanSeconds, setScanSeconds] = useState(null); @@ -31,6 +36,8 @@ export default function OnboardingPage({ onFinish }: OnboardingPageProps) { const [reveal, setReveal] = useState(null); const [writing, setWriting] = useState(false); const [writeError, setWriteError] = useState(null); + // Set when the target file already exists with different content (AC-51). + const [conflict, setConflict] = useState<{ existing: string } | null>(null); const startedAt = useRef(Date.now()); // Bumped by Retry; the scan effect is keyed on it so a rerun goes back // through the scan step (AC-32). handleRetry resets the scan state. @@ -104,6 +111,17 @@ export default function OnboardingPage({ onFinish }: OnboardingPageProps) { setWriting(true); setWriteError(null); try { + // AC-51: never replace an existing harness.yaml unseen. A read failure + // aborts the write rather than risk clobbering a file we couldn't read. + const current = await readHarnessFile(); + if (current.found && current.path === WRITE_TARGET) { + if (current.content === result.harnessYaml) { + onFinish(); + return; + } + setConflict({ existing: current.content ?? "" }); + return; + } await writeHarnessFile(result.harnessYaml); onFinish(); } catch (err) { @@ -113,6 +131,30 @@ export default function OnboardingPage({ onFinish }: OnboardingPageProps) { } }, [result, onFinish]); + const handleKeepExisting = useCallback(() => { + setConflict(null); + onFinish(); + }, [onFinish]); + + const handleReplace = useCallback(async () => { + if (!result || !conflict) return; + setWriting(true); + setWriteError(null); + try { + const stamp = new Date().toISOString().replace(/[:.]/g, "-"); + // Backup first; if it fails the original stays untouched. + await writeConfigFile(`${WRITE_TARGET}.bak-${stamp}`, conflict.existing); + await writeHarnessFile(result.harnessYaml); + setConflict(null); + onFinish(); + } catch (err) { + setConflict(null); + setWriteError(errorDetails(err)); + } finally { + setWriting(false); + } + }, [result, conflict, onFinish]); + const handleRetry = useCallback(() => { setScanError(null); setScanSeconds(null); @@ -131,20 +173,45 @@ export default function OnboardingPage({ onFinish }: OnboardingPageProps) { }, [onFinish]); return ( - + <> + + + + + + } + > +

+ {WRITE_TARGET} differs from what onboarding would write. Replacing saves the current file as{" "} + {WRITE_TARGET}.bak-<timestamp> first. +

+ {conflict && result && ( + + )} +
+ ); } diff --git a/apps/desktop/src/pages/onboarding/__tests__/OnboardingPage.test.tsx b/apps/desktop/src/pages/onboarding/__tests__/OnboardingPage.test.tsx index 9f11e134..3a926bb4 100644 --- a/apps/desktop/src/pages/onboarding/__tests__/OnboardingPage.test.tsx +++ b/apps/desktop/src/pages/onboarding/__tests__/OnboardingPage.test.tsx @@ -24,8 +24,12 @@ vi.mock("../../../lib/harness-fs", () => ({ const mockWriteHarnessFile = vi.fn(); const mockGrantProjectScope = vi.fn(); +const mockReadHarnessFile = vi.fn(); +const mockWriteConfigFile = vi.fn(); vi.mock("../../../lib/tauri", () => ({ writeHarnessFile: (...args: unknown[]) => mockWriteHarnessFile(...args), + readHarnessFile: (...args: unknown[]) => mockReadHarnessFile(...args), + writeConfigFile: (...args: unknown[]) => mockWriteConfigFile(...args), grantProjectScope: (...args: unknown[]) => mockGrantProjectScope(...args), })); @@ -48,6 +52,8 @@ describe("OnboardingPage", () => { beforeEach(() => { vi.clearAllMocks(); mockWriteHarnessFile.mockResolvedValue("~/.claude/harness.yaml"); + mockReadHarnessFile.mockResolvedValue({ found: false, content: null, path: null }); + mockWriteConfigFile.mockResolvedValue(undefined); }); it("runs the scan step then advances to the sprawl reveal with real counts", async () => { @@ -174,4 +180,86 @@ describe("OnboardingPage", () => { timeout: 3000, }); }); + + describe("existing harness.yaml (AC-51)", () => { + const TARGET = "~/.claude/harness.yaml"; + + async function toConfirm() { + mockImportMachine.mockResolvedValue(ONBOARDING_FIXTURE_RESULT); + const user = userEvent.setup(); + const utils = renderPage(); + await waitFor(() => expect(screen.getByText(/preview harness\.yaml/i)).toBeInTheDocument(), { + timeout: 3000, + }); + await user.click(screen.getByRole("button", { name: /preview harness\.yaml/i })); + await user.click(await screen.findByRole("button", { name: /^continue$/i })); + return { user, ...utils }; + } + + it("writes directly when no file exists", async () => { + const { user, onFinish } = await toConfirm(); + await user.click(await screen.findByRole("button", { name: /^write harness\.yaml$/i })); + await waitFor(() => expect(mockWriteHarnessFile).toHaveBeenCalledWith(ONBOARDING_FIXTURE_RESULT.harnessYaml)); + expect(mockWriteConfigFile).not.toHaveBeenCalled(); + await waitFor(() => expect(onFinish).toHaveBeenCalled()); + }); + + it("skips the write when the existing file is identical", async () => { + mockReadHarnessFile.mockResolvedValue({ + found: true, + content: ONBOARDING_FIXTURE_RESULT.harnessYaml, + path: TARGET, + }); + const { user, onFinish } = await toConfirm(); + await user.click(await screen.findByRole("button", { name: /^write harness\.yaml$/i })); + await waitFor(() => expect(onFinish).toHaveBeenCalled()); + expect(mockWriteHarnessFile).not.toHaveBeenCalled(); + expect(mockWriteConfigFile).not.toHaveBeenCalled(); + }); + + it("differs + Keep existing: no write, no backup", async () => { + mockReadHarnessFile.mockResolvedValue({ found: true, content: "version: old\n", path: TARGET }); + const { user, onFinish } = await toConfirm(); + await user.click(await screen.findByRole("button", { name: /^write harness\.yaml$/i })); + expect(await screen.findByRole("button", { name: /^keep existing$/i })).toBeInTheDocument(); + expect(mockWriteHarnessFile).not.toHaveBeenCalled(); + await user.click(screen.getByRole("button", { name: /^keep existing$/i })); + await waitFor(() => expect(onFinish).toHaveBeenCalled()); + expect(mockWriteHarnessFile).not.toHaveBeenCalled(); + expect(mockWriteConfigFile).not.toHaveBeenCalled(); + }); + + it("differs + Replace: writes the backup first, then the new file", async () => { + mockReadHarnessFile.mockResolvedValue({ found: true, content: "version: old\n", path: TARGET }); + const order: string[] = []; + mockWriteConfigFile.mockImplementation(async () => { + order.push("backup"); + }); + mockWriteHarnessFile.mockImplementation(async () => { + order.push("write"); + return TARGET; + }); + const { user, onFinish } = await toConfirm(); + await user.click(await screen.findByRole("button", { name: /^write harness\.yaml$/i })); + await user.click(await screen.findByRole("button", { name: /replace \(backup kept\)/i })); + await waitFor(() => expect(onFinish).toHaveBeenCalled()); + expect(order).toEqual(["backup", "write"]); + expect(mockWriteConfigFile).toHaveBeenCalledWith( + expect.stringMatching(/^~\/\.claude\/harness\.yaml\.bak-.+/), + "version: old\n", + ); + expect(mockWriteHarnessFile).toHaveBeenCalledWith(ONBOARDING_FIXTURE_RESULT.harnessYaml); + }); + + it("does not write the new file when the backup fails", async () => { + mockReadHarnessFile.mockResolvedValue({ found: true, content: "version: old\n", path: TARGET }); + mockWriteConfigFile.mockRejectedValue(new Error("disk full")); + const { user, onFinish } = await toConfirm(); + await user.click(await screen.findByRole("button", { name: /^write harness\.yaml$/i })); + await user.click(await screen.findByRole("button", { name: /replace \(backup kept\)/i })); + await waitFor(() => expect(mockWriteConfigFile).toHaveBeenCalled()); + expect(mockWriteHarnessFile).not.toHaveBeenCalled(); + expect(onFinish).not.toHaveBeenCalled(); + }); + }); }); From c95c199b47eb8fe0a685589858987ec00fa38e90 Mon Sep 17 00:00:00 2001 From: John Siracusa Date: Fri, 6 Nov 2026 00:13:31 -0500 Subject: [PATCH 02/12] fix(desktop): uninstall deletes only the plugin's own cache installPath, by full key (AC-48) Co-Authored-By: Claude Opus 5.5 --- .../desktop/src-tauri/src/commands/plugins.rs | 263 +++++++++++++++--- 1 file changed, 223 insertions(+), 40 deletions(-) diff --git a/apps/desktop/src-tauri/src/commands/plugins.rs b/apps/desktop/src-tauri/src/commands/plugins.rs index 4c3b21d9..83f4b183 100644 --- a/apps/desktop/src-tauri/src/commands/plugins.rs +++ b/apps/desktop/src-tauri/src/commands/plugins.rs @@ -259,59 +259,125 @@ pub fn uninstall_plugin(name: String) -> Result<(), String> { uninstall_plugin_in(&claude_dir()?, name) } +const RESERVED_PLUGIN_NAMES: [&str; 3] = ["cache", "data", "marketplaces"]; + +/// Reject names that are empty, `.`/`..`, reserved directory names, or contain +/// path separators. Applied to the whole argument and to its name part. +fn validate_plugin_name(part: &str) -> Result<(), String> { + let trimmed = part.trim(); + if trimmed.is_empty() || trimmed == "." || trimmed == ".." { + return Err(format!("Invalid plugin name: {:?}", part)); + } + if trimmed.contains('/') || trimmed.contains('\\') || trimmed.contains("..") { + return Err(format!("Invalid plugin name: {:?}", part)); + } + if RESERVED_PLUGIN_NAMES.contains(&trimmed) { + return Err(format!("Refusing to uninstall reserved name {:?}", part)); + } + Ok(()) +} + +/// Resolve the `installed_plugins.json` key for `name`. An exact key match +/// wins. A bare name (no `@`) matches only when exactly one key has that name. +fn resolve_plugin_key( + plugins: &serde_json::Map, + name: &str, +) -> Result, String> { + if plugins.contains_key(name) { + return Ok(Some(name.to_string())); + } + if name.contains('@') { + return Ok(None); + } + let matches: Vec<&String> = plugins + .keys() + .filter(|k| k.find('@').map_or(k.as_str(), |i| &k[..i]) == name) + .collect(); + match matches.len() { + 0 => Ok(None), + 1 => Ok(Some(matches[0].clone())), + _ => Err(format!( + "Plugin name {:?} is installed from several marketplaces; use the full name@marketplace key", + name + )), + } +} + fn uninstall_plugin_in(claude_dir: &std::path::Path, name: String) -> Result<(), String> { - // Validate name doesn't contain path traversal characters - if name.contains('/') || name.contains('\\') || name.contains("..") { - return Err("Invalid plugin name".to_string()); + validate_plugin_name(&name)?; + if let Some(base) = name.find('@').map(|i| &name[..i]) { + validate_plugin_name(base)?; } let plugins_dir = claude_dir.join("plugins"); + let json_path = plugins_dir.join("installed_plugins.json"); + if !json_path.exists() { + return Ok(()); + } - // Remove plugin directory — canonicalize before removal to block symlink traversal - let plugin_dir = plugins_dir.join(&name); - if plugin_dir.exists() { - let canonical = plugin_dir.canonicalize() + let contents = std::fs::read_to_string(&json_path) + .map_err(|e| format!("Failed to read installed_plugins.json: {}", e))?; + let mut data: serde_json::Value = serde_json::from_str(&contents) + .map_err(|e| format!("Failed to parse installed_plugins.json: {}", e))?; + + let key = match data + .get("plugins") + .and_then(|p| p.as_object()) + .map(|p| resolve_plugin_key(p, &name)) + .transpose()? + .flatten() + { + Some(k) => k, + None => return Ok(()), + }; + + // Delete only this record's own installPath, and only when it resolves + // strictly under plugins/cache. Canonicalize first to block symlinks and `..`. + let install_paths: Vec = data["plugins"][&key] + .as_array() + .map(|records| { + records + .iter() + .filter_map(|r| r.get("installPath").and_then(|p| p.as_str())) + .map(String::from) + .collect() + }) + .unwrap_or_default(); + + let cache_dir = plugins_dir.join("cache"); + let mut to_remove = Vec::new(); + for install_path in &install_paths { + let path = std::path::Path::new(install_path); + if !path.exists() { + continue; + } + let canonical = path.canonicalize() .map_err(|e| format!("Invalid plugin path: {}", e))?; - let canonical_plugins = plugins_dir.canonicalize() - .map_err(|e| format!("Invalid plugins dir: {}", e))?; - if !canonical.starts_with(&canonical_plugins) { - return Err("Access denied: plugin path outside plugins directory".to_string()); + let canonical_cache = cache_dir.canonicalize() + .map_err(|e| format!("Invalid plugin cache dir: {}", e))?; + if canonical == canonical_cache || !canonical.starts_with(&canonical_cache) { + return Err("Access denied: plugin path outside plugins cache directory".to_string()); } + to_remove.push(canonical); + } + // Validate every path before deleting any. + for canonical in to_remove { std::fs::remove_dir_all(&canonical) .map_err(|e| format!("Failed to remove plugin directory: {}", e))?; } - // Remove from installed_plugins.json - let json_path = plugins_dir.join("installed_plugins.json"); - if json_path.exists() { - let contents = std::fs::read_to_string(&json_path) - .map_err(|e| format!("Failed to read installed_plugins.json: {}", e))?; - let mut data: serde_json::Value = serde_json::from_str(&contents) - .map_err(|e| format!("Failed to parse installed_plugins.json: {}", e))?; - - if let Some(plugins) = data.get_mut("plugins").and_then(|p| p.as_object_mut()) { - // Remove any key matching the name (with or without @marketplace suffix) - let keys_to_remove: Vec = plugins - .keys() - .filter(|k| { - let base = k.find('@').map_or(k.as_str(), |i| &k[..i]); - base == name - }) - .cloned() - .collect(); - for key in keys_to_remove { - plugins.remove(&key); - } - } - - let serialized = serde_json::to_string_pretty(&data).unwrap(); - let tmp_path = json_path.with_extension("json.tmp"); - std::fs::write(&tmp_path, &serialized) - .map_err(|e| format!("Failed to write installed_plugins.json: {}", e))?; - std::fs::rename(&tmp_path, &json_path) - .map_err(|e| format!("Failed to finalize installed_plugins.json: {}", e))?; + // Remove only that key from installed_plugins.json + if let Some(plugins) = data.get_mut("plugins").and_then(|p| p.as_object_mut()) { + plugins.remove(&key); } + let serialized = serde_json::to_string_pretty(&data).unwrap(); + let tmp_path = json_path.with_extension("json.tmp"); + std::fs::write(&tmp_path, &serialized) + .map_err(|e| format!("Failed to write installed_plugins.json: {}", e))?; + std::fs::rename(&tmp_path, &json_path) + .map_err(|e| format!("Failed to finalize installed_plugins.json: {}", e))?; + Ok(()) } @@ -357,4 +423,121 @@ mod tests { assert_eq!(result[2].name, "research"); assert_eq!(result[2].version, "0.3.0"); } + + // --- uninstall_plugin_in --- + + /// Build `/.claude/plugins` with a cache dir, a sentinel file in the + /// plugins dir and the given installed_plugins.json body. + fn uninstall_fixture(json: &str) -> (TempDir, std::path::PathBuf) { + let dir = TempDir::new().unwrap(); + let claude = dir.path().join(".claude"); + let plugins = claude.join("plugins"); + std::fs::create_dir_all(plugins.join("cache")).unwrap(); + std::fs::write(plugins.join("cache").join("keep.txt"), "x").unwrap(); + std::fs::write(plugins.join("installed_plugins.json"), json).unwrap(); + (dir, claude) + } + + fn make_install(claude: &std::path::Path, rel: &str) -> std::path::PathBuf { + let p = claude.join("plugins").join("cache").join(rel); + std::fs::create_dir_all(&p).unwrap(); + std::fs::write(p.join("marker"), "x").unwrap(); + p + } + + fn record(path: &std::path::Path) -> String { + format!( + r#"[{{"version":"1.0.0","installedAt":"2024-01-01T00:00:00Z","installPath":{}}}]"#, + serde_json::to_string(path.to_str().unwrap()).unwrap() + ) + } + + #[test] + fn uninstall_refuses_reserved_and_degenerate_names() { + let (_d, claude) = uninstall_fixture(r#"{"plugins":{}}"#); + for bad in ["cache", "data", "marketplaces", ".", "..", "", "cache@x", "a/b"] { + let err = uninstall_plugin_in(&claude, bad.to_string()).unwrap_err(); + assert!(!err.is_empty(), "{bad:?} should be refused"); + } + assert!(claude.join("plugins").join("cache").join("keep.txt").exists()); + } + + #[test] + fn uninstall_happy_path_deletes_only_own_install_path() { + let (d, claude) = uninstall_fixture(r#"{"plugins":{}}"#); + let a = make_install(&claude, "mkt/alpha/1.0.0"); + let b = make_install(&claude, "mkt/beta/1.0.0"); + let json = format!( + r#"{{"plugins":{{"alpha@mkt":{},"beta@mkt":{}}}}}"#, + record(&a), + record(&b) + ); + std::fs::write(claude.join("plugins").join("installed_plugins.json"), json).unwrap(); + uninstall_plugin_in(&claude, "alpha@mkt".to_string()).unwrap(); + assert!(!a.exists()); + assert!(b.exists()); + assert!(claude.join("plugins").join("cache").join("keep.txt").exists()); + let left = list_installed_plugins_in(&claude).unwrap(); + assert_eq!(left.len(), 1); + assert_eq!(left[0].name, "beta"); + drop(d); + } + + #[test] + fn uninstall_same_name_other_marketplace_is_untouched() { + let (_d, claude) = uninstall_fixture(r#"{"plugins":{}}"#); + let a = make_install(&claude, "one/tool/1.0.0"); + let b = make_install(&claude, "two/tool/1.0.0"); + let json = format!( + r#"{{"plugins":{{"tool@one":{},"tool@two":{}}}}}"#, + record(&a), + record(&b) + ); + std::fs::write(claude.join("plugins").join("installed_plugins.json"), &json).unwrap(); + + // Bare name is ambiguous: refuse, delete nothing. + assert!(uninstall_plugin_in(&claude, "tool".to_string()).is_err()); + assert!(a.exists() && b.exists()); + + uninstall_plugin_in(&claude, "tool@one".to_string()).unwrap(); + assert!(!a.exists()); + assert!(b.exists()); + let left = list_installed_plugins_in(&claude).unwrap(); + assert_eq!(left.len(), 1); + assert_eq!(left[0].marketplace.as_deref(), Some("two")); + } + + #[test] + fn uninstall_refuses_install_path_outside_cache() { + let (d, claude) = uninstall_fixture(r#"{"plugins":{}}"#); + let outside = d.path().join("precious"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("file"), "x").unwrap(); + let json = format!(r#"{{"plugins":{{"evil@mkt":{}}}}}"#, record(&outside)); + std::fs::write(claude.join("plugins").join("installed_plugins.json"), json).unwrap(); + assert!(uninstall_plugin_in(&claude, "evil@mkt".to_string()).is_err()); + assert!(outside.join("file").exists()); + // Record stays so the user can see the failure. + assert_eq!(list_installed_plugins_in(&claude).unwrap().len(), 1); + } + + #[test] + fn uninstall_refuses_install_path_equal_to_cache() { + let (_d, claude) = uninstall_fixture(r#"{"plugins":{}}"#); + let cache = claude.join("plugins").join("cache"); + let json = format!(r#"{{"plugins":{{"evil@mkt":{}}}}}"#, record(&cache)); + std::fs::write(claude.join("plugins").join("installed_plugins.json"), json).unwrap(); + assert!(uninstall_plugin_in(&claude, "evil@mkt".to_string()).is_err()); + assert!(cache.join("keep.txt").exists()); + } + + #[test] + fn uninstall_refuses_dotdot_install_path_escaping_cache() { + let (_d, claude) = uninstall_fixture(r#"{"plugins":{}}"#); + let sneaky = claude.join("plugins").join("cache").join("..").join(".."); + let json = format!(r#"{{"plugins":{{"evil@mkt":{}}}}}"#, record(&sneaky)); + std::fs::write(claude.join("plugins").join("installed_plugins.json"), json).unwrap(); + assert!(uninstall_plugin_in(&claude, "evil@mkt".to_string()).is_err()); + assert!(claude.join("plugins").join("installed_plugins.json").exists()); + } } From 66fc6db6521a38ea06519444f8fce689aaf0b886 Mon Sep 17 00:00:00 2001 From: John Siracusa Date: Fri, 6 Nov 2026 00:13:33 -0500 Subject: [PATCH 03/12] fix(desktop): compile refuses symlinked path components and writes atomically (AC-53) Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src-tauri/src/commands/sync.rs | 208 +++++++++++++++++++- 1 file changed, 204 insertions(+), 4 deletions(-) diff --git a/apps/desktop/src-tauri/src/commands/sync.rs b/apps/desktop/src-tauri/src/commands/sync.rs index 188188fa..efca485a 100644 --- a/apps/desktop/src-tauri/src/commands/sync.rs +++ b/apps/desktop/src-tauri/src/commands/sync.rs @@ -68,15 +68,20 @@ fn resolve_project_root(project_dir: &str) -> Result { Ok(canonical_root) } -/// Validate that `relative` is safely within `project_dir`. -/// Rejects absolute paths and ".." components in `relative`. -fn validate_project_path(project_dir: &str, relative: &str) -> Result { +fn validate_relative(relative: &str) -> Result<(), String> { if Path::new(relative).is_absolute() { return Err("relative path must not be absolute".to_string()); } if relative.contains("..") { return Err("relative path must not contain '..'".to_string()); } + Ok(()) +} + +/// Validate that `relative` is safely within `project_dir`. +/// Rejects absolute paths and ".." components in `relative`. +fn validate_project_path(project_dir: &str, relative: &str) -> Result { + validate_relative(relative)?; let canonical_root = resolve_project_root(project_dir)?; @@ -187,9 +192,77 @@ pub fn sync_read_dir(project_dir: String, dir_path: String) -> Result Result<(), String> { + let mut walked = root.to_path_buf(); + for segment in Path::new(relative).components() { + walked.push(segment); + match fs::symlink_metadata(&walked) { + Ok(meta) if meta.file_type().is_symlink() => { + return Err(format!( + "Refusing to write '{}': '{}' is a symbolic link", + relative, + walked.display() + )); + } + Ok(_) => {} + // Missing component: nothing to follow, and its parent was + // checked on the previous iteration. + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => { + return Err(format!("Failed to inspect {}: {}", walked.display(), e)); + } + } + } + Ok(()) +} + +/// Replace `dest` atomically: stage in a temp file in the same directory, +/// fsync, then rename. A failure removes the temp file and leaves `dest` as it +/// was. `create_new` makes the temp open refuse a pre-planted path. +fn write_file_atomically(dest: &Path, bytes: &[u8]) -> Result<(), String> { + use std::io::Write; + let parent = dest + .parent() + .ok_or_else(|| format!("{} has no parent directory", dest.display()))?; + let name = dest + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let temp = parent.join(format!(".{}.{}.tmp", name, uuid::Uuid::new_v4())); + let staged = (|| -> std::io::Result<()> { + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&temp)?; + file.write_all(bytes)?; + file.sync_all()?; + drop(file); + fs::rename(&temp, dest) + })(); + if let Err(e) = staged { + let _ = fs::remove_file(&temp); + return Err(format!("{}", e)); + } + Ok(()) +} + /// Write compiled output files into a project directory. +/// +/// Every component from the project root to the target is checked with +/// `symlink_metadata` before anything is written; any symlink refuses the +/// whole call. The check runs for all files first so a bad path late in the +/// batch cannot leave earlier files half-applied. #[tauri::command] pub fn sync_write_files(project_dir: String, files: Vec) -> Result<(), String> { + let root = resolve_project_root(&project_dir)?; + for file in &files { + validate_relative(&file.relative_path)?; + refuse_symlink_components(&root, &file.relative_path)?; + } for file in &files { let dest = validate_project_path(&project_dir, &file.relative_path)?; if let Some(parent) = dest.parent() { @@ -197,7 +270,7 @@ pub fn sync_write_files(project_dir: String, files: Vec) -> Resul format!("Failed to create directory for {}: {}", file.relative_path, e) })?; } - fs::write(&dest, &file.content) + write_file_atomically(&dest, file.content.as_bytes()) .map_err(|e| format!("Failed to write {}: {}", file.relative_path, e))?; } Ok(()) @@ -450,6 +523,133 @@ mod tests { fs::remove_dir_all(&dir).ok(); } + // ── Symlink refusal (AC-53) ────────────────────────────────── + + #[cfg(unix)] + mod symlinks { + use super::*; + use std::os::unix::fs::symlink; + + fn granted_project() -> (tempfile::TempDir, String) { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().canonicalize().unwrap(); + super::super::super::fs_scope::remember_granted_root(root.clone()); + let s = root.to_string_lossy().into_owned(); + (tmp, s) + } + + fn write(project: &str, rel: &str) -> Result<(), String> { + sync_write_files( + project.to_string(), + vec![SyncFileWrite { + relative_path: rel.to_string(), + content: "compiled".to_string(), + }], + ) + } + + fn assert_refused(result: Result<(), String>) { + let err = result.unwrap_err(); + assert!(err.contains("symbolic link"), "got: {err}"); + } + + #[test] + fn normal_path_succeeds_and_leaves_no_temp_files() { + let (_tmp, project) = granted_project(); + write(&project, "sub/dir/out.md").unwrap(); + let dir = Path::new(&project).join("sub/dir"); + assert_eq!(fs::read_to_string(dir.join("out.md")).unwrap(), "compiled"); + let names: Vec<_> = fs::read_dir(&dir).unwrap().flatten().collect(); + assert_eq!(names.len(), 1, "temp file left behind"); + } + + #[test] + fn overwrites_an_existing_regular_file() { + let (_tmp, project) = granted_project(); + fs::write(Path::new(&project).join("out.md"), "old").unwrap(); + write(&project, "out.md").unwrap(); + assert_eq!( + fs::read_to_string(Path::new(&project).join("out.md")).unwrap(), + "compiled" + ); + } + + #[test] + fn refuses_a_symlink_at_the_target() { + let (_tmp, project) = granted_project(); + let outside = tempfile::tempdir().unwrap(); + let victim = outside.path().join("victim.txt"); + fs::write(&victim, "original").unwrap(); + symlink(&victim, Path::new(&project).join("out.md")).unwrap(); + assert_refused(write(&project, "out.md")); + assert_eq!(fs::read_to_string(&victim).unwrap(), "original"); + } + + #[test] + fn refuses_a_symlinked_parent_directory() { + let (_tmp, project) = granted_project(); + let outside = tempfile::tempdir().unwrap(); + symlink(outside.path(), Path::new(&project).join("linked")).unwrap(); + assert_refused(write(&project, "linked/out.md")); + assert!(!outside.path().join("out.md").exists()); + } + + #[test] + fn refuses_a_dangling_symlink_at_the_target() { + let (_tmp, project) = granted_project(); + let outside = tempfile::tempdir().unwrap(); + let missing = outside.path().join("not-yet.txt"); + symlink(&missing, Path::new(&project).join("out.md")).unwrap(); + assert_refused(write(&project, "out.md")); + assert!(!missing.exists(), "write followed the dangling link"); + } + + #[test] + fn refuses_a_dangling_symlink_as_a_parent() { + let (_tmp, project) = granted_project(); + let outside = tempfile::tempdir().unwrap(); + let missing_dir = outside.path().join("not-yet-dir"); + symlink(&missing_dir, Path::new(&project).join("linked")).unwrap(); + assert_refused(write(&project, "linked/out.md")); + assert!(!missing_dir.exists(), "create_dir_all followed the link"); + } + + #[test] + fn a_bad_path_late_in_the_batch_writes_nothing() { + let (_tmp, project) = granted_project(); + let outside = tempfile::tempdir().unwrap(); + symlink(outside.path(), Path::new(&project).join("linked")).unwrap(); + let result = sync_write_files( + project.clone(), + vec![ + SyncFileWrite { + relative_path: "first.md".to_string(), + content: "x".to_string(), + }, + SyncFileWrite { + relative_path: "linked/second.md".to_string(), + content: "y".to_string(), + }, + ], + ); + assert_refused(result); + assert!(!Path::new(&project).join("first.md").exists()); + } + + #[test] + fn failed_atomic_write_leaves_destination_and_directory_untouched() { + let tmp = tempfile::tempdir().unwrap(); + // Destination is a non-empty directory: rename over it fails. + let dest = tmp.path().join("out.md"); + fs::create_dir(&dest).unwrap(); + fs::write(dest.join("keep"), "k").unwrap(); + assert!(write_file_atomically(&dest, b"new").is_err()); + assert!(dest.join("keep").exists()); + let names: Vec<_> = fs::read_dir(tmp.path()).unwrap().flatten().collect(); + assert_eq!(names.len(), 1, "temp file left behind after failure"); + } + } + #[test] fn file_exists_reports_false_for_a_missing_root_without_erroring() { let missing = std::env::temp_dir().join("harness-kit-sync-guard-absent"); From ce95a7f5368f90ee344d8e14fef21db5793d14a3 Mon Sep 17 00:00:00 2001 From: John Siracusa Date: Fri, 6 Nov 2026 00:25:14 -0500 Subject: [PATCH 04/12] fix(desktop): presets merge and confirm before dropping deny rules; keychain secrets never on argv (AC-49, AC-54) Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src-tauri/Cargo.lock | 3 + apps/desktop/src-tauri/Cargo.toml | 5 +- .../src-tauri/src/commands/security.rs | 407 ++++++++++++++++-- .../src/pages/security/PermissionsPage.tsx | 30 +- .../__tests__/PermissionsPage.test.tsx | 19 +- 5 files changed, 423 insertions(+), 41 deletions(-) diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 378a4d3f..d89abce8 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -1535,6 +1535,7 @@ dependencies = [ "ed25519-dalek", "reqwest", "rusqlite", + "security-framework", "serde", "serde_json", "sha2 0.11.1", @@ -3321,6 +3322,8 @@ version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ + "foldhash 0.2.0", + "indexmap 2.13.0", "itoa", "memchr", "serde", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index ef996211..a1e25bde 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -23,7 +23,7 @@ tauri-plugin-window-state = "2" tauri-plugin-dialog = "2" tauri-plugin-single-instance = "2" serde = { version = "1", features = ["derive"] } -serde_json = "1" +serde_json = { version = "1", features = ["preserve_order"] } dirs = "7" walkdir = "2" zip = { version = "9.0.5", default-features = false, features = ["deflate"] } @@ -35,5 +35,8 @@ rusqlite = { version = "0.40", features = ["bundled"] } ed25519-dalek = { version = "3", default-features = false } sha2 = "0.11" +[target.'cfg(target_os = "macos")'.dependencies] +security-framework = "3" + [dev-dependencies] tempfile = "3" diff --git a/apps/desktop/src-tauri/src/commands/security.rs b/apps/desktop/src-tauri/src/commands/security.rs index 4bc269ee..1140707b 100644 --- a/apps/desktop/src-tauri/src/commands/security.rs +++ b/apps/desktop/src-tauri/src/commands/security.rs @@ -85,36 +85,78 @@ fn env_config_path() -> Result { } fn read_settings_json() -> Result { - let path = settings_path()?; + read_settings_at(&settings_path()?) +} + +fn read_settings_at(path: &std::path::Path) -> Result { if !path.exists() { return Ok(serde_json::json!({})); } - let content = std::fs::read_to_string(&path) + let content = std::fs::read_to_string(path) .map_err(|e| format!("Failed to read settings.json: {}", e))?; serde_json::from_str(&content) .map_err(|e| format!("Failed to parse settings.json: {}", e)) } fn write_settings_json(value: &serde_json::Value) -> Result<(), String> { - let path = settings_path()?; + write_settings_at(&settings_path()?, value) +} - // Create backup - if path.exists() { - let backup = path.with_extension("json.bak"); - std::fs::copy(&path, &backup) +/// Serialize `value` and replace `path` atomically (temp file in the same +/// directory, 0600 from the first byte, fsync, rename). The previous file is +/// copied to a timestamped `.bak-