diff --git a/rust/Cargo.lock b/rust/Cargo.lock index b17a586f..5eda52c4 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -964,6 +964,7 @@ version = "0.1.0" dependencies = [ "base64", "lithe-diagnostics", + "lithe-platform", "lithe-plugin-model", "lithe-protocol", "serde", @@ -998,6 +999,7 @@ dependencies = [ name = "lithe-document-uri" version = "0.1.0" dependencies = [ + "lithe-platform", "lithe-protocol", "serde", "serde_json", @@ -1031,6 +1033,7 @@ version = "0.1.0" dependencies = [ "ignore", "lithe-diagnostics", + "lithe-platform", "lithe-plugin-model", "lithe-protocol", "lithe-toolchain", @@ -1109,6 +1112,7 @@ version = "0.1.0" dependencies = [ "lithe-diagnostics", "lithe-document-uri", + "lithe-platform", "lithe-plugin-editor", "lithe-plugin-keymap-import", "lithe-plugin-model", @@ -1130,6 +1134,7 @@ dependencies = [ "lithe-git", "lithe-lsp-client", "lithe-lsp-transport", + "lithe-platform", "lithe-plugin-editor", "lithe-plugin-function-relay", "lithe-plugin-language-servers", @@ -1151,6 +1156,7 @@ version = "0.1.0" dependencies = [ "lithe-core-rules", "lithe-document-uri", + "lithe-platform", "lithe-protocol", "serde", "serde_json", @@ -1340,6 +1346,7 @@ name = "lithe-plugin-output-links" version = "0.1.0" dependencies = [ "lithe-document-uri", + "lithe-platform", "lithe-plugin-model", "lithe-protocol", "lithe-toolchain", @@ -1501,6 +1508,7 @@ name = "lithe-toolchain" version = "0.1.0" dependencies = [ "ignore", + "lithe-platform", "lithe-plugin-model", "lithe-protocol", "regex", diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 344a0877..0c2afc0c 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -5478,9 +5478,11 @@ by `rust/fixtures/workspace/directory-rules-v1.json`. `workspace.planDuplicate` takes `{ name, isDirectory, existing?, caseInsensitive? }` and returns `{ name }`; `workspace.planPaste` takes `{ items: [{ name, isDirectory }], existing?, caseInsensitive? }` -and returns `{ names }`. A file name is split at its last dot, a directory name and a leading-dot name -are not. Core never touches the file system: the host passes the names it has seen to exist, creates the -copy without replacing anything (`FileManager.copyItem`, which refuses an existing destination, on macOS; +and returns `{ names }`. Every name must be one file name on the host: an empty name, `.`, `..` and a +name containing `/` are rejected everywhere, and on Windows a name containing `\` or `:` is too, while +on Unix those are ordinary characters. A file name is split at its last dot, a directory name and a +leading-dot name are not. Core never touches the file system: the host passes the names it has seen +to exist, creates the copy without replacing anything (`FileManager.copyItem`, which refuses an existing destination, on macOS; `create_new` and `MoveFileEx` without replacement on Windows) and, when that fails because the name appeared meanwhile, adds the name to `existing` and plans again. After 512 rounds the host reports the stable `destination_exists` error. Cases are in `rust/fixtures/workspace/file-copy-names-v1.json`. diff --git a/rust/crates/core/src/tests/git.rs b/rust/crates/core/src/tests/git.rs index 0399558e..0c77d8db 100644 --- a/rust/crates/core/src/tests/git.rs +++ b/rust/crates/core/src/tests/git.rs @@ -1117,6 +1117,49 @@ fn git_write_appends_shared_and_local_ignore_patterns_without_duplicates() { fs::remove_dir_all(root).expect("temporary workspace should be removable"); } +/// A Unix file name may hold a backslash. The pattern must ignore that one file +/// rather than read the backslash as a separator or let Git read it as an escape. +#[cfg(unix)] +#[test] +fn git_write_ignores_a_unix_file_whose_name_holds_a_backslash() { + let root = temporary_root("git-write-ignore-backslash"); + fs::create_dir_all(root.join("logs")).expect("temporary repository should be creatable"); + let run = |arguments: &[&str]| { + Command::new("git") + .args(arguments) + .current_dir(&root) + .output() + .expect("git should be available") + }; + assert!(run(&["init", "-q"]).status.success()); + fs::write(root.join("logs\\app.log"), "ignored\n").expect("log file should be writable"); + fs::write(root.join("logs/app.log"), "kept\n").expect("nested file should be writable"); + + let response: Value = serde_json::from_str(&execute_json( + &serde_json::to_string(&serde_json::json!({ + "id": "ignore", + "command": "git.write", + "payload": {"root": root, "operation": "ignore", "paths": ["logs\\app.log"]} + })) + .expect("ignore request should encode"), + )) + .expect("ignore response should be JSON"); + assert_eq!(response["ok"], true, "{response:?}"); + + assert_eq!( + fs::read_to_string(root.join(".gitignore")).expect("gitignore should be readable"), + "/logs\\\\app.log\n" + ); + assert!(run(&["check-ignore", "-q", "logs\\app.log"]) + .status + .success()); + assert!(!run(&["check-ignore", "-q", "logs/app.log"]) + .status + .success()); + + fs::remove_dir_all(root).expect("temporary workspace should be removable"); +} + #[test] fn git_write_edits_a_local_commit_message_and_rebuilds_descendants() { let root = history_rewrite_repository("git-edit-commit-message"); diff --git a/rust/crates/core/src/tests/project.rs b/rust/crates/core/src/tests/project.rs index c3785dd7..7df8392f 100644 --- a/rust/crates/core/src/tests/project.rs +++ b/rust/crates/core/src/tests/project.rs @@ -1763,6 +1763,9 @@ fn file_commands_round_trip_and_reject_traversal() { assert_eq!(traversal_response["ok"], false); assert_eq!(traversal_response["error"]["code"], "invalid_request"); + // Windows reads these as leaving the root and rejects them. On Unix each is + // one file name inside the root, and none of them exists. Neither reads + // outside the workspace. for path in [ "..\\outside.txt", "nested\\..\\outside.txt", @@ -1777,12 +1780,27 @@ fn file_commands_round_trip_and_reject_traversal() { &serde_json::to_string(&request).expect("Windows path request should encode"), )) .expect("Windows path response should be JSON"); - assert_eq!(response["ok"], false, "path {path} should be rejected"); - assert_eq!(response["error"]["code"], "invalid_request"); + assert_eq!(response["ok"], false, "path {path} should not be read"); } #[cfg(unix)] { + fs::write(root.join("..\\outside.txt"), "inside") + .expect("a Unix name with a backslash should be writable"); + let named = serde_json::json!({ + "id": "backslash-name", + "command": "file.read", + "payload": {"root": root, "path": "..\\outside.txt"} + }); + let named_response: Value = serde_json::from_str(&execute_json( + &serde_json::to_string(&named).expect("backslash name request should encode"), + )) + .expect("backslash name response should be JSON"); + assert_eq!( + named_response["data"]["text"], "inside", + "{named_response:?}" + ); + std::os::unix::fs::symlink(&outside, root.join("link")) .expect("test symlink should be creatable"); let symlink_write = serde_json::json!({ diff --git a/rust/crates/core/src/tests/project_tree.rs b/rust/crates/core/src/tests/project_tree.rs index 66c832eb..d682e2d8 100644 --- a/rust/crates/core/src/tests/project_tree.rs +++ b/rust/crates/core/src/tests/project_tree.rs @@ -2,13 +2,17 @@ use serde_json::{json, Value}; -fn run(request: &Value) -> Value { +fn execute(command: &str, payload: Value) -> Value { serde_json::from_str(&crate::execute_json( - &json!({"command": "workspace.projectTree.rows", "payload": request}).to_string(), + &json!({"command": command, "payload": payload}).to_string(), )) .unwrap() } +fn run(request: &Value) -> Value { + execute("workspace.projectTree.rows", request.clone()) +} + #[test] fn shared_project_tree_rows_fixture_runs_every_case() { let fixture: Value = serde_json::from_str(include_str!(concat!( @@ -31,3 +35,45 @@ fn shared_project_tree_rows_fixture_runs_every_case() { ); } } + +/// Issue 2009: Spring Boot on macOS writes a Windows-style `logging.file.path` +/// such as `D:\logs` as one folder name. On Unix `\` and `:` are ordinary +/// file-name characters, so the listing keeps each entry one level below its +/// folder and the project tree accepts the rows built from it. +#[cfg(unix)] +#[test] +fn names_with_backslashes_stay_one_level_below_their_folder_on_unix() { + let root = super::support::temporary_root("backslash-file-names"); + std::fs::create_dir_all(root.join(r"D:\logs")).unwrap(); + std::fs::write(root.join(r"D:\logs").join("spring.log"), "").unwrap(); + std::fs::write(root.join(r"D:\logs\app.log"), "").unwrap(); + + let listing = execute( + "workspace.listDirectories", + json!({"root": root, "paths": ["", r"D:\logs"]}), + ); + let removed = std::fs::remove_dir_all(&root); + assert_eq!(listing["ok"], true, "{listing}"); + removed.expect("temporary fixture should be removable"); + + let children = |index: usize| { + listing["data"]["directories"][index]["children"] + .as_array() + .unwrap() + .iter() + .map(|child| child["path"].as_str().unwrap().to_string()) + .collect::>() + }; + assert_eq!(children(0), [r"D:\logs", r"D:\logs\app.log"]); + assert_eq!(listing["data"]["directories"][1]["path"], r"D:\logs"); + assert_eq!(children(1), [r"D:\logs/spring.log"]); + + let rows = run(&json!({"nodes": [ + {"path": "", "depth": 0, "open": true}, + {"path": r"D:\logs", "depth": 1, "open": true}, + {"path": r"D:\logs/spring.log", "depth": 2}, + {"path": r"D:\logs\app.log", "depth": 1}, + ]})); + assert_eq!(rows["ok"], true, "{rows}"); + assert_eq!(rows["data"]["rows"], json!([0, 1, 2, 3])); +} diff --git a/rust/crates/debug/Cargo.toml b/rust/crates/debug/Cargo.toml index 96502b9d..23561dfb 100644 --- a/rust/crates/debug/Cargo.toml +++ b/rust/crates/debug/Cargo.toml @@ -8,6 +8,7 @@ description = "Debug Adapter Protocol sessions for Lithe: adapter declarations, [dependencies] base64 = "0.22" lithe-diagnostics = { path = "../diagnostics" } +lithe-platform = { path = "../platform" } lithe-plugin-model = { path = "../plugin-model" } lithe-protocol = { path = "../protocol" } serde = { version = "1.0", features = ["derive"] } diff --git a/rust/crates/debug/src/projection_v2.rs b/rust/crates/debug/src/projection_v2.rs index 3bf2da76..707ee6a5 100644 --- a/rust/crates/debug/src/projection_v2.rs +++ b/rust/crates/debug/src/projection_v2.rs @@ -4,6 +4,8 @@ //! Version 1 stays authoritative until every consumer migrates. The engine emits v2 //! beside it, built here from the raw adapter body so no v1 narrowing leaks into v2. +use lithe_platform::paths::slash_separated; +use lithe_platform::Platform; #[cfg(test)] use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; @@ -456,13 +458,12 @@ fn finish(projection: SessionProjection) -> Option { fn workspace_relative(path: &str, root: &str) -> Option { let is_windows = root.as_bytes().get(1) == Some(&b':') && root.as_bytes()[0].is_ascii_alphabetic(); - let normalize = |text: &str| { - if is_windows { - text.replace('\\', "/") - } else { - text.to_string() - } + let platform = if is_windows { + Platform::Windows + } else { + Platform::Unix }; + let normalize = |text: &str| slash_separated(text, platform).into_owned(); let (path, root) = (normalize(path), normalize(root)); let root = root.trim_end_matches('/'); let rest = if is_windows && path.len() >= root.len() && path.is_char_boundary(root.len()) { diff --git a/rust/crates/document-uri/Cargo.toml b/rust/crates/document-uri/Cargo.toml index 6f7e27e9..e9a687b4 100644 --- a/rust/crates/document-uri/Cargo.toml +++ b/rust/crates/document-uri/Cargo.toml @@ -6,6 +6,7 @@ license = "Apache-2.0" description = "Lexical conversions between native filesystem paths and LSP document URIs that both platform hosts share" [dependencies] +lithe-platform = { path = "../platform" } lithe-protocol = { path = "../protocol" } serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } diff --git a/rust/crates/document-uri/src/encode.rs b/rust/crates/document-uri/src/encode.rs index c419a870..988451ef 100644 --- a/rust/crates/document-uri/src/encode.rs +++ b/rust/crates/document-uri/src/encode.rs @@ -1,5 +1,7 @@ //! Platform-neutral conversion of absolute filesystem paths to LSP file URIs. +use lithe_platform::paths::slash_separated; +use lithe_platform::Platform; use lithe_protocol::{CoreError, ErrorCode}; use serde::Deserialize; use serde_json::{json, Value}; @@ -77,13 +79,13 @@ fn document_uri(path: &str, platform: DocumentPathPlatform) -> Result { - let path = path.replace('\\', "/"); + let path = slash_separated(path, Platform::Windows); if let Some(rest) = path.strip_prefix("//?/UNC/") { format!("//{rest}") } else if let Some(rest) = path.strip_prefix("//?/") { rest.to_owned() } else { - path + path.into_owned() } } DocumentPathPlatform::Auto => unreachable!("auto platform is resolved above"), diff --git a/rust/crates/execution/Cargo.toml b/rust/crates/execution/Cargo.toml index 5b20a75f..518d9540 100644 --- a/rust/crates/execution/Cargo.toml +++ b/rust/crates/execution/Cargo.toml @@ -12,6 +12,7 @@ test-support = [] [dependencies] ignore = "=0.4.33" lithe-diagnostics = { path = "../diagnostics" } +lithe-platform = { path = "../platform" } lithe-plugin-model = { path = "../plugin-model" } lithe-protocol = { path = "../protocol" } lithe-toolchain = { path = "../toolchain" } diff --git a/rust/crates/execution/src/configuration.rs b/rust/crates/execution/src/configuration.rs index 8b4e4c54..bfa83114 100644 --- a/rust/crates/execution/src/configuration.rs +++ b/rust/crates/execution/src/configuration.rs @@ -5,7 +5,11 @@ pub use project_toolchain::{project_toolchain, ProjectToolchainRequest}; use super::generated_layer::{self, GeneratedLayer}; use super::types::{Confidence, Execution, RunCategory}; -use lithe_protocol::{invalid_relative_path, CoreError, ErrorCode}; +use lithe_platform::paths::{ + invalid_native_relative_path, invalid_portable_relative_path, slash_separated_path, +}; +use lithe_platform::Platform; +use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; diff --git a/rust/crates/execution/src/configuration/document.rs b/rust/crates/execution/src/configuration/document.rs index 4ae13a0c..167aee4f 100644 --- a/rust/crates/execution/src/configuration/document.rs +++ b/rust/crates/execution/src/configuration/document.rs @@ -67,10 +67,7 @@ impl BuildProviderRunReference { .user_arguments .iter() .any(|arg| arg.len() > 4096 || arg.contains('\0')) - || invalid_relative_path(&self.root) - || self.root.is_empty() - || self.root.contains('\\') - || self.root.contains('\0') + || invalid_portable_relative_path(&self.root) { return Err(CoreError::new( ErrorCode::InvalidRequest, diff --git a/rust/crates/execution/src/configuration/inputs.rs b/rust/crates/execution/src/configuration/inputs.rs index b4c0fef7..d9e43abe 100644 --- a/rust/crates/execution/src/configuration/inputs.rs +++ b/rust/crates/execution/src/configuration/inputs.rs @@ -58,11 +58,10 @@ pub(crate) fn project_inputs(root: &Path) -> Result { if !fingerprint_input(&path) { continue; } - let relative = path - .strip_prefix(root) - .expect("scan stays within root") - .to_string_lossy() - .replace('\\', "/"); + let relative = slash_separated_path( + path.strip_prefix(root).expect("scan stays within root"), + Platform::HOST, + ); lithe_protocol::cancellation::check()?; // The scan lists files through the workspace adapter, so content reads // must use the same adapter or remote projects look permanently unreadable. diff --git a/rust/crates/execution/src/configuration/launch.rs b/rust/crates/execution/src/configuration/launch.rs index 9f1fe55d..6e4aefa4 100644 --- a/rust/crates/execution/src/configuration/launch.rs +++ b/rust/crates/execution/src/configuration/launch.rs @@ -5,9 +5,7 @@ use super::*; /// Extracts existing Run document values; framework goals and runtime semantics stay in providers. pub fn provider_launch_inputs(request: ProviderLaunchInputsRequest) -> Result { let root = existing_root(&request.root)?; - if invalid_relative_path(&request.provider_root) - || !project_directory_exists(&root, &request.provider_root) - { + if !project_directory_exists(&root, &request.provider_root) { return Err(CoreError::new( ErrorCode::InvalidRequest, "The provider instance leaves the workspace.", diff --git a/rust/crates/execution/src/configuration/layers.rs b/rust/crates/execution/src/configuration/layers.rs index 373ebe40..6aecc168 100644 --- a/rust/crates/execution/src/configuration/layers.rs +++ b/rust/crates/execution/src/configuration/layers.rs @@ -52,7 +52,7 @@ pub(crate) fn normalize_working_directory(root: &Path, value: &str) -> Result Result { let candidate = Path::new(value); - if (!candidate.is_absolute() && invalid_relative_path(value)) + if (!candidate.is_absolute() && invalid_native_relative_path(value, Platform::HOST)) || candidate .components() .any(|component| matches!(component, std::path::Component::ParentDir)) @@ -86,12 +86,12 @@ pub(crate) fn normalize_project_directory(root: &Path, value: &str) -> Result bool { - if invalid_relative_path(value) { + if invalid_native_relative_path(value, Platform::HOST) { return false; } let Ok(canonical_root) = fs::canonicalize(root) else { diff --git a/rust/crates/execution/src/configuration/project_toolchain.rs b/rust/crates/execution/src/configuration/project_toolchain.rs index 74f19038..e221e6d5 100644 --- a/rust/crates/execution/src/configuration/project_toolchain.rs +++ b/rust/crates/execution/src/configuration/project_toolchain.rs @@ -4,7 +4,8 @@ //! It never inspects a build file or runs a tool. use super::{existing_root, local_layer_document, read_local_toolchains, validate_version_value}; -use lithe_protocol::{invalid_relative_path, CoreError, ErrorCode}; +use lithe_platform::paths::invalid_portable_relative_path; +use lithe_protocol::{CoreError, ErrorCode}; use serde::Deserialize; use serde_json::{json, Value}; use std::collections::BTreeMap; @@ -29,8 +30,7 @@ pub struct ProjectToolchainRequest { /// Returns saved paths, never resolved executables. pub fn project_toolchain(request: ProjectToolchainRequest) -> Result { if request.path.len() > 1024 - || invalid_relative_path(&request.path) - || request.path.contains('\\') + || invalid_portable_relative_path(&request.path) || request.path.chars().any(char::is_control) || request.path != "." && request diff --git a/rust/crates/execution/src/configuration/validation.rs b/rust/crates/execution/src/configuration/validation.rs index 6211685e..7f3c75b8 100644 --- a/rust/crates/execution/src/configuration/validation.rs +++ b/rust/crates/execution/src/configuration/validation.rs @@ -89,7 +89,7 @@ pub(crate) fn validate_configuration(configuration: &RunConfiguration) -> Result )); } } - if invalid_relative_path(&configuration.cwd) { + if invalid_native_relative_path(&configuration.cwd, Platform::HOST) { return Err(CoreError::new( ErrorCode::InvalidRequest, "Run configuration contains an invalid project-relative path", @@ -99,11 +99,6 @@ pub(crate) fn validate_configuration(configuration: &RunConfiguration) -> Result Ok(()) } -#[allow(dead_code)] -fn valid_relative(value: &str) -> bool { - !invalid_relative_path(value) -} - /// `namespace.name`, both segments lowercase kebab starting with a letter. /// Shape is checked, membership is not: an unknown ecosystem must be able to /// register a provider without touching this file. diff --git a/rust/crates/execution/src/context_selection.rs b/rust/crates/execution/src/context_selection.rs index 2996df2c..f441c096 100644 --- a/rust/crates/execution/src/context_selection.rs +++ b/rust/crates/execution/src/context_selection.rs @@ -1,5 +1,7 @@ //! Chooses an existing configuration for a provider-supplied entry identity. +use lithe_platform::paths::slash_separated; +use lithe_platform::Platform; use serde::Deserialize; /// One already-resolved configuration; Core performs no provider-specific discovery. @@ -38,7 +40,7 @@ pub struct ContextSelectionRequest { pub fn select_context_configuration(request: ContextSelectionRequest) -> Option { let path_key = |path: &str| { if request.case_insensitive_paths { - path.replace('\\', "/").to_lowercase() + slash_separated(path, Platform::Windows).to_lowercase() } else { path.to_owned() } diff --git a/rust/crates/execution/src/detectors/scan.rs b/rust/crates/execution/src/detectors/scan.rs index e2d26501..15f4eb8e 100644 --- a/rust/crates/execution/src/detectors/scan.rs +++ b/rust/crates/execution/src/detectors/scan.rs @@ -1,6 +1,8 @@ //! Bounded workspace traversal shared by all run-configuration detectors. use crate::workspace_scan::{scan_run_workspace_ignoring, IgnoredPaths}; +use lithe_platform::paths::slash_separated_path; +use lithe_platform::Platform; use lithe_protocol::{CoreError, ErrorCode}; use lithe_workspace::fs; use std::collections::BTreeSet; @@ -109,7 +111,7 @@ fn relative_path(root: &Path, directory: &Path) -> Result { "Scanned directory escaped the project root", ) })?; - let value = relative.to_string_lossy().replace('\\', "/"); + let value = slash_separated_path(relative, Platform::HOST); Ok(if value.is_empty() { ".".to_string() } else { diff --git a/rust/crates/execution/src/provider_runs.rs b/rust/crates/execution/src/provider_runs.rs index 4a04bf59..57c19be2 100644 --- a/rust/crates/execution/src/provider_runs.rs +++ b/rust/crates/execution/src/provider_runs.rs @@ -3,6 +3,7 @@ use super::configuration::{BuildProviderRunReference, RunConfiguration}; use super::types::{Confidence, RunCategory}; +use lithe_platform::paths::invalid_portable_relative_path; use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -34,10 +35,8 @@ pub(super) fn validate(runs: &[ProviderRunConfiguration]) -> Result<(), CoreErro if run.name.trim().is_empty() || run.name.len() > 4096 || run.name.chars().any(char::is_control) - || lithe_protocol::invalid_relative_path(&run.project_path) - || run.project_path.is_empty() + || invalid_portable_relative_path(&run.project_path) || run.project_path.len() > 4096 - || run.project_path.contains(['\\', '\0']) || !contains(&run.reference.root, &run.project_path) || !run.reference.user_arguments.is_empty() || !identities.insert(run.reference.generated_id()) diff --git a/rust/crates/execution/src/workspace_scan.rs b/rust/crates/execution/src/workspace_scan.rs index 2205c04b..3978f1ba 100644 --- a/rust/crates/execution/src/workspace_scan.rs +++ b/rust/crates/execution/src/workspace_scan.rs @@ -20,6 +20,8 @@ use ignore::gitignore::{Gitignore, GitignoreBuilder}; use ignore::Match; +use lithe_platform::paths::slash_separated_path; +use lithe_platform::Platform; use lithe_protocol::CoreError; use lithe_workspace::fs; use std::collections::BTreeSet; @@ -449,10 +451,7 @@ fn visit_with_readers( } fn relative(root: &Path, path: &Path) -> String { - path.strip_prefix(root) - .unwrap_or(path) - .to_string_lossy() - .replace('\\', "/") + slash_separated_path(path.strip_prefix(root).unwrap_or(path), Platform::HOST) } #[cfg(test)] diff --git a/rust/crates/git/src/file_context.rs b/rust/crates/git/src/file_context.rs index a229aeff..ac0191f8 100644 --- a/rust/crates/git/src/file_context.rs +++ b/rust/crates/git/src/file_context.rs @@ -168,10 +168,10 @@ mod tests { Self(root) } fn root(&self, name: &str) -> String { - super::super::canonicalize_simplified(&self.0.join(name)) - .unwrap() - .to_string_lossy() - .replace('\\', "/") + lithe_platform::paths::slash_separated_path( + &super::super::canonicalize_simplified(&self.0.join(name)).unwrap(), + Platform::HOST, + ) } fn resolve(&self, root: &str, path: &str) -> Option { resolve(Request { diff --git a/rust/crates/git/src/ignore.rs b/rust/crates/git/src/ignore.rs index 949ca4e8..a166e68d 100644 --- a/rust/crates/git/src/ignore.rs +++ b/rust/crates/git/src/ignore.rs @@ -1,6 +1,8 @@ //! Appending patterns to `.gitignore` and `.git/info/exclude`. use super::*; +use lithe_platform::paths::slash_separated; +use lithe_platform::Platform; /// Chooses whether ignore patterns belong to the shared repository file or the /// current checkout's local Git metadata. @@ -62,7 +64,7 @@ fn git_ignore_patterns(paths: &[String]) -> Result, CoreError> { "Git ignore operation contains an invalid path", )); } - let normalized = path.replace('\\', "/"); + let normalized = slash_separated(path, Platform::HOST); let is_directory = normalized.ends_with('/'); let normalized = normalized.trim_end_matches('/'); if !is_safe_pathspec(normalized) { @@ -75,7 +77,9 @@ fn git_ignore_patterns(paths: &[String]) -> Result, CoreError> { let mut escaped = String::with_capacity(normalized.len() + 2); escaped.push('/'); for character in normalized.chars() { - if matches!(character, '*' | '?' | '[' | ']' | '#' | '!' | ' ') { + // A backslash left after separator conversion is part of a Unix + // file name, and Git ignore patterns read it as an escape. + if matches!(character, '*' | '?' | '[' | ']' | '#' | '!' | ' ' | '\\') { escaped.push('\\'); } escaped.push(character); diff --git a/rust/crates/git/src/process.rs b/rust/crates/git/src/process.rs index b7f5a2cb..e16842e2 100644 --- a/rust/crates/git/src/process.rs +++ b/rust/crates/git/src/process.rs @@ -2,6 +2,8 @@ //! invocation trace and the generic `git.command` entry points. use super::*; +use lithe_platform::paths::slash_separated_path; +use lithe_platform::Platform; /// Raw Git process streams kept separate for machine-readable consumers. pub(crate) struct GitProcessOutput { @@ -131,7 +133,7 @@ pub fn discover_repository_root( ) -> Result, CoreError> { let root = validate_root(&request.root)?; Ok(discover_containing_repository(Path::new(&root))? - .map(|path| path.to_string_lossy().replace('\\', "/"))) + .map(|path| slash_separated_path(&path, Platform::HOST))) } /// Runs one Git invocation the user sees in the console, under the request's diff --git a/rust/crates/git/src/repository.rs b/rust/crates/git/src/repository.rs index 5abc4472..e845c9c8 100644 --- a/rust/crates/git/src/repository.rs +++ b/rust/crates/git/src/repository.rs @@ -3,6 +3,7 @@ use super::*; use lithe_platform::names::is_reserved_device_name; +use lithe_platform::paths::{slash_separated, slash_separated_path}; use lithe_platform::Platform; /// Discovers Git repositories for an opened workspace using shared traversal rules. @@ -89,7 +90,7 @@ pub fn workspace_repositories( repositories: repositories .into_iter() .map(|path| WorkspaceRepositoryResponse { - path: path.to_string_lossy().replace('\\', "/"), + path: slash_separated_path(&path, Platform::HOST), }) .collect(), }) @@ -118,7 +119,9 @@ pub(crate) fn validate_windows_git_path(path: &Path) -> std::io::Result<()> { /// [`validate_windows_git_path`] for a repository that `platform` opens. A /// drive or UNC path is checked on every platform. fn validate_git_path_on(path: &Path, platform: Platform) -> std::io::Result<()> { - let text = path.to_string_lossy().replace('\\', "/"); + // Read the text the way Windows would: a drive or UNC shape matters even + // when this host is not Windows. + let text = slash_separated(&path.to_string_lossy(), Platform::Windows).into_owned(); let windows_path = platform.is_windows() || text.starts_with("//") || (text.as_bytes().get(1) == Some(&b':') && text.as_bytes()[0].is_ascii_alphabetic()); @@ -176,7 +179,7 @@ fn validate_git_path_on(path: &Path, platform: Platform) -> std::io::Result<()> pub fn simplified_canonical_path(path: PathBuf) -> std::io::Result { validate_windows_git_path(&path)?; let text = path.to_string_lossy(); - let normalized = text.replace('\\', "/"); + let normalized = slash_separated(&text, Platform::Windows); if normalized .get(..8) .is_some_and(|prefix| prefix.eq_ignore_ascii_case("//?/UNC/")) @@ -310,7 +313,7 @@ fn sort_workspace_repository_paths(paths: &mut [PathBuf], workspace_root: &Path) } fn path_sort_key(path: &Path) -> String { - path.to_string_lossy().replace('\\', "/").to_lowercase() + slash_separated_path(path, Platform::HOST).to_lowercase() } pub(crate) fn validate_paths(paths: &[String]) -> Result, CoreError> { @@ -394,7 +397,7 @@ pub(crate) fn empty_tree_oid(root: &str) -> Result { } pub(crate) fn is_safe_pathspec(path: &str) -> bool { - let normalized = path.replace('\\', "/"); + let normalized = slash_separated(path, Platform::HOST); !normalized.is_empty() && !normalized.starts_with('/') && !normalized.split('/').any(|component| component == "..") @@ -408,14 +411,14 @@ pub(crate) fn null_device() -> &'static str { pub(crate) fn relative_or_absolute(path: &Path, root: &Path) -> String { path.strip_prefix(root) .map(|relative| { - let value = relative.to_string_lossy().replace('\\', "/"); + let value = slash_separated_path(relative, Platform::HOST); if value.is_empty() { ".".to_string() } else { value } }) - .unwrap_or_else(|_| path.to_string_lossy().replace('\\', "/")) + .unwrap_or_else(|_| slash_separated_path(path, Platform::HOST)) } #[cfg(test)] diff --git a/rust/crates/lsp-client/Cargo.toml b/rust/crates/lsp-client/Cargo.toml index b66017f2..f30eb6c5 100644 --- a/rust/crates/lsp-client/Cargo.toml +++ b/rust/crates/lsp-client/Cargo.toml @@ -6,8 +6,8 @@ license = "Apache-2.0" description = "The stateful LSP client: capability negotiation, documents, feature requests and the provider protocols a server offers" [dependencies] -lithe-diagnostics = { path = "../diagnostics" } lithe-document-uri = { path = "../document-uri" } +lithe-platform = { path = "../platform" } lithe-plugin-editor = { path = "../plugin-editor" } lithe-plugin-keymap-import = { path = "../plugin-keymap-import" } lithe-plugin-model = { path = "../plugin-model" } @@ -18,3 +18,6 @@ lithe-vcs = { path = "../vcs" } serde = { version = "1.0", features = ["derive", "rc"] } serde_json = { version = "1.0", features = ["preserve_order"] } url = "2.5" + +[dev-dependencies] +lithe-diagnostics = { path = "../diagnostics" } diff --git a/rust/crates/lsp-client/src/client/validation.rs b/rust/crates/lsp-client/src/client/validation.rs index 7e32a815..0a073120 100644 --- a/rust/crates/lsp-client/src/client/validation.rs +++ b/rust/crates/lsp-client/src/client/validation.rs @@ -62,9 +62,12 @@ pub(crate) fn normalize_uri_for_comparison(uri: &str) -> String { pub(crate) fn workspace_name_from_uri(uri: &str) -> String { let decoded = file_path_from_uri(uri); + let separator = |character: char| { + lithe_platform::paths::is_separator(character, lithe_platform::Platform::HOST) + }; decoded - .trim_end_matches(['/', '\\']) - .rsplit(['/', '\\']) + .trim_end_matches(separator) + .rsplit(separator) .find(|component| !component.is_empty()) .unwrap_or("workspace") .to_string() diff --git a/rust/crates/lsp-engine/Cargo.toml b/rust/crates/lsp-engine/Cargo.toml index 96085918..b84d3a66 100644 --- a/rust/crates/lsp-engine/Cargo.toml +++ b/rust/crates/lsp-engine/Cargo.toml @@ -10,6 +10,7 @@ lithe-diagnostics = { path = "../diagnostics" } lithe-document-uri = { path = "../document-uri" } lithe-lsp-client = { path = "../lsp-client" } lithe-lsp-transport = { path = "../lsp-transport" } +lithe-platform = { path = "../platform" } lithe-plugin-function-relay = { path = "../plugin-function-relay" } lithe-plugin-language-servers = { path = "../plugin-language-servers" } lithe-plugin-rpc = { path = "../plugin-rpc" } diff --git a/rust/crates/lsp-engine/src/engine.rs b/rust/crates/lsp-engine/src/engine.rs index e49f0416..e166ecb7 100644 --- a/rust/crates/lsp-engine/src/engine.rs +++ b/rust/crates/lsp-engine/src/engine.rs @@ -376,7 +376,8 @@ fn canonical_workspace_path(root_uri: &str) -> Option { pub(crate) fn canonical_workspace_root(root_uri: &str) -> Option { let canonical = canonical_workspace_path(root_uri)?; - let canonical = canonical.to_string_lossy().replace('\\', "/"); + let canonical = + lithe_platform::paths::slash_separated_path(&canonical, lithe_platform::Platform::HOST); // Windows canonical paths carry a verbatim `\\?\` prefix that language servers never report. Some( canonical diff --git a/rust/crates/lsp-policy/Cargo.toml b/rust/crates/lsp-policy/Cargo.toml index 271408bd..6ca96eab 100644 --- a/rust/crates/lsp-policy/Cargo.toml +++ b/rust/crates/lsp-policy/Cargo.toml @@ -8,6 +8,7 @@ description = "Deterministic language-tooling decisions both platform hosts appl [dependencies] lithe-core-rules = { path = "../core-rules" } lithe-document-uri = { path = "../document-uri" } +lithe-platform = { path = "../platform" } lithe-protocol = { path = "../protocol" } serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } diff --git a/rust/crates/lsp-policy/src/document_identity.rs b/rust/crates/lsp-policy/src/document_identity.rs index 9336a798..8f967046 100644 --- a/rust/crates/lsp-policy/src/document_identity.rs +++ b/rust/crates/lsp-policy/src/document_identity.rs @@ -2,6 +2,8 @@ use crate::workspace_scope::WorkspaceScope; use lithe_document_uri::{native_path, DocumentPathPlatform, MAX_PATH_BYTES}; +use lithe_platform::paths::{is_separator, slash_separated}; +use lithe_platform::Platform; use lithe_protocol::{CoreError, ErrorCode}; use serde::Deserialize; use serde_json::{json, Value}; @@ -69,7 +71,7 @@ pub fn resolve_command(payload: Value) -> Result { return Ok(missing()); }; if windows { - path = path.replace('\\', "/"); + path = slash_separated(&path, Platform::Windows).into_owned(); let bytes = path.as_bytes(); let drive = bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() @@ -81,7 +83,9 @@ pub fn resolve_command(payload: Value) -> Result { } path = format!( "{}/{}", - request.workspace_root.trim_end_matches(['/', '\\']), + request + .workspace_root + .trim_end_matches(|character| is_separator(character, Platform::Windows)), path ); } diff --git a/rust/crates/platform/src/lib.rs b/rust/crates/platform/src/lib.rs index 63a925cc..9d34fc91 100644 --- a/rust/crates/platform/src/lib.rs +++ b/rust/crates/platform/src/lib.rs @@ -26,6 +26,9 @@ pub enum Platform { } impl Platform { + /// Every platform, for rules that must hold on each of them. + pub const ALL: [Self; 2] = [Self::Unix, Self::Windows]; + /// The platform this binary was compiled for. pub const HOST: Self = if cfg!(windows) { Self::Windows diff --git a/rust/crates/platform/src/paths.rs b/rust/crates/platform/src/paths.rs index 632af47d..18628e67 100644 --- a/rust/crates/platform/src/paths.rs +++ b/rust/crates/platform/src/paths.rs @@ -1,9 +1,14 @@ //! Path text that follows platform rules. //! //! Core identifies workspace files by `/`-separated paths. These helpers -//! compare such paths, convert native path text the way the given platform's -//! file systems would, and read the native absolute paths and path lists a -//! tool prints. +//! compare and validate such paths, convert native path text the way the +//! given platform's file systems would, and read the native absolute paths +//! and path lists a tool prints. +//! +//! [`is_separator`] is the one separator rule: every platform splits paths at +//! `/`, and only Windows also splits them at `\`. On Unix `\` and `:` are +//! ordinary file-name characters, so a folder that a Windows-style setting +//! created on macOS, such as `D:\logs`, is one name there. use crate::Platform; use std::borrow::Cow; @@ -29,16 +34,68 @@ pub fn relative_path_contains(ancestor: &str, path: &str, platform: Platform) -> .is_some_and(|suffix| suffix.starts_with('/')) } -/// Writes every Windows `\` separator as `/`. +/// Whether `character` separates path components on `platform`. +/// +/// Every platform separates at `/`. Windows also separates at `\`, which is +/// an ordinary file-name character on Unix. +pub const fn is_separator(character: char, platform: Platform) -> bool { + character == '/' || (platform.is_windows() && character == '\\') +} + +/// Writes every separator of `platform` as `/`. /// -/// On Unix `\` is an ordinary file-name character, so the text is returned -/// unchanged. +/// On Unix only `/` separates, so the text is returned unchanged. pub fn slash_separated(path: &str, platform: Platform) -> Cow<'_, str> { - if platform.is_windows() && path.contains('\\') { - Cow::Owned(path.replace('\\', "/")) - } else { - Cow::Borrowed(path) + let native = |character: char| character != '/' && is_separator(character, platform); + if !path.contains(native) { + return Cow::Borrowed(path); } + Cow::Owned( + path.chars() + .map(|character| if native(character) { '/' } else { character }) + .collect(), + ) +} + +/// [`slash_separated`] text of a native path. Bytes that are not UTF-8 +/// become U+FFFD. +pub fn slash_separated_path(path: &Path, platform: Platform) -> String { + slash_separated(&path.to_string_lossy(), platform).into_owned() +} + +/// Whether `/`-separated `value` fails to name a path below a root on +/// `platform`. +/// +/// The path is invalid when it is empty, starts with `/`, contains NUL or has +/// a `..` component. A component is invalid when `platform` would not read it +/// as one file name: on Windows a component containing a `\` separator, or a +/// `:` that names a drive (`C:x`) or an alternate data stream +/// (`file:stream`). Native text goes through [`invalid_native_relative_path`]. +pub fn invalid_relative_path(value: &str, platform: Platform) -> bool { + value.is_empty() + || value.starts_with('/') + || value.contains('\0') + || value.split('/').any(|component| { + component == ".." + || component.contains(|character| is_separator(character, platform)) + || (platform.is_windows() && component.contains(':')) + }) +} + +/// [`invalid_relative_path`] for native text, such as a path a user typed, +/// that may spell `platform`'s own separators. +pub fn invalid_native_relative_path(value: &str, platform: Platform) -> bool { + invalid_relative_path(&slash_separated(value, platform), platform) +} + +/// Whether `value` fails [`invalid_relative_path`] on any platform. +/// +/// A path saved in a document that every platform reads must name the same +/// files on each of them, so it may not contain `\` or `:`. +pub fn invalid_portable_relative_path(value: &str) -> bool { + Platform::ALL + .into_iter() + .any(|platform| invalid_relative_path(value, platform)) } /// Separator between the entries of a path list such as `PATH`. @@ -71,9 +128,7 @@ pub fn is_absolute_path(path: &str, platform: Platform) -> bool { /// Appends a `/`-separated relative path to a native directory with the /// platform's separator, dropping separators that already end `directory`. pub fn join_native(directory: &str, relative: &str, platform: Platform) -> String { - let is_separator = - |character: char| character == '/' || (platform.is_windows() && character == '\\'); - let trimmed = directory.trim_end_matches(is_separator); + let trimmed = directory.trim_end_matches(|character| is_separator(character, platform)); let (separator, relative) = if platform.is_windows() { ('\\', relative.replace('/', "\\")) } else { @@ -105,10 +160,12 @@ pub fn native_path_from_bytes(bytes: &[u8]) -> Option<&Path> { #[cfg(test)] mod tests { use super::{ - is_absolute_path, join_native, native_path_from_bytes, path_list_separator, - relative_path_contains, slash_separated, + invalid_native_relative_path, invalid_portable_relative_path, invalid_relative_path, + is_absolute_path, is_separator, join_native, native_path_from_bytes, path_list_separator, + relative_path_contains, slash_separated, slash_separated_path, }; use crate::Platform; + use std::path::Path; #[test] fn the_root_contains_every_path() { @@ -160,6 +217,75 @@ mod tests { r"name\with\backslash" ); assert_eq!(slash_separated("a/b", Platform::Windows), "a/b"); + assert_eq!( + slash_separated_path(Path::new(r"D:\logs\app.log"), Platform::Unix), + r"D:\logs\app.log" + ); + assert_eq!( + slash_separated_path(Path::new(r"src\main.rs"), Platform::Windows), + "src/main.rs" + ); + } + + #[test] + fn every_platform_separates_at_a_slash_and_only_windows_at_a_backslash() { + for platform in Platform::ALL { + assert!(is_separator('/', platform)); + assert!(!is_separator(':', platform)); + } + assert!(is_separator('\\', Platform::Windows)); + assert!(!is_separator('\\', Platform::Unix)); + } + + #[test] + fn relative_paths_that_leave_the_root_are_invalid_on_every_platform() { + for platform in Platform::ALL { + for path in ["", "/etc", "..", "a/../b", "a/..", "a\0b"] { + assert!(invalid_relative_path(path, platform), "{path:?}"); + } + for path in ["a", "a/b", "a/b/", ".a/..b", "a..b"] { + assert!(!invalid_relative_path(path, platform), "{path:?}"); + } + } + } + + #[test] + fn only_windows_rejects_backslashes_and_colons_in_a_component() { + for path in [ + r"D:\logs", + r"D:\logs/spring.log", + r"a\b.log", + "a:b", + r"..\x", + ] { + assert!(invalid_relative_path(path, Platform::Windows), "{path:?}"); + assert!(!invalid_relative_path(path, Platform::Unix), "{path:?}"); + } + assert!(invalid_relative_path("C:x", Platform::Windows)); + assert!(invalid_relative_path("file:stream", Platform::Windows)); + } + + #[test] + fn native_paths_are_read_with_the_platform_separators() { + assert!(!invalid_native_relative_path( + r"src\main", + Platform::Windows + )); + assert!(!invalid_native_relative_path(r"src\main", Platform::Unix)); + assert!(invalid_native_relative_path(r"..\x", Platform::Windows)); + assert!(!invalid_native_relative_path(r"..\x", Platform::Unix)); + assert!(invalid_native_relative_path(r"C:\x", Platform::Windows)); + for platform in Platform::ALL { + assert!(invalid_native_relative_path("../x", platform)); + } + } + + #[test] + fn portable_paths_hold_on_every_platform() { + assert!(!invalid_portable_relative_path("module/src")); + for path in [r"D:\logs", "a:b", r"..\x", "../x", ""] { + assert!(invalid_portable_relative_path(path), "{path:?}"); + } } #[test] diff --git a/rust/crates/plugin-output-links/Cargo.toml b/rust/crates/plugin-output-links/Cargo.toml index 1d3fefd4..825591e2 100644 --- a/rust/crates/plugin-output-links/Cargo.toml +++ b/rust/crates/plugin-output-links/Cargo.toml @@ -7,6 +7,7 @@ description = "Output link matchers plugins declare, console-line matching and r [dependencies] lithe-document-uri = { path = "../document-uri" } +lithe-platform = { path = "../platform" } lithe-plugin-model = { path = "../plugin-model" } lithe-protocol = { path = "../protocol" } lithe-toolchain = { path = "../toolchain" } diff --git a/rust/crates/plugin-output-links/src/lib.rs b/rust/crates/plugin-output-links/src/lib.rs index 8c3520e5..9b221dfc 100644 --- a/rust/crates/plugin-output-links/src/lib.rs +++ b/rust/crates/plugin-output-links/src/lib.rs @@ -343,11 +343,8 @@ fn location( let line = number("line")?; let column = number("column")?; let windows = platform == "windows"; - let text = if windows { - raw.replace('\\', "/") - } else { - raw.to_string() - }; + let text = lithe_platform::paths::slash_separated(raw, lithe_toolchain::paths::rules(platform)) + .into_owned(); let absolute = text.starts_with('/') || (windows && text.as_bytes().get(1) == Some(&b':')); let mut paths = Vec::new(); if absolute { diff --git a/rust/crates/project-generators/src/plan.rs b/rust/crates/project-generators/src/plan.rs index 666a72fa..108bdb76 100644 --- a/rust/crates/project-generators/src/plan.rs +++ b/rust/crates/project-generators/src/plan.rs @@ -277,10 +277,13 @@ fn template_files( let mut files = Vec::with_capacity(relative_files.len()); for relative in relative_files { - let relative_text = relative - .to_str() - .ok_or_else(|| template_error("A template path is not UTF-8.".into()))? - .replace('\\', "/"); + let relative_text = lithe_platform::paths::slash_separated( + relative + .to_str() + .ok_or_else(|| template_error("A template path is not UTF-8.".into()))?, + lithe_platform::Platform::HOST, + ) + .into_owned(); let full = root.join(&relative); let metadata = fs::symlink_metadata(&full) .map_err(|error| template_error(format!("{relative_text}: {error}")))?; diff --git a/rust/crates/project/src/directory_actions.rs b/rust/crates/project/src/directory_actions.rs index 6b7c56e6..3dd6dc76 100644 --- a/rust/crates/project/src/directory_actions.rs +++ b/rust/crates/project/src/directory_actions.rs @@ -17,6 +17,8 @@ //! The sequence contract is `rust/fixtures/workspace/directory-actions-v1.json`; the //! request and response shapes are pinned by `directory-rules-v1.json`. +use lithe_platform::paths::invalid_relative_path; +use lithe_platform::Platform; use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -302,11 +304,7 @@ fn parse(payload: Value) -> Result } fn validate_path(path: &str) -> Result<(), CoreError> { - if path.is_empty() - || path.starts_with('/') - || path.contains(['\\', ':', '\0']) - || path.split('/').any(|part| part == "..") - { + if invalid_relative_path(path, Platform::HOST) { return Err(CoreError::new( ErrorCode::InvalidRequest, "Directory rule paths must be workspace-relative", diff --git a/rust/crates/project/src/file_operations.rs b/rust/crates/project/src/file_operations.rs index 42cb3fd7..2aacbb57 100644 --- a/rust/crates/project/src/file_operations.rs +++ b/rust/crates/project/src/file_operations.rs @@ -12,6 +12,8 @@ //! reports that the name now exists, add that name to `existing` and plan again. Core //! never touches the file system. +use lithe_platform::paths::invalid_relative_path; +use lithe_platform::Platform; use lithe_protocol::{CoreError, ErrorCode}; use serde::Deserialize; use serde_json::{json, Value}; @@ -72,6 +74,7 @@ pub fn plan_duplicate_command(payload: Value) -> Result { &request.existing, request.case_insensitive, true, + Platform::HOST, )?; Ok(json!({ "name": names[0] })) } @@ -94,6 +97,7 @@ pub fn plan_paste_command(payload: Value) -> Result { &request.existing, request.case_insensitive, false, + Platform::HOST, )?; Ok(json!({ "names": names })) } @@ -108,6 +112,7 @@ fn plan( existing: &[String], case_insensitive: bool, always_suffix: bool, + platform: Platform, ) -> Result, CoreError> { if existing.len() > MAX_EXISTING_NAMES { return Err(CoreError::new( @@ -125,7 +130,7 @@ fn plan( let mut taken: HashSet = existing.iter().map(|name| key(name)).collect(); let mut planned = Vec::with_capacity(items.len()); for item in items { - validate_name(&item.name)?; + validate_name(&item.name, platform)?; let (stem, extension) = split_name(&item.name, item.is_directory); let chosen = std::iter::once(0usize) .filter(|_| !always_suffix) @@ -143,12 +148,14 @@ fn plan( Ok(planned) } -fn validate_name(name: &str) -> Result<(), CoreError> { - if name.is_empty() - || name == "." - || name == ".." +/// Rejects `name` unless `platform` reads it as one file name. On Unix `\` and +/// `:` are ordinary characters, so `D:\logs` is a name there but not on Windows. +fn validate_name(name: &str, platform: Platform) -> Result<(), CoreError> { + // One component of a valid relative path is a single file name. + if name == "." || name.len() > MAX_NAME_BYTES - || name.contains(['/', '\\', '\0']) + || name.contains('/') + || invalid_relative_path(name, platform) { return Err(CoreError::new( ErrorCode::InvalidRequest, @@ -168,3 +175,35 @@ fn split_name(name: &str, is_directory: bool) -> (&str, &str) { _ => (name, ""), } } + +#[cfg(test)] +mod tests { + use super::validate_name; + use lithe_platform::Platform; + use serde_json::Value; + + fn names(key: &str) -> Vec { + let fixture: Value = serde_json::from_str(include_str!( + "../../../fixtures/workspace/file-copy-names-v1.json" + )) + .expect("file copy names fixture should be JSON"); + serde_json::from_value(fixture[key].clone()).expect("fixture names should be strings") + } + + #[test] + fn invalid_names_are_rejected_on_every_platform() { + for name in names("invalidNames") { + for platform in Platform::ALL { + assert!(validate_name(&name, platform).is_err(), "{name:?}"); + } + } + } + + #[test] + fn only_windows_rejects_names_with_a_backslash_or_a_colon() { + for name in names("windowsInvalidNames") { + assert!(validate_name(&name, Platform::Windows).is_err(), "{name:?}"); + assert!(validate_name(&name, Platform::Unix).is_ok(), "{name:?}"); + } + } +} diff --git a/rust/crates/project/src/files.rs b/rust/crates/project/src/files.rs index 46862380..ddddbb04 100644 --- a/rust/crates/project/src/files.rs +++ b/rust/crates/project/src/files.rs @@ -9,7 +9,11 @@ use crate::contracts::{ WorkspaceSnapshotResponse, }; use lithe_core_rules::file_names::FileNameKey; -use lithe_protocol::{invalid_relative_path, CoreError, ErrorCode}; +use lithe_platform::paths::{ + invalid_relative_path, is_separator, slash_separated, slash_separated_path, +}; +use lithe_platform::Platform; +use lithe_protocol::{CoreError, ErrorCode}; use lithe_workspace::fs; use regex::{Regex, RegexBuilder}; use serde::{Deserialize, Serialize}; diff --git a/rust/crates/project/src/files/events.rs b/rust/crates/project/src/files/events.rs index 97ba600e..289e2a84 100644 --- a/rust/crates/project/src/files/events.rs +++ b/rust/crates/project/src/files/events.rs @@ -13,11 +13,13 @@ pub fn is_workspace_event_relevant(relative: &str) -> bool { /// off with a `!` hidden-path entry is visible, so its events are kept. fn is_workspace_event_relevant_with(relative: &str, hidden_file_patterns: &[String]) -> bool { let disabled = disabled_built_ins(hidden_file_patterns); - !relative.split(['/', '\\']).any(|component| { - BUILT_IN_HIDDEN_DIRECTORIES.iter().any(|name| { - component.eq_ignore_ascii_case(name) && !is_disabled_directory(name, &disabled) + !relative + .split(|character| is_separator(character, Platform::HOST)) + .any(|component| { + BUILT_IN_HIDDEN_DIRECTORIES.iter().any(|name| { + component.eq_ignore_ascii_case(name) && !is_disabled_directory(name, &disabled) + }) }) - }) } /// Changed paths for `workspace.filterChanges`: a bare path list, or the diff --git a/rust/crates/project/src/files/paths.rs b/rust/crates/project/src/files/paths.rs index e717fd9a..cf204ebc 100644 --- a/rust/crates/project/src/files/paths.rs +++ b/rust/crates/project/src/files/paths.rs @@ -15,15 +15,24 @@ pub(crate) fn existing_root(value: &str) -> Result { fs::canonicalize(path).map_err(CoreError::from) } -pub(crate) fn safe_relative_path(root: &Path, value: &str) -> Result { - let relative = Path::new(value); - if relative.is_absolute() || invalid_relative_path(value) { +/// `value` in the shared `/`-separated form, or an error when it does not +/// name a path below the workspace root on this host. +/// +/// Requests may still spell a Windows path with `\`; [`slash_separated`] +/// turns only this host's separators into `/`. +fn relative_request_path(value: &str) -> Result, CoreError> { + let value = slash_separated(value, Platform::HOST); + if invalid_relative_path(&value, Platform::HOST) { return Err(CoreError::new( ErrorCode::InvalidRequest, "Path must be relative to the workspace", )); } - let path = root.join(relative); + Ok(value) +} + +pub(crate) fn safe_relative_path(root: &Path, value: &str) -> Result { + let path = root.join(relative_request_path(value)?.as_ref()); let canonical = fs::canonicalize(path).map_err(CoreError::from)?; if !canonical.starts_with(root) { return Err(CoreError::new( @@ -35,14 +44,7 @@ pub(crate) fn safe_relative_path(root: &Path, value: &str) -> Result Result { - let relative = Path::new(value); - if relative.is_absolute() || invalid_relative_path(value) { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Path must be relative to the workspace", - )); - } - let path = root.join(relative); + let path = root.join(relative_request_path(value)?.as_ref()); if let Some(parent) = path.parent() { let mut existing_parent = parent; while !fs::try_exists(existing_parent)? { @@ -76,22 +78,15 @@ pub(crate) fn writable_relative_path(root: &Path, value: &str) -> Result String { - path.strip_prefix(root) - .unwrap_or(path) - .to_string_lossy() - .replace('\\', "/") + slash_separated_path(path.strip_prefix(root).unwrap_or(path), Platform::HOST) .trim_matches('/') .to_string() } pub(crate) fn safe_relative_path_string(value: &str) -> Result { - let path = Path::new(value); - if path.is_absolute() || invalid_relative_path(value) { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Path must be relative to the workspace", - )); - } - Ok(value.replace('\\', "/").trim_matches('/').to_string()) + Ok(relative_request_path(value)?.trim_matches('/').to_string()) } diff --git a/rust/crates/project/src/files/snapshot.rs b/rust/crates/project/src/files/snapshot.rs index 5e65437f..c3763bf5 100644 --- a/rust/crates/project/src/files/snapshot.rs +++ b/rust/crates/project/src/files/snapshot.rs @@ -117,7 +117,9 @@ fn listable_directory(root: &Path, relative: &str, rules: &VisibilityRules) -> O if relative.is_empty() { return Some(root.to_path_buf()); } - if Path::new(relative).is_absolute() || invalid_relative_path(relative) { + let relative = slash_separated(relative, Platform::HOST); + let relative = relative.as_ref(); + if invalid_relative_path(relative, Platform::HOST) { return None; } let mut current = root.to_path_buf(); diff --git a/rust/crates/project/src/history.rs b/rust/crates/project/src/history.rs index db23f720..c4fbb3f2 100644 --- a/rust/crates/project/src/history.rs +++ b/rust/crates/project/src/history.rs @@ -2,7 +2,9 @@ use crate::contracts::{HistoryEntriesResponse, HistoryEntryResponse}; use crate::files::VisibilityRules; -use lithe_protocol::{invalid_relative_path, CoreError, ErrorCode}; +use lithe_platform::paths::{invalid_relative_path, slash_separated, slash_separated_path}; +use lithe_platform::Platform; +use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeSet, HashMap}; use std::fs; @@ -874,11 +876,12 @@ fn read_entries(directory: &Path, storage: &Path) -> Vec { return (value.version == HISTORY_VERSION).then_some(value); } let legacy = serde_json::from_slice::(&data).ok()?; - let content = PathBuf::from(legacy.content_url) - .strip_prefix(storage) - .ok()? - .to_string_lossy() - .replace('\\', "/"); + let content = slash_separated_path( + PathBuf::from(legacy.content_url) + .strip_prefix(storage) + .ok()?, + Platform::HOST, + ); Some(StoredEntry { version: HISTORY_VERSION, id: legacy.id, @@ -1162,14 +1165,14 @@ fn storage_root(value: &str) -> Result { } fn safe_relative_path(value: &str) -> Result { - let path = Path::new(value); - if path.is_absolute() || invalid_relative_path(value) { + let value = slash_separated(value, Platform::HOST); + if invalid_relative_path(&value, Platform::HOST) { return Err(CoreError::new( ErrorCode::InvalidRequest, "Path must be relative", )); } - let normalized = value.replace('\\', "/").trim_matches('/').to_string(); + let normalized = value.trim_matches('/').to_string(); if normalized.is_empty() { return Err(CoreError::new( ErrorCode::InvalidRequest, diff --git a/rust/crates/project/src/indexing.rs b/rust/crates/project/src/indexing.rs index 506c100c..94642074 100644 --- a/rust/crates/project/src/indexing.rs +++ b/rust/crates/project/src/indexing.rs @@ -1,7 +1,7 @@ //! Workspace-owned indexing exclusions, independent of tree visibility and Git writes. use super::files::{existing_root, is_nested_linked_worktree, relative_path, VisibilityRules}; -use lithe_platform::paths::relative_path_contains; +use lithe_platform::paths::{invalid_relative_path, relative_path_contains}; use lithe_platform::Platform; use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; @@ -147,12 +147,8 @@ fn validate_paths(paths: &mut Vec) -> Result<(), CoreError> { for path in paths.iter_mut() { *path = path.trim_end_matches('/').to_string(); if path != "." - && (path.is_empty() - || Path::new(path).is_absolute() - || path.contains(['\\', '\0', ':']) - || path - .split('/') - .any(|part| part.is_empty() || part == ".." || part == ".")) + && (invalid_relative_path(path, Platform::HOST) + || path.split('/').any(|part| part.is_empty() || part == ".")) { return Err(CoreError::new( ErrorCode::InvalidRequest, diff --git a/rust/crates/protocol/src/error.rs b/rust/crates/protocol/src/error.rs index 14c58b76..c98ce5f8 100644 --- a/rust/crates/protocol/src/error.rs +++ b/rust/crates/protocol/src/error.rs @@ -107,15 +107,3 @@ impl From for CoreError { Self::new(code, error.to_string()) } } - -/// Workspace-relative paths use `/` in the shared contract even when the -/// caller is running on Windows. Validate both separator conventions so a -/// Windows-shaped path cannot bypass checks on another host. -pub fn invalid_relative_path(value: &str) -> bool { - let normalized = value.replace('\\', "/"); - normalized.is_empty() - || normalized.starts_with('/') - || normalized.contains(':') - || normalized.contains('\0') - || normalized.split('/').any(|component| component == "..") -} diff --git a/rust/crates/protocol/src/lib.rs b/rust/crates/protocol/src/lib.rs index f0524ad7..dec753d1 100644 --- a/rust/crates/protocol/src/lib.rs +++ b/rust/crates/protocol/src/lib.rs @@ -10,5 +10,5 @@ mod error; pub mod json_document; mod response; -pub use error::{invalid_relative_path, CoreError, ErrorCode}; +pub use error::{CoreError, ErrorCode}; pub use response::{CoreResponse, ResponseData}; diff --git a/rust/crates/toolchain/Cargo.toml b/rust/crates/toolchain/Cargo.toml index 3866b049..6f66d424 100644 --- a/rust/crates/toolchain/Cargo.toml +++ b/rust/crates/toolchain/Cargo.toml @@ -7,6 +7,7 @@ description = "Plugin-owned toolchain policy for Lithe: tool definitions, direct [dependencies] ignore = "=0.4.33" +lithe-platform = { path = "../platform" } lithe-plugin-model = { path = "../plugin-model" } lithe-protocol = { path = "../protocol" } regex = "1.11" diff --git a/rust/crates/toolchain/src/paths.rs b/rust/crates/toolchain/src/paths.rs index 54dc3276..c6769e03 100644 --- a/rust/crates/toolchain/src/paths.rs +++ b/rust/crates/toolchain/src/paths.rs @@ -1,20 +1,25 @@ //! Lexical native-path policy independent of the machine running Core. +use lithe_platform::paths::{is_separator, slash_separated}; +use lithe_platform::Platform; + +/// Separator rules for a host platform name (`windows`, `macos`, `linux`). +pub fn rules(platform: &str) -> Platform { + if platform == "windows" { + Platform::Windows + } else { + Platform::Unix + } +} + /// Normalizes a bounded absolute path using the target platform's separators. /// Native adapters must supply canonical filesystem facts separately. pub fn normalize(path: &str, platform: &str, case_sensitive: bool) -> Option { if path.is_empty() || path.len() > 4096 || path.chars().any(char::is_control) { return None; } - let windows = platform == "windows"; - let text = if windows { - path.replace('\\', "/") - } else { - if path.contains('\\') { - return None; - } - path.to_owned() - }; + let windows = rules(platform).is_windows(); + let text = slash_separated(path, rules(platform)).into_owned(); let (prefix, remainder) = if windows { let bytes = text.as_bytes(); if bytes.len() >= 3 @@ -90,8 +95,33 @@ pub fn join(home: &str, relative: &str, platform: &str) -> Option { return None; } normalize( - &format!("{}/{relative}", home.trim_end_matches(['/', '\\'])), + &format!( + "{}/{relative}", + home.trim_end_matches(|character| is_separator(character, rules(platform))) + ), platform, true, ) } + +#[cfg(test)] +mod tests { + use super::normalize; + + #[test] + fn only_windows_reads_a_backslash_as_a_separator() { + assert_eq!( + normalize(r"C:\Tools\jdk", "windows", true).as_deref(), + Some("C:/Tools/jdk") + ); + assert_eq!( + normalize(r"/opt/a\b/jdk", "linux", true).as_deref(), + Some(r"/opt/a\b/jdk") + ); + assert_eq!( + normalize(r"/opt/a\b/jdk", "macos", true).as_deref(), + Some(r"/opt/a\b/jdk") + ); + assert_eq!(normalize(r"\opt\jdk", "linux", true), None); + } +} diff --git a/rust/fixtures/workspace/file-copy-names-v1.json b/rust/fixtures/workspace/file-copy-names-v1.json index 5b7571d6..25598c27 100644 --- a/rust/fixtures/workspace/file-copy-names-v1.json +++ b/rust/fixtures/workspace/file-copy-names-v1.json @@ -21,5 +21,6 @@ {"id": "case-insensitive-paste", "request": {"items": [{"name": "Readme.MD", "isDirectory": false}], "existing": ["readme.md"], "caseInsensitive": true}, "names": ["Readme copy.MD"]}, {"id": "directory-paste", "request": {"items": [{"name": "src.v2", "isDirectory": true}], "existing": ["src.v2", "src.v2 copy"]}, "names": ["src.v2 copy 2"]} ], - "invalidNames": ["", ".", "..", "a/b", "a\\b"] + "invalidNames": ["", ".", "..", "a/b"], + "windowsInvalidNames": ["a\\b", "D:\\logs", "a:b"] }