feat(app-server): complete filesystem host semantics

This commit is contained in:
Jeremy Rose
2026-06-17 18:45:11 -07:00
parent c274a83f8b
commit ded6a00c42
28 changed files with 552 additions and 48 deletions
@@ -928,6 +928,10 @@
],
"description": "Absolute destination path."
},
"exclusive": {
"description": "Fail if the destination already exists.",
"type": "boolean"
},
"recursive": {
"description": "Required for directory copies; ignored for file copies.",
"type": "boolean"
@@ -974,6 +978,13 @@
"FsGetMetadataParams": {
"description": "Request metadata for an absolute path.",
"properties": {
"followSymlinks": {
"description": "Whether metadata should describe the symlink target. Defaults to `true`.",
"type": [
"boolean",
"null"
]
},
"path": {
"allOf": [
{
@@ -9785,6 +9785,10 @@
],
"description": "Absolute destination path."
},
"exclusive": {
"description": "Fail if the destination already exists.",
"type": "boolean"
},
"recursive": {
"description": "Required for directory copies; ignored for file copies.",
"type": "boolean"
@@ -9847,6 +9851,13 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "Request metadata for an absolute path.",
"properties": {
"followSymlinks": {
"description": "Whether metadata should describe the symlink target. Defaults to `true`.",
"type": [
"boolean",
"null"
]
},
"path": {
"allOf": [
{
@@ -9887,6 +9898,12 @@
"description": "File modification time in Unix milliseconds when available, otherwise `0`.",
"format": "int64",
"type": "integer"
},
"sizeBytes": {
"description": "File size in bytes.",
"format": "uint64",
"minimum": 0.0,
"type": "integer"
}
},
"required": [
@@ -9894,7 +9911,8 @@
"isDirectory",
"isFile",
"isSymlink",
"modifiedAtMs"
"modifiedAtMs",
"sizeBytes"
],
"title": "FsGetMetadataResponse",
"type": "object"
@@ -9913,12 +9931,17 @@
"isFile": {
"description": "Whether this entry resolves to a regular file.",
"type": "boolean"
},
"isSymlink": {
"description": "Whether this entry itself is a symbolic link.",
"type": "boolean"
}
},
"required": [
"fileName",
"isDirectory",
"isFile"
"isFile",
"isSymlink"
],
"type": "object"
},
@@ -6070,6 +6070,10 @@
],
"description": "Absolute destination path."
},
"exclusive": {
"description": "Fail if the destination already exists.",
"type": "boolean"
},
"recursive": {
"description": "Required for directory copies; ignored for file copies.",
"type": "boolean"
@@ -6132,6 +6136,13 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "Request metadata for an absolute path.",
"properties": {
"followSymlinks": {
"description": "Whether metadata should describe the symlink target. Defaults to `true`.",
"type": [
"boolean",
"null"
]
},
"path": {
"allOf": [
{
@@ -6172,6 +6183,12 @@
"description": "File modification time in Unix milliseconds when available, otherwise `0`.",
"format": "int64",
"type": "integer"
},
"sizeBytes": {
"description": "File size in bytes.",
"format": "uint64",
"minimum": 0.0,
"type": "integer"
}
},
"required": [
@@ -6179,7 +6196,8 @@
"isDirectory",
"isFile",
"isSymlink",
"modifiedAtMs"
"modifiedAtMs",
"sizeBytes"
],
"title": "FsGetMetadataResponse",
"type": "object"
@@ -6198,12 +6216,17 @@
"isFile": {
"description": "Whether this entry resolves to a regular file.",
"type": "boolean"
},
"isSymlink": {
"description": "Whether this entry itself is a symbolic link.",
"type": "boolean"
}
},
"required": [
"fileName",
"isDirectory",
"isFile"
"isFile",
"isSymlink"
],
"type": "object"
},
@@ -16,6 +16,10 @@
],
"description": "Absolute destination path."
},
"exclusive": {
"description": "Fail if the destination already exists.",
"type": "boolean"
},
"recursive": {
"description": "Required for directory copies; ignored for file copies.",
"type": "boolean"
@@ -8,6 +8,13 @@
},
"description": "Request metadata for an absolute path.",
"properties": {
"followSymlinks": {
"description": "Whether metadata should describe the symlink target. Defaults to `true`.",
"type": [
"boolean",
"null"
]
},
"path": {
"allOf": [
{
@@ -23,6 +23,12 @@
"description": "File modification time in Unix milliseconds when available, otherwise `0`.",
"format": "int64",
"type": "integer"
},
"sizeBytes": {
"description": "File size in bytes.",
"format": "uint64",
"minimum": 0.0,
"type": "integer"
}
},
"required": [
@@ -30,7 +36,8 @@
"isDirectory",
"isFile",
"isSymlink",
"modifiedAtMs"
"modifiedAtMs",
"sizeBytes"
],
"title": "FsGetMetadataResponse",
"type": "object"
@@ -15,12 +15,17 @@
"isFile": {
"description": "Whether this entry resolves to a regular file.",
"type": "boolean"
},
"isSymlink": {
"description": "Whether this entry itself is a symbolic link.",
"type": "boolean"
}
},
"required": [
"fileName",
"isDirectory",
"isFile"
"isFile",
"isSymlink"
],
"type": "object"
}
@@ -18,4 +18,8 @@ destinationPath: AbsolutePathBuf,
/**
* Required for directory copies; ignored for file copies.
*/
recursive?: boolean, };
recursive?: boolean,
/**
* Fail if the destination already exists.
*/
exclusive?: boolean, };
@@ -10,4 +10,8 @@ export type FsGetMetadataParams = {
/**
* Absolute path to inspect.
*/
path: AbsolutePathBuf, };
path: AbsolutePathBuf,
/**
* Whether metadata should describe the symlink target. Defaults to `true`.
*/
followSymlinks?: boolean | null, };
@@ -18,6 +18,10 @@ isFile: boolean,
* Whether the path itself is a symbolic link.
*/
isSymlink: boolean,
/**
* File size in bytes.
*/
sizeBytes: number,
/**
* File creation time in Unix milliseconds when available, otherwise `0`.
*/
@@ -17,4 +17,8 @@ isDirectory: boolean,
/**
* Whether this entry resolves to a regular file.
*/
isFile: boolean, };
isFile: boolean,
/**
* Whether this entry itself is a symbolic link.
*/
isSymlink: boolean, };
@@ -2923,6 +2923,7 @@ mod tests {
request_id: RequestId::Integer(10),
params: v2::FsGetMetadataParams {
path: absolute_path("tmp/example"),
follow_symlinks: None,
},
};
assert_eq!(
@@ -2930,6 +2931,7 @@ mod tests {
"method": "fs/getMetadata",
"id": 10,
"params": {
"followSymlinks": null,
"path": absolute_path_string("tmp/example")
}
}),
@@ -64,6 +64,9 @@ pub struct FsCreateDirectoryResponse {}
pub struct FsGetMetadataParams {
/// Absolute path to inspect.
pub path: AbsolutePathBuf,
/// Whether metadata should describe the symlink target. Defaults to `true`.
#[ts(optional = nullable)]
pub follow_symlinks: Option<bool>,
}
/// Metadata returned by `fs/getMetadata`.
@@ -77,6 +80,9 @@ pub struct FsGetMetadataResponse {
pub is_file: bool,
/// Whether the path itself is a symbolic link.
pub is_symlink: bool,
/// File size in bytes.
#[ts(type = "number")]
pub size_bytes: u64,
/// File creation time in Unix milliseconds when available, otherwise `0`.
#[ts(type = "number")]
pub created_at_ms: i64,
@@ -105,6 +111,8 @@ pub struct FsReadDirectoryEntry {
pub is_directory: bool,
/// Whether this entry resolves to a regular file.
pub is_file: bool,
/// Whether this entry itself is a symbolic link.
pub is_symlink: bool,
}
/// Directory entries returned by `fs/readDirectory`.
@@ -149,6 +157,9 @@ pub struct FsCopyParams {
/// Required for directory copies; ignored for file copies.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub recursive: bool,
/// Fail if the destination already exists.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub exclusive: bool,
}
/// Successful response for `fs/copy`.
@@ -813,6 +813,7 @@ fn fs_get_metadata_response_round_trips_minimal_fields() {
is_directory: false,
is_file: true,
is_symlink: false,
size_bytes: 5,
created_at_ms: 123,
modified_at_ms: 456,
};
@@ -824,6 +825,7 @@ fn fs_get_metadata_response_round_trips_minimal_fields() {
"isDirectory": false,
"isFile": true,
"isSymlink": false,
"sizeBytes": 5,
"createdAtMs": 123,
"modifiedAtMs": 456,
})
@@ -920,6 +922,7 @@ fn fs_copy_params_round_trip_with_recursive_directory_copy() {
source_path: absolute_path("tmp/source"),
destination_path: absolute_path("tmp/destination"),
recursive: true,
exclusive: true,
};
let value = serde_json::to_value(&params).expect("serialize fs/copy params");
@@ -928,6 +931,7 @@ fn fs_copy_params_round_trip_with_recursive_directory_copy() {
json!({
"sourcePath": absolute_path_string("tmp/source"),
"destinationPath": absolute_path_string("tmp/destination"),
"exclusive": true,
"recursive": true,
})
);
+6 -5
View File
@@ -185,10 +185,10 @@ Example with notification opt-out:
- `fs/readFile` — read an absolute file path and return `{ dataBase64 }`.
- `fs/writeFile` — write an absolute file path from base64-encoded `{ dataBase64 }`; returns `{}`.
- `fs/createDirectory` — create an absolute directory path; `recursive` defaults to `true`.
- `fs/getMetadata` — return metadata for an absolute path: `isDirectory`, `isFile`, `isSymlink`, `createdAtMs`, and `modifiedAtMs`.
- `fs/readDirectory` — list direct child entries for an absolute directory path; each entry contains `fileName`, `isDirectory`, and `isFile`, and `fileName` is just the child name, not a path.
- `fs/getMetadata` — return metadata for an absolute path: `isDirectory`, `isFile`, `isSymlink`, `sizeBytes`, `createdAtMs`, and `modifiedAtMs`; set `followSymlinks: false` to inspect a link instead of its target.
- `fs/readDirectory` — list direct child entries for an absolute directory path; each entry contains `fileName`, `isDirectory`, `isFile`, and `isSymlink`, and `fileName` is just the child name, not a path.
- `fs/remove` — remove an absolute file or directory tree; `recursive` and `force` default to `true`.
- `fs/copy` — copy between absolute paths; directory copies require `recursive: true`.
- `fs/copy` — copy between absolute paths; directory copies require `recursive: true`, and file copies can set `exclusive: true` to reject an existing destination.
- `fs/watch` — subscribe this connection to filesystem change notifications for an absolute file or directory path and caller-provided `watchId`; returns the canonicalized `path`.
- `fs/unwatch` — stop sending notifications for a prior `fs/watch`; returns `{}`.
- `fs/changed` — notification emitted when watched paths change, including the `watchId` and `changedPaths`.
@@ -1235,6 +1235,7 @@ All filesystem paths in this section must be absolute.
"isDirectory": false,
"isFile": true,
"isSymlink": false,
"sizeBytes": 5,
"createdAtMs": 1730910000000,
"modifiedAtMs": 1730910000000
} }
@@ -1246,11 +1247,11 @@ All filesystem paths in this section must be absolute.
} }
```
- `fs/getMetadata` returns whether the path resolves to a directory or regular file, whether the path itself is a symlink, plus `createdAtMs` and `modifiedAtMs` in Unix milliseconds. If a timestamp is unavailable on the current platform, that field is `0`.
- `fs/getMetadata` returns whether the path resolves to a directory or regular file, whether the path itself is a symlink, its byte size, plus `createdAtMs` and `modifiedAtMs` in Unix milliseconds. `followSymlinks` defaults to `true`; set it to `false` for lstat-style metadata. If a timestamp is unavailable on the current platform, that field is `0`.
- `fs/createDirectory` defaults `recursive` to `true` when omitted.
- `fs/remove` defaults both `recursive` and `force` to `true` when omitted.
- `fs/readFile` always returns base64 bytes via `dataBase64`, and `fs/writeFile` always expects base64 bytes in `dataBase64`.
- `fs/copy` handles both file copies and directory-tree copies; it requires `recursive: true` when `sourcePath` is a directory. Recursive copies traverse regular files, directories, and symlinks; other entry types are skipped.
- `fs/copy` handles both file copies and directory-tree copies; it requires `recursive: true` when `sourcePath` is a directory. `exclusive: true` atomically rejects an existing destination for file copies. Recursive copies traverse regular files, directories, and symlinks; other entry types are skipped.
### Example: Filesystem watch
@@ -116,15 +116,20 @@ impl FsRequestProcessor {
params: FsGetMetadataParams,
) -> Result<FsGetMetadataResponse, JSONRPCErrorError> {
let path = PathUri::from_abs_path(&params.path);
let metadata = self
.file_system()?
.get_metadata(&path, /*sandbox*/ None)
.await
.map_err(map_fs_error)?;
let file_system = self.file_system()?;
let metadata = if params.follow_symlinks.unwrap_or(true) {
file_system.get_metadata(&path, /*sandbox*/ None).await
} else {
file_system
.get_symlink_metadata(&path, /*sandbox*/ None)
.await
}
.map_err(map_fs_error)?;
Ok(FsGetMetadataResponse {
is_directory: metadata.is_directory,
is_file: metadata.is_file,
is_symlink: metadata.is_symlink,
size_bytes: metadata.size,
created_at_ms: metadata.created_at_ms,
modified_at_ms: metadata.modified_at_ms,
})
@@ -147,6 +152,7 @@ impl FsRequestProcessor {
file_name: entry.file_name,
is_directory: entry.is_directory,
is_file: entry.is_file,
is_symlink: entry.is_symlink,
})
.collect(),
})
@@ -183,6 +189,7 @@ impl FsRequestProcessor {
&destination_path,
CopyOptions {
recursive: params.recursive,
exclusive: params.exclusive,
},
/*sandbox*/ None,
)
@@ -211,9 +218,13 @@ impl FsRequestProcessor {
}
fn map_fs_error(err: io::Error) -> JSONRPCErrorError {
if err.kind() == io::ErrorKind::InvalidInput {
invalid_request(err.to_string())
} else {
internal_error(err.to_string())
match err.kind() {
io::ErrorKind::InvalidInput => invalid_request(err.to_string()),
io::ErrorKind::AlreadyExists => JSONRPCErrorError {
code: -32603,
message: err.to_string(),
data: Some(serde_json::json!({ "code": "EEXIST" })),
},
_ => internal_error(err.to_string()),
}
}
+80 -1
View File
@@ -75,6 +75,7 @@ async fn fs_get_metadata_returns_only_used_fields() -> Result<()> {
let request_id = mcp
.send_fs_get_metadata_request(codex_app_server_protocol::FsGetMetadataParams {
path: absolute_path(file_path.clone()),
follow_symlinks: None,
})
.await?;
let response = timeout(
@@ -97,6 +98,7 @@ async fn fs_get_metadata_returns_only_used_fields() -> Result<()> {
"isFile".to_string(),
"isSymlink".to_string(),
"modifiedAtMs".to_string(),
"sizeBytes".to_string(),
]
);
@@ -107,6 +109,7 @@ async fn fs_get_metadata_returns_only_used_fields() -> Result<()> {
is_directory: false,
is_file: true,
is_symlink: false,
size_bytes: 5,
created_at_ms: stat.created_at_ms,
modified_at_ms: stat.modified_at_ms,
}
@@ -154,6 +157,7 @@ async fn fs_get_metadata_reports_symlink() -> Result<()> {
let request_id = mcp
.send_fs_get_metadata_request(codex_app_server_protocol::FsGetMetadataParams {
path: absolute_path(symlink_path),
follow_symlinks: Some(false),
})
.await?;
let response = timeout(
@@ -164,12 +168,78 @@ async fn fs_get_metadata_reports_symlink() -> Result<()> {
let stat: FsGetMetadataResponse = to_response(response)?;
assert_eq!(stat.is_directory, false);
assert_eq!(stat.is_file, true);
assert_eq!(stat.is_file, false);
assert_eq!(stat.is_symlink, true);
Ok(())
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn fs_read_directory_reports_symlink_entries() -> Result<()> {
let codex_home = TempDir::new()?;
let target_path = codex_home.path().join("target");
std::fs::create_dir(&target_path)?;
symlink(&target_path, codex_home.path().join("target-link"))?;
let mut mcp = initialized_mcp(&codex_home).await?;
let request_id = mcp
.send_fs_read_directory_request(codex_app_server_protocol::FsReadDirectoryParams {
path: absolute_path(codex_home.path().to_path_buf()),
})
.await?;
let response = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let entries =
to_response::<codex_app_server_protocol::FsReadDirectoryResponse>(response)?.entries;
assert_eq!(
entries
.into_iter()
.find(|entry| entry.file_name == "target-link"),
Some(FsReadDirectoryEntry {
file_name: "target-link".to_string(),
is_directory: true,
is_file: false,
is_symlink: true,
})
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn fs_copy_exclusive_preserves_existing_destination() -> Result<()> {
let codex_home = TempDir::new()?;
let source_path = codex_home.path().join("source.txt");
let destination_path = codex_home.path().join("destination.txt");
std::fs::write(&source_path, "source")?;
std::fs::write(&destination_path, "destination")?;
let mut mcp = initialized_mcp(&codex_home).await?;
let request_id = mcp
.send_fs_copy_request(FsCopyParams {
source_path: absolute_path(source_path),
destination_path: absolute_path(destination_path.clone()),
recursive: false,
exclusive: true,
})
.await?;
let error = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(request_id)),
)
.await??;
assert_eq!(error.error.data, Some(json!({ "code": "EEXIST" })));
assert_eq!(std::fs::read_to_string(destination_path)?, "destination");
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn fs_methods_cover_current_fs_utils_surface() -> Result<()> {
let codex_home = TempDir::new()?;
@@ -242,6 +312,7 @@ async fn fs_methods_cover_current_fs_utils_surface() -> Result<()> {
source_path: absolute_path(nested_file.clone()),
destination_path: absolute_path(copy_file_path.clone()),
recursive: false,
exclusive: false,
})
.await?;
timeout(
@@ -259,6 +330,7 @@ async fn fs_methods_cover_current_fs_utils_surface() -> Result<()> {
source_path: absolute_path(source_dir.clone()),
destination_path: absolute_path(copied_dir.clone()),
recursive: true,
exclusive: false,
})
.await?;
timeout(
@@ -292,11 +364,13 @@ async fn fs_methods_cover_current_fs_utils_surface() -> Result<()> {
file_name: "nested".to_string(),
is_directory: true,
is_file: false,
is_symlink: false,
},
FsReadDirectoryEntry {
file_name: "root.txt".to_string(),
is_directory: false,
is_file: true,
is_symlink: false,
},
]
);
@@ -528,6 +602,7 @@ async fn fs_copy_rejects_directory_without_recursive() -> Result<()> {
source_path: absolute_path(source_dir),
destination_path: absolute_path(codex_home.path().join("dest")),
recursive: false,
exclusive: false,
})
.await?;
let error = timeout(
@@ -555,6 +630,7 @@ async fn fs_copy_rejects_copying_directory_into_descendant() -> Result<()> {
source_path: absolute_path(source_dir.clone()),
destination_path: absolute_path(source_dir.join("nested").join("copy")),
recursive: true,
exclusive: false,
})
.await?;
let error = timeout(
@@ -586,6 +662,7 @@ async fn fs_copy_preserves_symlinks_in_recursive_copy() -> Result<()> {
source_path: absolute_path(source_dir),
destination_path: absolute_path(copied_dir.clone()),
recursive: true,
exclusive: false,
})
.await?;
timeout(
@@ -626,6 +703,7 @@ async fn fs_copy_ignores_unknown_special_files_in_recursive_copy() -> Result<()>
source_path: absolute_path(source_dir),
destination_path: absolute_path(copied_dir.clone()),
recursive: true,
exclusive: false,
})
.await?;
timeout(
@@ -663,6 +741,7 @@ async fn fs_copy_rejects_standalone_fifo_source() -> Result<()> {
source_path: absolute_path(fifo_path),
destination_path: absolute_path(codex_home.path().join("copied")),
recursive: false,
exclusive: false,
})
.await?;
expect_error_message(
+4 -1
View File
@@ -1173,7 +1173,10 @@ async fn remote_test_env_copy_preserves_symlink_source() -> Result<()> {
.copy(
&PathUri::from_path(&source_symlink)?,
&PathUri::from_path(&copied_symlink)?,
CopyOptions { recursive: false },
CopyOptions {
recursive: false,
exclusive: false,
},
Some(&sandbox),
)
.await?;
+12 -4
View File
@@ -225,10 +225,16 @@ pub(crate) async fn run_direct_request(
))
}
FsHelperRequest::GetMetadata(params) => {
let metadata = file_system
.get_metadata(&params.path, /*sandbox*/ None)
.await
.map_err(map_fs_error)?;
let metadata = if params.follow_symlinks {
file_system
.get_metadata(&params.path, /*sandbox*/ None)
.await
} else {
file_system
.get_symlink_metadata(&params.path, /*sandbox*/ None)
.await
}
.map_err(map_fs_error)?;
Ok(FsHelperPayload::GetMetadata(FsGetMetadataResponse {
is_directory: metadata.is_directory,
is_file: metadata.is_file,
@@ -257,6 +263,7 @@ pub(crate) async fn run_direct_request(
file_name: entry.file_name,
is_directory: entry.is_directory,
is_file: entry.is_file,
is_symlink: entry.is_symlink,
})
.collect();
Ok(FsHelperPayload::ReadDirectory(FsReadDirectoryResponse {
@@ -284,6 +291,7 @@ pub(crate) async fn run_direct_request(
&params.destination_path,
CopyOptions {
recursive: params.recursive,
exclusive: params.exclusive,
},
/*sandbox*/ None,
)
+88 -4
View File
@@ -161,6 +161,15 @@ impl LocalFileSystem {
file_system.get_metadata(path, sandbox).await
}
async fn get_symlink_metadata(
&self,
path: &PathUri,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<FileMetadata> {
let (file_system, sandbox) = self.file_system_for(sandbox)?;
file_system.get_symlink_metadata(path, sandbox).await
}
async fn read_directory(
&self,
path: &PathUri,
@@ -247,6 +256,14 @@ impl ExecutorFileSystem for LocalFileSystem {
Box::pin(LocalFileSystem::get_metadata(self, path, sandbox))
}
fn get_symlink_metadata<'a>(
&'a self,
path: &'a PathUri,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
Box::pin(LocalFileSystem::get_symlink_metadata(self, path, sandbox))
}
fn read_directory<'a>(
&'a self,
path: &'a PathUri,
@@ -355,6 +372,17 @@ impl UnsandboxedFileSystem {
self.file_system.get_metadata(path, /*sandbox*/ None).await
}
async fn get_symlink_metadata(
&self,
path: &PathUri,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<FileMetadata> {
reject_platform_sandbox_context(sandbox)?;
self.file_system
.get_symlink_metadata(path, /*sandbox*/ None)
.await
}
async fn read_directory(
&self,
path: &PathUri,
@@ -452,6 +480,16 @@ impl ExecutorFileSystem for UnsandboxedFileSystem {
Box::pin(UnsandboxedFileSystem::get_metadata(self, path, sandbox))
}
fn get_symlink_metadata<'a>(
&'a self,
path: &'a PathUri,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
Box::pin(UnsandboxedFileSystem::get_symlink_metadata(
self, path, sandbox,
))
}
fn read_directory<'a>(
&'a self,
path: &'a PathUri,
@@ -572,11 +610,32 @@ impl DirectFileSystem {
&self,
path: &PathUri,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<FileMetadata> {
self.get_metadata_impl(path, sandbox, true).await
}
async fn get_symlink_metadata(
&self,
path: &PathUri,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<FileMetadata> {
self.get_metadata_impl(path, sandbox, false).await
}
async fn get_metadata_impl(
&self,
path: &PathUri,
sandbox: Option<&FileSystemSandboxContext>,
follow_symlinks: bool,
) -> FileSystemResult<FileMetadata> {
reject_sandbox_context(sandbox)?;
let path = path.to_abs_path()?;
let metadata = tokio::fs::metadata(path.as_path()).await?;
let symlink_metadata = tokio::fs::symlink_metadata(path.as_path()).await?;
let metadata = if follow_symlinks {
tokio::fs::metadata(path.as_path()).await?
} else {
symlink_metadata.clone()
};
Ok(FileMetadata {
is_directory: metadata.is_dir(),
is_file: metadata.is_file(),
@@ -597,13 +656,20 @@ impl DirectFileSystem {
let mut entries = Vec::new();
let mut read_dir = tokio::fs::read_dir(path.as_path()).await?;
while let Some(entry) = read_dir.next_entry().await? {
let Ok(metadata) = tokio::fs::metadata(entry.path()).await else {
continue;
let symlink_metadata = entry.metadata().await?;
let is_symlink = symlink_metadata.file_type().is_symlink();
let metadata = if is_symlink {
tokio::fs::metadata(entry.path())
.await
.unwrap_or_else(|_| symlink_metadata.clone())
} else {
symlink_metadata
};
entries.push(ReadDirectoryEntry {
file_name: entry.file_name().to_string_lossy().into_owned(),
is_directory: metadata.is_dir(),
is_file: metadata.is_file(),
is_symlink,
});
}
Ok(entries)
@@ -676,7 +742,17 @@ impl DirectFileSystem {
}
if file_type.is_file() {
std::fs::copy(source_path.as_path(), destination_path.as_path())?;
if options.exclusive {
let mut source = std::fs::File::open(source_path.as_path())?;
let mut destination = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(destination_path.as_path())?;
std::io::copy(&mut source, &mut destination)?;
std::fs::set_permissions(destination_path.as_path(), metadata.permissions())?;
} else {
std::fs::copy(source_path.as_path(), destination_path.as_path())?;
}
return Ok(());
}
@@ -743,6 +819,14 @@ impl ExecutorFileSystem for DirectFileSystem {
Box::pin(DirectFileSystem::get_metadata(self, path, sandbox))
}
fn get_symlink_metadata<'a>(
&'a self,
path: &'a PathUri,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
Box::pin(DirectFileSystem::get_symlink_metadata(self, path, sandbox))
}
fn read_directory<'a>(
&'a self,
path: &'a PathUri,
+3
View File
@@ -280,6 +280,7 @@ pub struct FsCreateDirectoryResponse {}
#[serde(rename_all = "camelCase")]
pub struct FsGetMetadataParams {
pub path: PathUri,
pub follow_symlinks: bool,
pub sandbox: Option<FileSystemSandboxContext>,
}
@@ -320,6 +321,7 @@ pub struct FsReadDirectoryEntry {
pub file_name: String,
pub is_directory: bool,
pub is_file: bool,
pub is_symlink: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -347,6 +349,7 @@ pub struct FsCopyParams {
pub source_path: PathUri,
pub destination_path: PathUri,
pub recursive: bool,
pub exclusive: bool,
pub sandbox: Option<FileSystemSandboxContext>,
}
@@ -27,6 +27,7 @@ use crate::protocol::FsWriteFileParams;
const INVALID_REQUEST_ERROR_CODE: i64 = -32600;
const NOT_FOUND_ERROR_CODE: i64 = -32004;
const ALREADY_EXISTS_ERROR_CODE: i64 = -32005;
#[path = "remote_file_stream.rs"]
mod file_stream;
@@ -138,12 +139,32 @@ impl RemoteFileSystem {
&self,
path: &PathUri,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<FileMetadata> {
self.get_metadata_with_follow_symlinks(path, sandbox, true)
.await
}
async fn get_symlink_metadata(
&self,
path: &PathUri,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<FileMetadata> {
self.get_metadata_with_follow_symlinks(path, sandbox, false)
.await
}
async fn get_metadata_with_follow_symlinks(
&self,
path: &PathUri,
sandbox: Option<&FileSystemSandboxContext>,
follow_symlinks: bool,
) -> FileSystemResult<FileMetadata> {
trace!("remote fs get_metadata");
let client = self.client.get().await.map_err(map_remote_error)?;
let response = client
.fs_get_metadata(FsGetMetadataParams {
path: path.clone(),
follow_symlinks,
sandbox: remote_sandbox_context(sandbox),
})
.await
@@ -179,6 +200,7 @@ impl RemoteFileSystem {
file_name: entry.file_name,
is_directory: entry.is_directory,
is_file: entry.is_file,
is_symlink: entry.is_symlink,
})
.collect())
}
@@ -217,6 +239,7 @@ impl RemoteFileSystem {
source_path: source_path.clone(),
destination_path: destination_path.clone(),
recursive: options.recursive,
exclusive: options.exclusive,
sandbox: remote_sandbox_context(sandbox),
})
.await
@@ -278,6 +301,14 @@ impl ExecutorFileSystem for RemoteFileSystem {
Box::pin(RemoteFileSystem::get_metadata(self, path, sandbox))
}
fn get_symlink_metadata<'a>(
&'a self,
path: &'a PathUri,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
Box::pin(RemoteFileSystem::get_symlink_metadata(self, path, sandbox))
}
fn read_directory<'a>(
&'a self,
path: &'a PathUri,
@@ -325,6 +356,9 @@ fn map_remote_error(error: ExecServerError) -> io::Error {
ExecServerError::Server { code, message } if code == NOT_FOUND_ERROR_CODE => {
io::Error::new(io::ErrorKind::NotFound, message)
}
ExecServerError::Server { code, message } if code == ALREADY_EXISTS_ERROR_CODE => {
io::Error::new(io::ErrorKind::AlreadyExists, message)
}
ExecServerError::Server { code, message } if code == INVALID_REQUEST_ERROR_CODE => {
io::Error::new(io::ErrorKind::InvalidInput, message)
}
+9
View File
@@ -27,6 +27,7 @@ use crate::connection::JsonRpcConnectionEvent;
use crate::connection::JsonRpcTransport;
pub(crate) const SESSION_ALREADY_ATTACHED_ERROR_CODE: i64 = -32010;
pub(crate) const ALREADY_EXISTS_ERROR_CODE: i64 = -32005;
#[derive(Debug)]
pub(crate) enum RpcCallError {
@@ -464,6 +465,14 @@ pub(crate) fn not_found(message: String) -> JSONRPCErrorError {
}
}
pub(crate) fn already_exists(message: String) -> JSONRPCErrorError {
JSONRPCErrorError {
code: ALREADY_EXISTS_ERROR_CODE,
data: None,
message,
}
}
pub(crate) fn internal_error(message: String) -> JSONRPCErrorError {
JSONRPCErrorError {
code: -32603,
@@ -147,6 +147,25 @@ impl SandboxedFileSystem {
&self,
path: &PathUri,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<FileMetadata> {
self.get_metadata_with_follow_symlinks(path, sandbox, true)
.await
}
async fn get_symlink_metadata(
&self,
path: &PathUri,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<FileMetadata> {
self.get_metadata_with_follow_symlinks(path, sandbox, false)
.await
}
async fn get_metadata_with_follow_symlinks(
&self,
path: &PathUri,
sandbox: Option<&FileSystemSandboxContext>,
follow_symlinks: bool,
) -> FileSystemResult<FileMetadata> {
let sandbox = require_platform_sandbox(sandbox)?;
validate_native_path(path)?;
@@ -155,6 +174,7 @@ impl SandboxedFileSystem {
sandbox,
FsHelperRequest::GetMetadata(FsGetMetadataParams {
path: path.clone(),
follow_symlinks,
sandbox: None,
}),
)
@@ -196,6 +216,7 @@ impl SandboxedFileSystem {
file_name: entry.file_name,
is_directory: entry.is_directory,
is_file: entry.is_file,
is_symlink: entry.is_symlink,
})
.collect())
}
@@ -239,6 +260,7 @@ impl SandboxedFileSystem {
source_path: source_path.clone(),
destination_path: destination_path.clone(),
recursive: options.recursive,
exclusive: options.exclusive,
sandbox: None,
}),
)
@@ -309,6 +331,16 @@ impl ExecutorFileSystem for SandboxedFileSystem {
Box::pin(SandboxedFileSystem::get_metadata(self, path, sandbox))
}
fn get_symlink_metadata<'a>(
&'a self,
path: &'a PathUri,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
Box::pin(SandboxedFileSystem::get_symlink_metadata(
self, path, sandbox,
))
}
fn read_directory<'a>(
&'a self,
path: &'a PathUri,
@@ -35,6 +35,7 @@ use crate::protocol::FsRemoveParams;
use crate::protocol::FsRemoveResponse;
use crate::protocol::FsWriteFileParams;
use crate::protocol::FsWriteFileResponse;
use crate::rpc::already_exists;
use crate::rpc::internal_error;
use crate::rpc::invalid_request;
use crate::rpc::not_found;
@@ -152,11 +153,16 @@ impl FileSystemHandler {
&self,
params: FsGetMetadataParams,
) -> Result<FsGetMetadataResponse, JSONRPCErrorError> {
let metadata = self
.file_system
.get_metadata(&params.path, params.sandbox.as_ref())
.await
.map_err(map_fs_error)?;
let metadata = if params.follow_symlinks {
self.file_system
.get_metadata(&params.path, params.sandbox.as_ref())
.await
} else {
self.file_system
.get_symlink_metadata(&params.path, params.sandbox.as_ref())
.await
}
.map_err(map_fs_error)?;
Ok(FsGetMetadataResponse {
is_directory: metadata.is_directory,
is_file: metadata.is_file,
@@ -193,6 +199,7 @@ impl FileSystemHandler {
file_name: entry.file_name,
is_directory: entry.is_directory,
is_file: entry.is_file,
is_symlink: entry.is_symlink,
})
.collect();
Ok(FsReadDirectoryResponse { entries })
@@ -225,6 +232,7 @@ impl FileSystemHandler {
&params.destination_path,
CopyOptions {
recursive: params.recursive,
exclusive: params.exclusive,
},
params.sandbox.as_ref(),
)
@@ -246,6 +254,7 @@ fn validate_file_read_handle_id(handle_id: &str) -> Result<(), JSONRPCErrorError
fn map_fs_error(err: io::Error) -> JSONRPCErrorError {
match err.kind() {
io::ErrorKind::NotFound => not_found(err.to_string()),
io::ErrorKind::AlreadyExists => already_exists(err.to_string()),
io::ErrorKind::InvalidInput | io::ErrorKind::PermissionDenied => {
invalid_request(err.to_string())
}
@@ -273,7 +273,10 @@ async fn file_system_copy_copies_file(implementation: FileSystemImplementation)
.copy(
&PathUri::from_path(&source_file)?,
&PathUri::from_path(&copied_file)?,
CopyOptions { recursive: false },
CopyOptions {
recursive: false,
exclusive: false,
},
/*sandbox*/ None,
)
.await
@@ -283,6 +286,38 @@ async fn file_system_copy_copies_file(implementation: FileSystemImplementation)
Ok(())
}
#[test_case(FileSystemImplementation::Local ; "local")]
#[test_case(FileSystemImplementation::Remote ; "remote")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn file_system_copy_exclusive_preserves_existing_destination(
implementation: FileSystemImplementation,
) -> Result<()> {
let context = create_file_system_context(implementation).await?;
let file_system = context.file_system;
let tmp = TempDir::new()?;
let source_file = tmp.path().join("source.txt");
let destination_file = tmp.path().join("destination.txt");
std::fs::write(&source_file, "source")?;
std::fs::write(&destination_file, "destination")?;
let error = file_system
.copy(
&PathUri::from_path(&source_file)?,
&PathUri::from_path(&destination_file)?,
CopyOptions {
recursive: false,
exclusive: true,
},
/*sandbox*/ None,
)
.await
.expect_err("exclusive copy should reject an existing destination");
assert_eq!(error.kind(), std::io::ErrorKind::AlreadyExists);
assert_eq!(std::fs::read_to_string(destination_file)?, "destination");
Ok(())
}
#[test_case(FileSystemImplementation::Local ; "local")]
#[test_case(FileSystemImplementation::Remote ; "remote")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -304,7 +339,10 @@ async fn file_system_copy_copies_directory_recursively(
.copy(
&PathUri::from_path(&source_dir)?,
&PathUri::from_path(&copied_dir)?,
CopyOptions { recursive: true },
CopyOptions {
recursive: true,
exclusive: false,
},
/*sandbox*/ None,
)
.await
@@ -343,11 +381,13 @@ async fn file_system_read_directory_lists_entries(
file_name: "nested".to_string(),
is_directory: true,
is_file: false,
is_symlink: false,
},
ReadDirectoryEntry {
file_name: "root.txt".to_string(),
is_directory: false,
is_file: true,
is_symlink: false,
},
]
);
@@ -434,7 +474,10 @@ async fn file_system_copy_rejects_directory_without_recursive(
.copy(
&PathUri::from_path(&source_dir)?,
&PathUri::from_path(tmp.path().join("dest"))?,
CopyOptions { recursive: false },
CopyOptions {
recursive: false,
exclusive: false,
},
/*sandbox*/ None,
)
.await;
@@ -619,7 +662,10 @@ async fn file_system_copy_rejects_copying_directory_into_descendant(
.copy(
&PathUri::from_path(&source_dir)?,
&PathUri::from_path(source_dir.join("nested").join("copy"))?,
CopyOptions { recursive: true },
CopyOptions {
recursive: true,
exclusive: false,
},
/*sandbox*/ None,
)
.await;
+68 -6
View File
@@ -237,6 +237,22 @@ async fn file_system_get_metadata_reports_symlink_targets(
);
assert!(symlink_metadata.modified_at_ms > 0);
let link_metadata = file_system
.get_symlink_metadata(&PathUri::from_path(&symlink_path)?, /*sandbox*/ None)
.await
.with_context(|| format!("mode={implementation}"))?;
assert_eq!(
link_metadata,
FileMetadata {
is_directory: false,
is_file: false,
is_symlink: true,
size: std::fs::symlink_metadata(&symlink_path)?.len(),
created_at_ms: link_metadata.created_at_ms,
modified_at_ms: link_metadata.modified_at_ms,
}
);
let dir_path = tmp.path().join("notes");
std::fs::create_dir(&dir_path)?;
let dir_symlink_path = tmp.path().join("notes-link");
@@ -263,6 +279,34 @@ async fn file_system_get_metadata_reports_symlink_targets(
Ok(())
}
#[test_case(FileSystemImplementation::Local ; "local")]
#[test_case(FileSystemImplementation::Remote ; "remote")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn file_system_read_directory_reports_symlinks(
implementation: FileSystemImplementation,
) -> Result<()> {
let context = create_file_system_context(implementation).await?;
let file_system = context.file_system;
let tmp = TempDir::new()?;
let target_path = tmp.path().join("target");
std::fs::create_dir(&target_path)?;
symlink(&target_path, tmp.path().join("target-link"))?;
let entries = file_system
.read_directory(&PathUri::from_path(tmp.path())?, /*sandbox*/ None)
.await
.with_context(|| format!("mode={implementation}"))?;
let entry = entries
.into_iter()
.find(|entry| entry.file_name == "target-link")
.context("missing symlink entry")?;
assert_eq!(entry.is_directory, true);
assert_eq!(entry.is_file, false);
assert_eq!(entry.is_symlink, true);
Ok(())
}
#[test_case(FileSystemImplementation::Local ; "local")]
#[test_case(FileSystemImplementation::Remote ; "remote")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -564,7 +608,10 @@ async fn file_system_copy_rejects_symlink_escape_destination(
.copy(
&PathUri::from_path(allowed_dir.join("source.txt"))?,
&PathUri::from_path(&requested_destination)?,
CopyOptions { recursive: false },
CopyOptions {
recursive: false,
exclusive: false,
},
Some(&sandbox),
)
.await
@@ -642,7 +689,10 @@ async fn file_system_copy_preserves_symlink_source(
.copy(
&PathUri::from_path(&source_symlink)?,
&PathUri::from_path(&copied_symlink)?,
CopyOptions { recursive: false },
CopyOptions {
recursive: false,
exclusive: false,
},
Some(&sandbox),
)
.await
@@ -720,7 +770,10 @@ async fn file_system_copy_rejects_symlink_escape_source(
.copy(
&PathUri::from_path(&requested_source)?,
&PathUri::from_path(&requested_destination)?,
CopyOptions { recursive: false },
CopyOptions {
recursive: false,
exclusive: false,
},
Some(&sandbox),
)
.await
@@ -754,7 +807,10 @@ async fn file_system_copy_preserves_symlinks_in_recursive_copy(
.copy(
&PathUri::from_path(&source_dir)?,
&PathUri::from_path(&copied_dir)?,
CopyOptions { recursive: true },
CopyOptions {
recursive: true,
exclusive: false,
},
/*sandbox*/ None,
)
.await
@@ -800,7 +856,10 @@ async fn file_system_copy_ignores_unknown_special_files_in_recursive_copy(
.copy(
&PathUri::from_path(&source_dir)?,
&PathUri::from_path(&copied_dir)?,
CopyOptions { recursive: true },
CopyOptions {
recursive: true,
exclusive: false,
},
/*sandbox*/ None,
)
.await
@@ -839,7 +898,10 @@ async fn file_system_copy_rejects_standalone_fifo_source(
.copy(
&PathUri::from_path(&fifo_path)?,
&PathUri::from_path(tmp.path().join("copied"))?,
CopyOptions { recursive: false },
CopyOptions {
recursive: false,
exclusive: false,
},
/*sandbox*/ None,
)
.await;
+10
View File
@@ -36,6 +36,7 @@ pub struct RemoveOptions {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CopyOptions {
pub recursive: bool,
pub exclusive: bool,
}
#[derive(Clone, Debug, Eq, PartialEq)]
@@ -54,6 +55,7 @@ pub struct ReadDirectoryEntry {
pub file_name: String,
pub is_directory: bool,
pub is_file: bool,
pub is_symlink: bool,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
@@ -243,6 +245,14 @@ pub trait ExecutorFileSystem: Send + Sync {
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata>;
fn get_symlink_metadata<'a>(
&'a self,
path: &'a PathUri,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
self.get_metadata(path, sandbox)
}
fn read_directory<'a>(
&'a self,
path: &'a PathUri,