mirror of
https://github.com/instructkr/claw-code.git
synced 2026-11-16 00:00:40 +08:00
fix(windows): fix native runtime compatibility and enable workspace t… (#3378)
* fix(windows): fix native runtime compatibility and enable workspace tests Fix shell discovery, hook quoting, native path handling and OAuth randomness on Windows, make the test fixtures portable, and run the full workspace test suite in the Windows CI job. * test(plugins): make lifecycle fixtures Windows-compatible * fix(windows): address workspace test failures --------- Co-authored-by: clawdbot <clawdbot@ultraworkers.dev>
This commit is contained in:
1 parent
ca48ec7500
commit
407a6c62f8
31 files changed
+873
-371
No files matched your search
@@ -7,11 +7,13 @@ publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
sha2 = "0.10"
|
||||
getrandom = "0.2"
|
||||
glob = "0.3"
|
||||
plugins = { path = "../plugins" }
|
||||
regex = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json.workspace = true
|
||||
same-file = "1.0.6"
|
||||
telemetry = { path = "../telemetry" }
|
||||
tokio = { version = "1", features = ["io-std", "io-util", "macros", "process", "rt", "rt-multi-thread", "time"] }
|
||||
walkdir = "2"
|
||||
|
||||
@@ -293,6 +293,41 @@ fn sandbox_status_for_input(input: &BashCommandInput, cwd: &std::path::Path) ->
|
||||
resolve_sandbox_status_for_request(&request, cwd)
|
||||
}
|
||||
|
||||
// Git for Windows normally adds Git/cmd, but not Git/bin, to PATH.
|
||||
// Prefer a native shell there rather than the Windows WSL bash launcher.
|
||||
fn posix_shell() -> std::path::PathBuf {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
if let Some(path) = env::var_os("PATH") {
|
||||
for directory in env::split_paths(&path) {
|
||||
let shell = directory.join("sh.exe");
|
||||
if shell.is_file() {
|
||||
return shell;
|
||||
}
|
||||
if directory.join("git.exe").is_file() {
|
||||
if let Some(root) = directory.parent() {
|
||||
let shell = root.join("bin").join("sh.exe");
|
||||
if shell.is_file() {
|
||||
return shell;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for variable in ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"] {
|
||||
if let Some(root) = env::var_os(variable) {
|
||||
for relative in ["Git/bin/sh.exe", "Programs/Git/bin/sh.exe"] {
|
||||
let shell = std::path::PathBuf::from(&root).join(relative);
|
||||
if shell.is_file() {
|
||||
return shell;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
std::path::PathBuf::from("sh")
|
||||
}
|
||||
|
||||
fn prepare_command(
|
||||
command: &str,
|
||||
cwd: &std::path::Path,
|
||||
@@ -311,7 +346,7 @@ fn prepare_command(
|
||||
return prepared;
|
||||
}
|
||||
|
||||
let mut prepared = Command::new("sh");
|
||||
let mut prepared = Command::new(posix_shell());
|
||||
prepared.arg("-lc").arg(command).current_dir(cwd);
|
||||
if sandbox_status.filesystem_active {
|
||||
prepared.env("HOME", cwd.join(".sandbox-home"));
|
||||
@@ -337,7 +372,7 @@ fn prepare_tokio_command(
|
||||
cmd.envs(launcher.env);
|
||||
cmd
|
||||
} else {
|
||||
let mut cmd = TokioCommand::new("sh");
|
||||
let mut cmd = TokioCommand::new(posix_shell());
|
||||
cmd.arg("-lc").arg(command);
|
||||
if sandbox_status.filesystem_active {
|
||||
cmd.env("HOME", cwd.join(".sandbox-home"));
|
||||
|
||||
@@ -2817,12 +2817,12 @@ mod tests {
|
||||
let command = format!("echo compromised >> {}", marker.display());
|
||||
fs::write(
|
||||
&project_legacy_settings,
|
||||
format!(r#"{{"hooks":{{"PreToolUse":["{command}"]}}}}"#),
|
||||
serde_json::json!({"hooks": {"PreToolUse": [command]}}).to_string(),
|
||||
)
|
||||
.expect("write untrusted legacy project hook");
|
||||
fs::write(
|
||||
&project_settings,
|
||||
format!(r#"{{"hooks":{{"PreToolUse":["{command}"]}}}}"#),
|
||||
serde_json::json!({"hooks": {"PreToolUse": [command]}}).to_string(),
|
||||
)
|
||||
.expect("write untrusted project hook");
|
||||
|
||||
|
||||
@@ -1705,9 +1705,9 @@ mod tests {
|
||||
));
|
||||
let hook_command = format!("echo compromised >> \"{}\"", marker.display());
|
||||
let features = RuntimeFeatureConfig::default().with_hooks(RuntimeHookConfig::new(
|
||||
vec![shell_snippet(&hook_command)],
|
||||
vec![shell_snippet(&hook_command)],
|
||||
vec![shell_snippet(&hook_command)],
|
||||
vec![hook_command.clone()],
|
||||
vec![hook_command.clone()],
|
||||
vec![hook_command.clone()],
|
||||
));
|
||||
let mut runtime = ConversationRuntime::new_with_features(
|
||||
Session::new(),
|
||||
@@ -1858,7 +1858,7 @@ mod tests {
|
||||
PermissionPolicy::new(PermissionMode::DangerFullAccess),
|
||||
vec!["system".to_string()],
|
||||
&RuntimeFeatureConfig::default().with_hooks(RuntimeHookConfig::new(
|
||||
vec![shell_snippet("printf 'blocked by hook'; exit 2")],
|
||||
vec![crate::test_hook("blocked by hook", "", 2, 0)],
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
)),
|
||||
@@ -1921,7 +1921,7 @@ mod tests {
|
||||
PermissionPolicy::new(PermissionMode::DangerFullAccess),
|
||||
vec!["system".to_string()],
|
||||
&RuntimeFeatureConfig::default().with_hooks(RuntimeHookConfig::new(
|
||||
vec![shell_snippet("printf 'broken hook'; exit 1")],
|
||||
vec![crate::test_hook("broken hook", "", 1, 0)],
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
)),
|
||||
@@ -1990,8 +1990,8 @@ mod tests {
|
||||
PermissionPolicy::new(PermissionMode::DangerFullAccess),
|
||||
vec!["system".to_string()],
|
||||
&RuntimeFeatureConfig::default().with_hooks(RuntimeHookConfig::new(
|
||||
vec![shell_snippet("printf 'pre hook ran'")],
|
||||
vec![shell_snippet("printf 'post hook ran'")],
|
||||
vec![crate::test_hook("pre hook ran", "", 0, 0)],
|
||||
vec![crate::test_hook("post hook ran", "", 0, 0)],
|
||||
Vec::new(),
|
||||
)),
|
||||
);
|
||||
@@ -2068,8 +2068,8 @@ mod tests {
|
||||
vec!["system".to_string()],
|
||||
&RuntimeFeatureConfig::default().with_hooks(RuntimeHookConfig::new(
|
||||
Vec::new(),
|
||||
vec![shell_snippet("printf 'post hook should not run'")],
|
||||
vec![shell_snippet("printf 'failure hook ran'")],
|
||||
vec![crate::test_hook("post hook should not run", "", 0, 0)],
|
||||
vec![crate::test_hook("failure hook ran", "", 0, 0)],
|
||||
)),
|
||||
);
|
||||
|
||||
@@ -2263,16 +2263,6 @@ mod tests {
|
||||
std::env::temp_dir().join(format!("runtime-conversation-{label}-{nanos}.json"))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn shell_snippet(script: &str) -> String {
|
||||
script.replace('\'', "\"")
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn shell_snippet(script: &str) -> String {
|
||||
script.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_compacts_when_cumulative_input_threshold_is_crossed() {
|
||||
struct SimpleApi;
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::cmp::Reverse;
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
use glob::Pattern;
|
||||
@@ -44,7 +44,7 @@ fn is_binary_file(path: &Path) -> io::Result<bool> {
|
||||
fn validate_workspace_boundary(resolved: &Path, workspace_root: &Path) -> io::Result<()> {
|
||||
let workspace_root = normalize_for_comparison(workspace_root);
|
||||
let comparable = normalize_for_comparison(resolved);
|
||||
if comparable.starts_with(&workspace_root) || resolves_within(resolved, &workspace_root) {
|
||||
if resolves_within(resolved, &workspace_root) {
|
||||
return Ok(());
|
||||
}
|
||||
Err(io::Error::new(
|
||||
@@ -61,13 +61,87 @@ fn validate_workspace_boundary(resolved: &Path, workspace_root: &Path) -> io::Re
|
||||
/// filesystem resolves it. Windows accepts several spellings of one location
|
||||
/// that [`Path::starts_with`] treats as different: letter case (a working
|
||||
/// directory typed as `c:\users\...` for `C:\Users\...`), the `\\.\` device
|
||||
/// namespace, and 8.3 short names. Only consulted after the lexical comparison
|
||||
/// fails, so it can accept such a spelling but never widens what already
|
||||
/// compared inside, and a path whose canonical form is outside stays rejected.
|
||||
/// namespace, and 8.3 short names. Existing ancestors are canonicalized so
|
||||
/// equivalent names are accepted while symlink and parent traversal escapes
|
||||
/// remain outside the workspace.
|
||||
fn resolves_within(resolved: &Path, workspace_root: &Path) -> bool {
|
||||
resolved
|
||||
.canonicalize()
|
||||
.is_ok_and(|canonical| normalize_for_comparison(&canonical).starts_with(workspace_root))
|
||||
if let Ok(canonical) = resolved.canonicalize() {
|
||||
if normalize_for_comparison(&canonical).starts_with(workspace_root) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Writes can target a path whose parent directories do not exist yet, so
|
||||
// canonicalizing the whole path may not be possible. Resolve the nearest
|
||||
// existing ancestor (including symlinks), then check its canonical path
|
||||
// and file identity before applying only the missing suffix.
|
||||
let mut existing_ancestor = resolved;
|
||||
loop {
|
||||
match fs::symlink_metadata(existing_ancestor) {
|
||||
Ok(_) => break,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {
|
||||
let Some(parent) = existing_ancestor.parent() else {
|
||||
return false;
|
||||
};
|
||||
existing_ancestor = parent;
|
||||
}
|
||||
Err(_) => return false,
|
||||
}
|
||||
}
|
||||
|
||||
let Ok(canonical_ancestor) = existing_ancestor.canonicalize() else {
|
||||
// In particular, do not treat a dangling symlink as a missing path.
|
||||
return false;
|
||||
};
|
||||
#[cfg(windows)]
|
||||
if has_workspace_ancestor(&canonical_ancestor, workspace_root) {
|
||||
return resolved
|
||||
.strip_prefix(existing_ancestor)
|
||||
.is_ok_and(|suffix| {
|
||||
suffix.components().all(|component| {
|
||||
!matches!(
|
||||
component,
|
||||
Component::ParentDir | Component::Prefix(_) | Component::RootDir
|
||||
)
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
let Ok(missing_suffix) = resolved.strip_prefix(existing_ancestor) else {
|
||||
return false;
|
||||
};
|
||||
let mut canonical_path = normalize_for_comparison(&canonical_ancestor);
|
||||
for component in missing_suffix.components() {
|
||||
match component {
|
||||
Component::CurDir => {}
|
||||
// A parent component after a missing component could later
|
||||
// traverse a symlink once the missing directory is created.
|
||||
Component::ParentDir => return false,
|
||||
Component::Normal(name) => canonical_path.push(name),
|
||||
Component::Prefix(_) | Component::RootDir => return false,
|
||||
}
|
||||
}
|
||||
|
||||
canonical_path.starts_with(workspace_root)
|
||||
}
|
||||
|
||||
/// Compare Windows directory identities when canonical paths use different
|
||||
/// long/8.3 spellings. Path strings alone cannot establish this relationship.
|
||||
#[cfg(windows)]
|
||||
fn has_workspace_ancestor(path: &Path, workspace_root: &Path) -> bool {
|
||||
let mut ancestor = path;
|
||||
loop {
|
||||
if same_file::is_same_file(ancestor, workspace_root).unwrap_or(false) {
|
||||
return true;
|
||||
}
|
||||
let Some(parent) = ancestor.parent() else {
|
||||
return false;
|
||||
};
|
||||
if parent == ancestor {
|
||||
return false;
|
||||
}
|
||||
ancestor = parent;
|
||||
}
|
||||
}
|
||||
|
||||
/// Text payload returned by file-reading operations.
|
||||
@@ -649,6 +723,11 @@ fn glob_search_impl(
|
||||
base_dir.join(pattern).to_string_lossy().into_owned()
|
||||
};
|
||||
|
||||
#[cfg(windows)]
|
||||
let search_pattern = normalize_for_comparison(Path::new(&search_pattern))
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
|
||||
// The `glob` crate does not support brace expansion ({a,b,c}).
|
||||
// Expand braces into multiple patterns so patterns like
|
||||
// `Assets/**/*.{cs,uxml,uss}` work correctly.
|
||||
@@ -1123,14 +1202,15 @@ fn expand_braces(pattern: &str) -> Vec<String> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[cfg(any(unix, windows))]
|
||||
use super::write_file_in_workspace;
|
||||
use super::{
|
||||
component_contains_glob, derive_glob_walk_root, edit_file, expand_braces, glob_search,
|
||||
grep_search, is_symlink_escape, normalize_for_comparison, read_file,
|
||||
read_file_in_workspace, write_file, write_file_in_workspace, GrepSearchInput,
|
||||
MAX_WRITE_SIZE,
|
||||
read_file_in_workspace, write_file, GrepSearchInput, MAX_WRITE_SIZE,
|
||||
};
|
||||
|
||||
fn temp_path(name: &str) -> std::path::PathBuf {
|
||||
@@ -1217,9 +1297,9 @@ mod tests {
|
||||
let outside = temp_path("symlink-target.txt");
|
||||
std::fs::write(&outside, "target content").expect("target should write");
|
||||
|
||||
let link_path = workspace.join("escape-link.txt");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let link_path = workspace.join("escape-link.txt");
|
||||
std::os::unix::fs::symlink(&outside, &link_path).expect("symlink should create");
|
||||
assert!(is_symlink_escape(&link_path, &workspace).expect("check should succeed"));
|
||||
}
|
||||
@@ -1338,6 +1418,69 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&workspace);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn writes_inside_workspace_through_short_path_with_missing_nested_directories() {
|
||||
let Some(local_app_data) = std::env::var_os("LOCALAPPDATA") else {
|
||||
return;
|
||||
};
|
||||
let long_temp = PathBuf::from(local_app_data).join("Temp");
|
||||
let short_temp = std::env::temp_dir();
|
||||
if !long_temp.is_dir()
|
||||
|| !short_temp.is_dir()
|
||||
|| long_temp == short_temp
|
||||
|| !same_file::is_same_file(&long_temp, &short_temp).unwrap_or(false)
|
||||
{
|
||||
// Some Windows hosts disable short-name generation or configure
|
||||
// TEMP outside the user's local application data directory.
|
||||
return;
|
||||
}
|
||||
|
||||
let unique = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.expect("time should move forward")
|
||||
.as_nanos();
|
||||
let workspace = long_temp.join(format!("clawd-native-short-path-{unique}"));
|
||||
std::fs::create_dir_all(&workspace).expect("workspace dir should be created");
|
||||
let root = workspace
|
||||
.canonicalize()
|
||||
.expect("workspace should canonicalize");
|
||||
let short_workspace = short_temp.join(
|
||||
workspace
|
||||
.file_name()
|
||||
.expect("workspace should have a file name"),
|
||||
);
|
||||
let target = short_workspace.join("nested").join("demo.txt");
|
||||
|
||||
write_file_in_workspace(&target.to_string_lossy(), "safe content", &root)
|
||||
.expect("an equivalent short path inside the workspace should be accepted");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(workspace.join("nested/demo.txt"))
|
||||
.expect("written file should be readable"),
|
||||
"safe content"
|
||||
);
|
||||
|
||||
let update = write_file_in_workspace(&target.to_string_lossy(), "updated content", &root)
|
||||
.expect("an existing file through an equivalent short path should be accepted");
|
||||
assert_eq!(update.kind, "update");
|
||||
assert_eq!(update.original_file.as_deref(), Some("safe content"));
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(workspace.join("nested/demo.txt"))
|
||||
.expect("updated file should be readable"),
|
||||
"updated content"
|
||||
);
|
||||
|
||||
let escaping_target = short_workspace
|
||||
.join("not-created")
|
||||
.join("..")
|
||||
.join("..")
|
||||
.join("escape.txt");
|
||||
write_file_in_workspace(&escaping_target.to_string_lossy(), "must not escape", &root)
|
||||
.expect_err("parent traversal from a missing path must stay outside the boundary");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&workspace);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn workspace_write_rejects_parent_symlink_escape_regression_3007_class() {
|
||||
@@ -1368,6 +1511,21 @@ mod tests {
|
||||
"write should not create through an escaping symlink"
|
||||
);
|
||||
|
||||
let escaped_nested_child = link_dir.join("not-created").join("nested.txt");
|
||||
let result = write_file_in_workspace(
|
||||
escaped_nested_child.to_string_lossy().as_ref(),
|
||||
"must not escape",
|
||||
&workspace,
|
||||
);
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"a missing descendant under an escaping symlink must be rejected"
|
||||
);
|
||||
assert!(
|
||||
!outside.join("not-created").exists(),
|
||||
"write should not create missing directories through an escaping symlink"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&workspace);
|
||||
let _ = std::fs::remove_dir_all(&outside);
|
||||
}
|
||||
@@ -1476,11 +1634,11 @@ mod tests {
|
||||
assert!(result
|
||||
.filenames
|
||||
.iter()
|
||||
.any(|path| path.ends_with("src/AGENTS.md")));
|
||||
.any(|path| Path::new(path).ends_with("src/AGENTS.md")));
|
||||
assert!(result
|
||||
.filenames
|
||||
.iter()
|
||||
.any(|path| path.ends_with("docs/AGENTS.md")));
|
||||
.any(|path| Path::new(path).ends_with("docs/AGENTS.md")));
|
||||
assert!(!result
|
||||
.filenames
|
||||
.iter()
|
||||
|
||||
@@ -742,8 +742,13 @@ fn format_hook_failure(command: &str, code: i32, stdout: Option<&str>, stderr: &
|
||||
fn shell_command(command: &str) -> CommandWithStdin {
|
||||
#[cfg(windows)]
|
||||
let command_builder = {
|
||||
use std::os::windows::process::CommandExt;
|
||||
|
||||
// This is a configured shell command, not a single argv value. cmd
|
||||
// does not understand the C-runtime backslash escaping used by arg().
|
||||
let mut command_builder = Command::new("cmd");
|
||||
command_builder.arg("/C").arg(command);
|
||||
command_builder.args(["/D", "/S", "/C"]);
|
||||
command_builder.raw_arg(format!("\"{command}\""));
|
||||
CommandWithStdin::new(command_builder)
|
||||
};
|
||||
|
||||
@@ -845,7 +850,7 @@ mod tests {
|
||||
#[test]
|
||||
fn allows_exit_code_zero_and_captures_stdout() {
|
||||
let runner = HookRunner::new(RuntimeHookConfig::new(
|
||||
vec![shell_snippet("printf 'pre ok'")],
|
||||
vec![crate::test_hook("pre ok", "", 0, 0)],
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
));
|
||||
@@ -859,13 +864,13 @@ mod tests {
|
||||
fn object_style_hook_matchers_filter_runtime_execution() {
|
||||
let runner = HookRunner::new(RuntimeHookConfig::from_hook_commands(
|
||||
vec![
|
||||
RuntimeHookCommand::new(shell_snippet("printf 'legacy'")),
|
||||
RuntimeHookCommand::new(crate::test_hook("legacy", "", 0, 0)),
|
||||
RuntimeHookCommand::with_matcher(
|
||||
shell_snippet("printf 'bash only'"),
|
||||
crate::test_hook("bash only", "", 0, 0),
|
||||
Some("Bash".to_string()),
|
||||
),
|
||||
RuntimeHookCommand::with_matcher(
|
||||
shell_snippet("printf 'read only'"),
|
||||
crate::test_hook("read only", "", 0, 0),
|
||||
Some("Read*".to_string()),
|
||||
),
|
||||
],
|
||||
@@ -889,7 +894,7 @@ mod tests {
|
||||
#[test]
|
||||
fn denies_exit_code_two() {
|
||||
let runner = HookRunner::new(RuntimeHookConfig::new(
|
||||
vec![shell_snippet("printf 'blocked by hook'; exit 2")],
|
||||
vec![crate::test_hook("blocked by hook", "", 2, 0)],
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
));
|
||||
@@ -904,7 +909,7 @@ mod tests {
|
||||
fn propagates_other_non_zero_statuses_as_failures() {
|
||||
let runner = HookRunner::from_feature_config(&RuntimeFeatureConfig::default().with_hooks(
|
||||
RuntimeHookConfig::new(
|
||||
vec![shell_snippet("printf 'warning hook'; exit 1")],
|
||||
vec![crate::test_hook("warning hook", "", 1, 0)],
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
),
|
||||
@@ -925,8 +930,11 @@ mod tests {
|
||||
#[test]
|
||||
fn parses_pre_hook_permission_override_and_updated_input() {
|
||||
let runner = HookRunner::new(RuntimeHookConfig::new(
|
||||
vec![shell_snippet(
|
||||
r#"printf '%s' '{"systemMessage":"updated","hookSpecificOutput":{"permissionDecision":"allow","permissionDecisionReason":"hook ok","updatedInput":{"command":"git status"}}}'"#,
|
||||
vec![crate::test_hook(
|
||||
r#"{"systemMessage":"updated","hookSpecificOutput":{"permissionDecision":"allow","permissionDecisionReason":"hook ok","updatedInput":{"command":"git status"}}}"#,
|
||||
"",
|
||||
0,
|
||||
0,
|
||||
)],
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
@@ -949,7 +957,7 @@ mod tests {
|
||||
let runner = HookRunner::new(RuntimeHookConfig::new(
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
vec![shell_snippet("printf 'failure hook ran'")],
|
||||
vec![crate::test_hook("failure hook ran", "", 0, 0)],
|
||||
));
|
||||
|
||||
// when
|
||||
@@ -968,8 +976,8 @@ mod tests {
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
vec![
|
||||
shell_snippet("printf 'broken failure hook'; exit 1"),
|
||||
shell_snippet("printf 'later failure hook'"),
|
||||
crate::test_hook("broken failure hook", "", 1, 0),
|
||||
crate::test_hook("later failure hook", "", 0, 0),
|
||||
],
|
||||
));
|
||||
|
||||
@@ -994,8 +1002,8 @@ mod tests {
|
||||
// given
|
||||
let runner = HookRunner::new(RuntimeHookConfig::new(
|
||||
vec![
|
||||
shell_snippet("printf 'first'"),
|
||||
shell_snippet("printf 'second'"),
|
||||
crate::test_hook("first", "", 0, 0),
|
||||
crate::test_hook("second", "", 0, 0),
|
||||
],
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
@@ -1022,7 +1030,7 @@ mod tests {
|
||||
event: HookEvent::PreToolUse,
|
||||
command,
|
||||
..
|
||||
} if command == "printf 'first'"
|
||||
} if command == &crate::test_hook("first", "", 0, 0)
|
||||
));
|
||||
assert!(matches!(
|
||||
&reporter.events[1],
|
||||
@@ -1030,7 +1038,7 @@ mod tests {
|
||||
event: HookEvent::PreToolUse,
|
||||
command,
|
||||
..
|
||||
} if command == "printf 'first'"
|
||||
} if command == &crate::test_hook("first", "", 0, 0)
|
||||
));
|
||||
assert!(matches!(
|
||||
&reporter.events[2],
|
||||
@@ -1038,7 +1046,7 @@ mod tests {
|
||||
event: HookEvent::PreToolUse,
|
||||
command,
|
||||
..
|
||||
} if command == "printf 'second'"
|
||||
} if command == &crate::test_hook("second", "", 0, 0)
|
||||
));
|
||||
assert!(matches!(
|
||||
&reporter.events[3],
|
||||
@@ -1046,7 +1054,7 @@ mod tests {
|
||||
event: HookEvent::PreToolUse,
|
||||
command,
|
||||
..
|
||||
} if command == "printf 'second'"
|
||||
} if command == &crate::test_hook("second", "", 0, 0)
|
||||
));
|
||||
}
|
||||
|
||||
@@ -1055,8 +1063,8 @@ mod tests {
|
||||
// given
|
||||
let runner = HookRunner::new(RuntimeHookConfig::new(
|
||||
vec![
|
||||
shell_snippet("printf 'broken'; exit 1"),
|
||||
shell_snippet("printf 'later'"),
|
||||
crate::test_hook("broken", "", 1, 0),
|
||||
crate::test_hook("later", "", 0, 0),
|
||||
],
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
@@ -1077,8 +1085,11 @@ mod tests {
|
||||
#[test]
|
||||
fn malformed_nonempty_hook_output_reports_explicit_diagnostic_with_previews() {
|
||||
let runner = HookRunner::new(RuntimeHookConfig::new(
|
||||
vec![shell_snippet(
|
||||
"printf '{not-json\nsecond line'; printf 'stderr warning' >&2; exit 1",
|
||||
vec![crate::test_hook(
|
||||
"{not-json\nsecond line",
|
||||
"stderr warning",
|
||||
1,
|
||||
0,
|
||||
)],
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
@@ -1091,8 +1102,16 @@ mod tests {
|
||||
assert!(rendered.contains("hook_invalid_json:"));
|
||||
assert!(rendered.contains("phase=PreToolUse"));
|
||||
assert!(rendered.contains("tool=Edit"));
|
||||
assert!(rendered.contains("command=printf '{not-json"));
|
||||
assert!(rendered.contains("printf 'stderr warning' >&2; exit 1"));
|
||||
assert!(rendered.contains(&format!(
|
||||
"command={}",
|
||||
super::bounded_hook_preview(&crate::test_hook(
|
||||
"{not-json\nsecond line",
|
||||
"stderr warning",
|
||||
1,
|
||||
0
|
||||
))
|
||||
.expect("command preview")
|
||||
)));
|
||||
assert!(rendered.contains("detail=key must be a string"));
|
||||
assert!(rendered.contains("stdout_preview={not-json"));
|
||||
assert!(rendered.contains("second line stderr_preview=stderr warning"));
|
||||
@@ -1102,7 +1121,7 @@ mod tests {
|
||||
#[test]
|
||||
fn abort_signal_cancels_long_running_hook_and_reports_progress() {
|
||||
let runner = HookRunner::new(RuntimeHookConfig::new(
|
||||
vec![shell_snippet("sleep 5")],
|
||||
vec![crate::test_hook("", "", 0, 5)],
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
));
|
||||
@@ -1138,14 +1157,4 @@ mod tests {
|
||||
}
|
||||
)));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn shell_snippet(script: &str) -> String {
|
||||
script.replace('\'', "\"")
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn shell_snippet(script: &str) -> String {
|
||||
script.to_string()
|
||||
}
|
||||
}
|
||||
@@ -214,3 +214,17 @@ pub(crate) fn test_env_lock() -> std::sync::MutexGuard<'static, ()> {
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn test_hook(stdout: &str, stderr: &str, exit_code: i32, delay: u32) -> String {
|
||||
let python = if cfg!(windows) { "python" } else { "python3" };
|
||||
let encode = |text: &str| {
|
||||
text.bytes()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect::<String>()
|
||||
};
|
||||
format!(
|
||||
"{python} -c \"import sys,time; time.sleep({delay}); sys.stdout.write(bytes.fromhex('{}').decode()); sys.stderr.write(bytes.fromhex('{}').decode()); sys.exit({exit_code})\"",
|
||||
encode(stdout), encode(stderr)
|
||||
)
|
||||
}
|
||||
@@ -1443,7 +1443,6 @@ mod tests {
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io::ErrorKind;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
@@ -1466,6 +1465,9 @@ mod tests {
|
||||
};
|
||||
use crate::McpLifecyclePhase;
|
||||
|
||||
// Fixtures are interpreter inputs, not directly executable Unix scripts.
|
||||
const TEST_PYTHON: &str = if cfg!(windows) { "python" } else { "python3" };
|
||||
|
||||
fn temp_dir() -> PathBuf {
|
||||
static NEXT_TEMP_DIR_ID: AtomicU64 = AtomicU64::new(0);
|
||||
let nanos = SystemTime::now()
|
||||
@@ -1479,15 +1481,19 @@ mod tests {
|
||||
fn write_echo_script() -> PathBuf {
|
||||
let root = temp_dir();
|
||||
fs::create_dir_all(&root).expect("temp dir");
|
||||
let script_path = root.join("echo-mcp.sh");
|
||||
fs::write(
|
||||
&script_path,
|
||||
"#!/bin/sh\nprintf 'READY:%s\\n' \"$MCP_TEST_TOKEN\"\nIFS= read -r line\nprintf 'ECHO:%s\\n' \"$line\"\n",
|
||||
)
|
||||
.expect("write script");
|
||||
let mut permissions = fs::metadata(&script_path).expect("metadata").permissions();
|
||||
permissions.set_mode(0o755);
|
||||
fs::set_permissions(&script_path, permissions).expect("chmod");
|
||||
let script_path = root.join("echo-mcp.py");
|
||||
let script = [
|
||||
"import os, sys",
|
||||
r"ready = ('READY:' + os.environ['MCP_TEST_TOKEN'] + '\n').encode()",
|
||||
"sys.stdout.buffer.write(ready)",
|
||||
"sys.stdout.buffer.flush()",
|
||||
"line = sys.stdin.buffer.readline()",
|
||||
r"sys.stdout.buffer.write(b'ECHO:' + line.rstrip(b'\r\n') + b'\n')",
|
||||
"sys.stdout.buffer.flush()",
|
||||
"",
|
||||
]
|
||||
.join("\n");
|
||||
fs::write(&script_path, script).expect("write script");
|
||||
script_path
|
||||
}
|
||||
|
||||
@@ -1531,9 +1537,6 @@ mod tests {
|
||||
]
|
||||
.join("\n");
|
||||
fs::write(&script_path, script).expect("write script");
|
||||
let mut permissions = fs::metadata(&script_path).expect("metadata").permissions();
|
||||
permissions.set_mode(0o755);
|
||||
fs::set_permissions(&script_path, permissions).expect("chmod");
|
||||
script_path
|
||||
}
|
||||
|
||||
@@ -1665,9 +1668,6 @@ mod tests {
|
||||
]
|
||||
.join("\n");
|
||||
fs::write(&script_path, script).expect("write script");
|
||||
let mut permissions = fs::metadata(&script_path).expect("metadata").permissions();
|
||||
permissions.set_mode(0o755);
|
||||
fs::set_permissions(&script_path, permissions).expect("chmod");
|
||||
script_path
|
||||
}
|
||||
|
||||
@@ -1790,9 +1790,6 @@ mod tests {
|
||||
]
|
||||
.join("\n");
|
||||
fs::write(&script_path, script).expect("write script");
|
||||
let mut permissions = fs::metadata(&script_path).expect("metadata").permissions();
|
||||
permissions.set_mode(0o755);
|
||||
fs::set_permissions(&script_path, permissions).expect("chmod");
|
||||
script_path
|
||||
}
|
||||
|
||||
@@ -1801,7 +1798,7 @@ mod tests {
|
||||
required: false,
|
||||
scope: ConfigSource::Local,
|
||||
config: McpServerConfig::Stdio(McpStdioServerConfig {
|
||||
command: "/bin/sh".to_string(),
|
||||
command: TEST_PYTHON.to_string(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env: BTreeMap::from([("MCP_TEST_TOKEN".to_string(), "secret-value".to_string())]),
|
||||
tool_call_timeout_ms: None,
|
||||
@@ -1819,7 +1816,7 @@ mod tests {
|
||||
env: BTreeMap<String, String>,
|
||||
) -> crate::mcp_client::McpStdioTransport {
|
||||
crate::mcp_client::McpStdioTransport {
|
||||
command: "python3".to_string(),
|
||||
command: TEST_PYTHON.to_string(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env,
|
||||
tool_call_timeout_ms: None,
|
||||
@@ -1869,7 +1866,7 @@ mod tests {
|
||||
required: false,
|
||||
scope: ConfigSource::Local,
|
||||
config: McpServerConfig::Stdio(McpStdioServerConfig {
|
||||
command: "python3".to_string(),
|
||||
command: TEST_PYTHON.to_string(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env,
|
||||
tool_call_timeout_ms: None,
|
||||
@@ -2089,7 +2086,7 @@ mod tests {
|
||||
runtime.block_on(async {
|
||||
let script_path = write_echo_script();
|
||||
let transport = crate::mcp_client::McpStdioTransport {
|
||||
command: "/bin/sh".to_string(),
|
||||
command: TEST_PYTHON.to_string(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env: BTreeMap::from([("MCP_TEST_TOKEN".to_string(), "direct-secret".to_string())]),
|
||||
tool_call_timeout_ms: None,
|
||||
@@ -2349,7 +2346,7 @@ mod tests {
|
||||
required: false,
|
||||
scope: ConfigSource::Local,
|
||||
config: McpServerConfig::Stdio(McpStdioServerConfig {
|
||||
command: "python3".to_string(),
|
||||
command: TEST_PYTHON.to_string(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env: BTreeMap::from([(
|
||||
"MCP_TOOL_CALL_DELAY_MS".to_string(),
|
||||
@@ -2403,7 +2400,7 @@ mod tests {
|
||||
required: false,
|
||||
scope: ConfigSource::Local,
|
||||
config: McpServerConfig::Stdio(McpStdioServerConfig {
|
||||
command: "python3".to_string(),
|
||||
command: TEST_PYTHON.to_string(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env: BTreeMap::from([(
|
||||
"MCP_INVALID_TOOL_CALL_RESPONSE".to_string(),
|
||||
@@ -2714,9 +2711,6 @@ mod tests {
|
||||
]
|
||||
.join("\n");
|
||||
fs::write(&script_path, script).expect("write script");
|
||||
let mut permissions = fs::metadata(&script_path).expect("metadata").permissions();
|
||||
permissions.set_mode(0o755);
|
||||
fs::set_permissions(&script_path, permissions).expect("chmod");
|
||||
script_path
|
||||
}
|
||||
|
||||
@@ -2742,8 +2736,8 @@ mod tests {
|
||||
required: true,
|
||||
scope: ConfigSource::Local,
|
||||
config: McpServerConfig::Stdio(McpStdioServerConfig {
|
||||
command: broken_script_path.display().to_string(),
|
||||
args: Vec::new(),
|
||||
command: TEST_PYTHON.to_string(),
|
||||
args: vec![broken_script_path.to_string_lossy().into_owned()],
|
||||
env: BTreeMap::new(),
|
||||
tool_call_timeout_ms: None,
|
||||
}),
|
||||
|
||||
@@ -314,7 +314,6 @@ impl McpToolRegistry {
|
||||
mod tests {
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
@@ -324,6 +323,9 @@ mod tests {
|
||||
ConfigSource, McpServerConfig, McpStdioServerConfig, ScopedMcpServerConfig,
|
||||
};
|
||||
|
||||
// Fixtures are interpreter inputs, not directly executable Unix scripts.
|
||||
const TEST_PYTHON: &str = if cfg!(windows) { "python" } else { "python3" };
|
||||
|
||||
fn temp_dir() -> PathBuf {
|
||||
static NEXT_TEMP_DIR_ID: AtomicU64 = AtomicU64::new(0);
|
||||
let nanos = SystemTime::now()
|
||||
@@ -430,9 +432,6 @@ mod tests {
|
||||
]
|
||||
.join("\n");
|
||||
fs::write(&script_path, script).expect("write script");
|
||||
let mut permissions = fs::metadata(&script_path).expect("metadata").permissions();
|
||||
permissions.set_mode(0o755);
|
||||
fs::set_permissions(&script_path, permissions).expect("chmod");
|
||||
script_path
|
||||
}
|
||||
|
||||
@@ -445,7 +444,7 @@ mod tests {
|
||||
required: false,
|
||||
scope: ConfigSource::Local,
|
||||
config: McpServerConfig::Stdio(McpStdioServerConfig {
|
||||
command: "python3".to_string(),
|
||||
command: TEST_PYTHON.to_string(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env: BTreeMap::from([
|
||||
("MCP_SERVER_LABEL".to_string(), server_name.to_string()),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, Read};
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -326,7 +326,7 @@ pub fn parse_oauth_callback_query(query: &str) -> Result<OAuthCallbackParams, St
|
||||
|
||||
fn generate_random_token(bytes: usize) -> io::Result<String> {
|
||||
let mut buffer = vec![0_u8; bytes];
|
||||
File::open("/dev/urandom")?.read_exact(&mut buffer)?;
|
||||
getrandom::getrandom(&mut buffer).map_err(|error| io::Error::other(error.to_string()))?;
|
||||
Ok(base64url_encode(&buffer))
|
||||
}
|
||||
|
||||
|
||||
@@ -262,6 +262,12 @@ impl Session {
|
||||
|
||||
pub fn load_from_path(path: impl AsRef<Path>) -> Result<Self, SessionError> {
|
||||
let path = path.as_ref();
|
||||
if fs::metadata(path)?.is_dir() {
|
||||
return Err(SessionError::Io(std::io::Error::new(
|
||||
std::io::ErrorKind::IsADirectory,
|
||||
format!("session_path_is_directory: {}", path.display()),
|
||||
)));
|
||||
}
|
||||
let contents = fs::read_to_string(path)?;
|
||||
let session = match JsonValue::parse(&contents) {
|
||||
Ok(value)
|
||||
|
||||
Reference in new issue
Block a user