Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions rust/crates/workspace/src/fs.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Filesystem adapter for workspace engines, with no local fallback on remote errors.

use crate::scope::{self as workspace, Host};
use lithe_platform::{paths::invalid_relative_path, Platform};
use lithe_remote::client::session::ClientError;
use lithe_remote::protocol::{methods, ErrorCode};
use serde::de::DeserializeOwned;
Expand Down Expand Up @@ -590,6 +591,14 @@ pub fn read_dir(
.entries
.into_iter()
.map(|entry| {
// The server sends a Unix leaf. Keep a Windows separator or
// drive prefix from changing the placeholder it belongs to.
if invalid_relative_path(&entry.name, Platform::HOST) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Remote entry name cannot be represented on this client",
));
}
Ok(DirEntry {
path: path_value.join(entry.name),
kind: entry.metadata.kind,
Expand Down
206 changes: 169 additions & 37 deletions rust/crates/workspace/src/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
//! executables. Git continues to own Git semantics; this boundary supplies IO.

use crate::sessions::{lookup, Connection};
use lithe_platform::{
paths::{invalid_relative_path, is_absolute_path, join_native, slash_separated},
Platform,
};
use lithe_protocol::{CoreError, ErrorCode};
use serde::Deserialize;
use std::cell::RefCell;
Expand All @@ -16,7 +20,7 @@ use std::sync::Arc;
pub struct Workspace {
session_id: String,
local_root: PathBuf,
remote_root: PathBuf,
remote_root: String,
}

/// The connected host a request's workspace lives on, and its path mapping.
Expand All @@ -38,16 +42,17 @@ impl Scope {
/// with `..`, or when the session is not connected.
pub fn begin(workspace: Option<Workspace>) -> Result<Self, CoreError> {
let host = workspace
.map(|workspace| {
if !valid_root(&workspace.local_root)
|| workspace.local_root.file_name().is_none()
|| !valid_root(&workspace.remote_root)
{
.map(|mut workspace| {
let root = normalize_remote_path(&workspace.remote_root);
let Some(root) = root.filter(|_| {
valid_root(&workspace.local_root) && workspace.local_root.file_name().is_some()
}) else {
return Err(CoreError::new(
ErrorCode::InvalidRequest,
"Workspace roots must be absolute without parent components",
));
}
};
workspace.remote_root = root;
Ok(Host {
connection: lookup(&workspace.session_id)?,
workspace,
Expand All @@ -70,6 +75,28 @@ fn valid_root(path: &Path) -> bool {
.any(|component| matches!(component, std::path::Component::ParentDir))
}

fn normalize_remote_path(path: &str) -> Option<String> {
// Shipped workspace servers run on Unix, even when the client is Windows.
if !is_absolute_path(path, Platform::Unix) || path.contains('\0') {
return None;
}
let mut normalized = String::with_capacity(path.len());
for part in path
.split('/')
.filter(|part| !part.is_empty() && *part != ".")
{
if part == ".." {
return None;
}
normalized.push('/');
normalized.push_str(part);
}
if normalized.is_empty() {
normalized.push('/');
}
Some(normalized)
}

impl Drop for Scope {
fn drop(&mut self) {
HOST.with(|current| current.replace(self.0.take()));
Expand Down Expand Up @@ -114,45 +141,66 @@ impl Host {
/// Translates a placeholder path to the host path it stands for; paths
/// outside the workspace stay as they are.
pub fn remote_path(&self, path: &Path) -> PathBuf {
if let Ok(suffix) = path.strip_prefix(self.host_paths_root()) {
return Path::new("/").join(suffix);
}
if path == self.workspace.local_root {
return self.workspace.remote_root.clone();
}
path.strip_prefix(&self.workspace.local_root)
.map(|suffix| self.workspace.remote_root.join(suffix))
.unwrap_or_else(|_| path.to_owned())
self.workspace
.project_to_remote(path, Platform::HOST)
.unwrap_or_else(|| path.to_owned())
}

pub(crate) fn local_path(&self, path: &Path) -> PathBuf {
if path == self.workspace.remote_root {
return self.workspace.local_root.clone();
path.to_str()
.and_then(|path| self.workspace.project_to_local(path, Platform::HOST))
.unwrap_or_else(|| path.to_owned())
}

pub(crate) fn identity(&self) -> &str {
&self.workspace.session_id
}
}

impl Workspace {
fn project_to_remote(&self, path: &Path, client: Platform) -> Option<PathBuf> {
let (root, suffix) = if let Ok(suffix) = path.strip_prefix(self.host_paths_root()) {
("/", suffix)
} else {
(
self.remote_root.as_str(),
path.strip_prefix(&self.local_root).ok()?,
)
};
let suffix = slash_separated(suffix.to_str()?, client);
Some(if suffix.is_empty() {
PathBuf::from(root)
} else {
PathBuf::from(join_native(root, &suffix, Platform::Unix))
})
}

fn project_to_local(&self, path: &str, client: Platform) -> Option<PathBuf> {
let path = normalize_remote_path(path)?;
if path == self.remote_root {
return Some(self.local_root.clone());
}
path.strip_prefix(&self.workspace.remote_root)
.map(|suffix| self.workspace.local_root.join(suffix))
.unwrap_or_else(|_| {
path.strip_prefix("/")
.map(|suffix| self.host_paths_root().join(suffix))
.unwrap_or_else(|_| path.to_owned())
})
let (root, suffix) = if let Some(suffix) = path
.strip_prefix(self.remote_root.trim_end_matches('/'))
.and_then(|suffix| suffix.strip_prefix('/'))
{
(self.local_root.clone(), suffix)
} else {
(self.host_paths_root(), path.trim_start_matches('/'))
};
if suffix.is_empty() {
return Some(root);
}
// A name legal on Unix can be a separator, drive or stream on Windows.
// Mapping it to a native path would change its identity.
(!invalid_relative_path(suffix, client)).then(|| root.join(suffix))
}

fn host_paths_root(&self) -> PathBuf {
// A sibling namespace cannot collide with files in the opened folder.
// Keep this projection in sync with RemoteWorkspaceBinding on macOS.
let mut name = self
.workspace
.local_root
.file_name()
.unwrap()
.to_os_string();
let mut name = self.local_root.file_name().unwrap().to_os_string();
name.push(".lithe-remote-host");
self.workspace.local_root.with_file_name(name)
}

pub(crate) fn identity(&self) -> &str {
&self.workspace.session_id
self.local_root.with_file_name(name)
}
}

Expand All @@ -176,3 +224,87 @@ pub fn identity_key(path: &Path) -> PathBuf {
.map(|host| PathBuf::from(host.identity()).join(path.strip_prefix("/").unwrap_or(path)))
.unwrap_or_else(|| path.to_owned())
}

#[cfg(test)]
mod tests {
use super::*;

fn workspace(remote_root: &str) -> Workspace {
Workspace {
session_id: "missing-test-session".into(),
local_root: std::env::temp_dir().join("remote-workspace"),
remote_root: remote_root.into(),
}
}

#[test]
fn remote_root_validation_precedes_connection_lookup() {
for (path, expected) in [
("/srv/repo", ErrorCode::ConnectionClosed),
("/", ErrorCode::ConnectionClosed),
("/srv/./repo//", ErrorCode::ConnectionClosed),
("srv/repo", ErrorCode::InvalidRequest),
(r"C:\srv\repo", ErrorCode::InvalidRequest),
("/srv/../repo", ErrorCode::InvalidRequest),
("/srv/\0repo", ErrorCode::InvalidRequest),
] {
let error = match Scope::begin(Some(workspace(path))) {
Err(error) => error,
Ok(_) => panic!("unexpected session for {path:?}"),
};
assert_eq!(
std::mem::discriminant(&error.code),
std::mem::discriminant(&expected),
"{path:?}: got {:?}",
error.code
);
}
}

#[test]
fn workspace_and_host_paths_keep_their_namespace() {
let workspace = workspace("/srv/repo");
for client in Platform::ALL {
let relative = Path::new("src").join("main.rs");
let local = workspace.local_root.join(relative);
let remote = workspace.project_to_remote(&local, client).unwrap();
assert_eq!(remote.to_str(), Some("/srv/repo/src/main.rs"));
assert_eq!(
workspace.project_to_local("/srv/repo/./src//main.rs", client),
Some(local)
);

let external = workspace.host_paths_root().join("srv/repository/lib.rs");
assert_eq!(
workspace.project_to_local("/srv/repository/lib.rs", client),
Some(external.clone())
);
assert_eq!(
workspace
.project_to_remote(&external, client)
.unwrap()
.to_str(),
Some("/srv/repository/lib.rs")
);
assert_eq!(
workspace.project_to_local("/", client),
Some(workspace.host_paths_root())
);
}
}

#[test]
fn unix_file_names_cannot_become_windows_separators_or_drives() {
let workspace = workspace("/");
for name in [r"dir\leaf", "D:leaf"] {
let remote = format!("/{name}");
assert_eq!(
workspace.project_to_local(&remote, Platform::Unix),
Some(workspace.local_root.join(name))
);
assert!(workspace
.project_to_local(&remote, Platform::Windows)
.is_none());
}
}
}
Loading