Skip to content

Commit 69ea36c

Browse files
authored
Merge pull request #595 from OpenCoven/fix/517-cmd-start-open
fix(core,tui,mcp): give cmd.exe start its target whole on Windows
2 parents b56f123 + b3f37cd commit 69ea36c

6 files changed

Lines changed: 380 additions & 32 deletions

File tree

‎.github/workflows/rust-ci.yml‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ jobs:
229229
windows-foreground:
230230
name: Windows foreground command cleanup
231231
runs-on: windows-latest
232-
timeout-minutes: 20
232+
timeout-minutes: 30
233233
steps:
234234
- uses: actions/checkout@v5
235235
with:
@@ -307,17 +307,30 @@ jobs:
307307
done
308308
309309
# cmd.exe must get a command's double quotes exactly as written (#517).
310-
# Each of these five crates hands a command line to cmd.exe and has a
311-
# test file for it. This step runs even if an earlier step failed, tries
312-
# every crate, and requires tests from each.
310+
# Each of these six crates hands a command line to cmd.exe and has a
311+
# test file for it; claurst-mcp's opens a URL with `start`. This step
312+
# runs even if an earlier step failed, tries every crate, and requires
313+
# tests from each.
313314
- name: Test that cmd.exe gets a command's quotes as written
314315
if: ${{ !cancelled() }}
315316
working-directory: src-rust
316317
shell: bash
317318
run: |
318319
failed=0
319-
for package in claurst-core claurst-plugins claurst-tools claurst-query claurst-commands; do
320+
for package in claurst-core claurst-plugins claurst-tools claurst-query claurst-commands claurst-mcp; do
320321
cargo test -p "$package" --locked --test windows_cmd_quotes | tee "$RUNNER_TEMP/$package-cmd-quotes.txt" || failed=1
321322
grep -E 'test result: ok\. [1-9][0-9]* passed' "$RUNNER_TEMP/$package-cmd-quotes.txt" || failed=1
322323
done
323324
exit "$failed"
325+
326+
# The terminal opens the keybindings file with `cmd.exe /C start`, which
327+
# must get the file's path whole (#517). The test is in the terminal
328+
# crate's unit tests, so it runs here by module. This step runs even if
329+
# an earlier step failed, and requires at least one passed test.
330+
- name: Test that the terminal opens a file by its whole path
331+
if: ${{ !cancelled() }}
332+
working-directory: src-rust
333+
shell: bash
334+
run: |
335+
cargo test -p claurst-tui --locked --lib app::windows_open_tests | tee "$RUNNER_TEMP/tui-windows-open-tests.txt"
336+
grep -E 'test result: ok\. [1-9][0-9]* passed' "$RUNNER_TEMP/tui-windows-open-tests.txt"

‎src-rust/crates/core/src/shell.rs‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,55 @@ pub fn command(line: &str) -> Command {
3838
}
3939
}
4040

41+
/// The variable through which [`start`] hands `cmd.exe` its target.
42+
#[cfg(windows)]
43+
pub const START_TARGET_VARIABLE: &str = "COVEN_CODE_START_TARGET";
44+
45+
/// Opens `target`, a file or a URL, with the program Windows associates
46+
/// with it: `shell`, a `cmd.exe` with its environment already set, runs
47+
/// `start "" "<target>"` (#517).
48+
///
49+
/// The target is not written into the command line. `cmd.exe` replaces
50+
/// `%NAME%` there with a variable's value before it reads quotes, and a
51+
/// value can hold a `"`, which would end the quoting and let what follows
52+
/// run as commands. Instead the line is `start "" "!VARIABLE!"`, appended
53+
/// as written like [`command`]'s, with delayed expansion on (`/V:ON`) and
54+
/// the target in [`START_TARGET_VARIABLE`]. `cmd.exe` puts that value in
55+
/// after it has split the line into commands and expanded `%NAME%`, and
56+
/// scans it for neither. `start` takes the first quoted argument as a
57+
/// window title, hence the empty one. `/D` skips the user's `AutoRun`
58+
/// commands. The opened program inherits the variable, so a browser started
59+
/// for an OAuth login keeps the authorization URL in its environment.
60+
///
61+
/// A target with a `"` in it is refused with `InvalidInput`, because
62+
/// `start` would split it there. Windows paths cannot contain one, and
63+
/// `url::Url` writes it percent-encoded. An empty target is refused too:
64+
/// `start ""` would open a console window.
65+
///
66+
/// Add no arguments to the returned command, and do not clear its
67+
/// environment.
68+
#[cfg(windows)]
69+
pub fn start(mut shell: Command, target: impl AsRef<std::ffi::OsStr>) -> std::io::Result<Command> {
70+
use std::os::windows::{ffi::OsStrExt, process::CommandExt};
71+
let target = target.as_ref();
72+
if target.is_empty() {
73+
return Err(std::io::Error::new(
74+
std::io::ErrorKind::InvalidInput,
75+
"no target to open",
76+
));
77+
}
78+
if target.encode_wide().any(|unit| unit == u16::from(b'"')) {
79+
return Err(std::io::Error::new(
80+
std::io::ErrorKind::InvalidInput,
81+
"a target to open contains a double quote",
82+
));
83+
}
84+
shell.env(START_TARGET_VARIABLE, target).raw_arg(format!(
85+
"/D /V:ON /C \"start \"\" \"!{START_TARGET_VARIABLE}!\"\""
86+
));
87+
Ok(shell)
88+
}
89+
4190
#[cfg(all(test, unix))]
4291
mod tests {
4392
#[test]

‎src-rust/crates/core/tests/windows_cmd_quotes.rs‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,36 @@ fn shell_command_passes_quotes_as_written() {
6060
assert_eq!(String::from_utf8_lossy(&output.stdout), printed, "{line}");
6161
}
6262
}
63+
64+
/// `start` gets its target through a variable that `cmd.exe` expands after
65+
/// it has read the line, and a target that would split `start`'s argument
66+
/// is refused, as is an empty one. What `start` then opens is covered by the callers' tests, in
67+
/// claurst-tui and claurst-mcp.
68+
#[test]
69+
fn shell_start_hands_over_its_target_in_a_variable() {
70+
use claurst_core::shell::{start, START_TARGET_VARIABLE};
71+
let target = r"C:\temp\safe & %PATH% ^ literal.txt";
72+
let shell = start(std::process::Command::new("cmd"), target).unwrap();
73+
assert_eq!(shell.get_program(), "cmd");
74+
let arguments: Vec<String> = shell
75+
.get_args()
76+
.map(|argument| argument.to_string_lossy().into_owned())
77+
.collect();
78+
assert_eq!(
79+
arguments,
80+
[format!(
81+
r#"/D /V:ON /C "start "" "!{START_TARGET_VARIABLE}!"""#
82+
)]
83+
);
84+
assert_eq!(
85+
shell.get_envs().collect::<Vec<_>>(),
86+
[(
87+
std::ffi::OsStr::new(START_TARGET_VARIABLE),
88+
Some(std::ffi::OsStr::new(target))
89+
)]
90+
);
91+
for refused in [r#"x" & echo injected & ""#, ""] {
92+
let error = start(std::process::Command::new("cmd"), refused).unwrap_err();
93+
assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput, "{refused}");
94+
}
95+
}

‎src-rust/crates/mcp/src/oauth.rs‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -890,9 +890,7 @@ pub fn initiate_xaa_login(server_name: &str, idp_url: &str) -> std::io::Result<X
890890
fn open_browser(url: &str) -> std::io::Result<()> {
891891
#[cfg(target_os = "windows")]
892892
{
893-
std::process::Command::new("cmd")
894-
.args(["/C", "start", url])
895-
.status()?;
893+
claurst_core::shell::start(std::process::Command::new("cmd"), url)?.status()?;
896894
}
897895
#[cfg(target_os = "macos")]
898896
{
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
//! #517 on Windows: the XAA login opens its URL through `cmd.exe /C start`,
2+
//! which must get the whole URL. Before, the URL reached `cmd.exe` unquoted,
3+
//! and `cmd.exe` ended the command at the URL's first `&`.
4+
//!
5+
//! `cmd.exe` also replaces `%NAME%` with the variable's value, which can be
6+
//! a `"` that ends the quoting around the URL.
7+
//!
8+
//! A URL scheme registered for the current user stands in for the browser:
9+
//! Windows runs this test binary with the URL it was asked to open. Whether a
10+
//! real browser then shows the page can only be seen on a desktop.
11+
#![cfg(windows)]
12+
13+
use claurst_mcp::oauth::{initiate_xaa_login, pkce_challenge};
14+
use std::collections::BTreeMap;
15+
use std::path::{Path, PathBuf};
16+
use std::process::Command;
17+
use std::time::{Duration, Instant};
18+
19+
const CAPTURE: &str = "capture";
20+
21+
// The registry helpers are repeated in claurst-tui's `windows_open_tests`:
22+
// test crates cannot share a module.
23+
24+
/// A registry key under `HKCU\Software\Classes`, removed on drop.
25+
struct Registered(String);
26+
27+
impl Drop for Registered {
28+
fn drop(&mut self) {
29+
let _ = Command::new("reg")
30+
.args(["delete", self.0.as_str(), "/f"])
31+
.output();
32+
}
33+
}
34+
35+
fn reg_add(key: &str, value: &[&str], data: &str) {
36+
let output = Command::new("reg")
37+
.arg("add")
38+
.arg(key)
39+
.args(value)
40+
.args(["/d", data, "/f"])
41+
.output()
42+
.unwrap();
43+
assert!(output.status.success(), "reg add {key}: {output:?}");
44+
}
45+
46+
/// Make `scheme:` URLs open with this test binary, which writes the URL it
47+
/// was given to `capture`.
48+
fn register_scheme(scheme: &str, capture: &Path) -> Registered {
49+
let registered = Registered(format!(r"HKCU\Software\Classes\{scheme}"));
50+
reg_add(&registered.0, &["/ve"], "URL:coven-code #517 test");
51+
reg_add(&registered.0, &["/v", "URL Protocol"], "");
52+
let handler = format!(
53+
r#""{}" --exact url_open_handler --ignored --nocapture "{}" "%1""#,
54+
std::env::current_exe().unwrap().display(),
55+
capture.display(),
56+
);
57+
reg_add(
58+
&format!(r"{}\shell\open\command", registered.0),
59+
&["/ve"],
60+
&handler,
61+
);
62+
registered
63+
}
64+
65+
fn wait_for(capture: &Path) -> String {
66+
let deadline = Instant::now() + Duration::from_secs(60);
67+
loop {
68+
if let Ok(text) = std::fs::read_to_string(capture) {
69+
return text;
70+
}
71+
assert!(
72+
Instant::now() < deadline,
73+
"nothing was opened within 60 s: {} was not written",
74+
capture.display()
75+
);
76+
std::thread::sleep(Duration::from_millis(100));
77+
}
78+
}
79+
80+
#[test]
81+
fn xaa_login_opens_the_whole_url() {
82+
let directory = tempfile::tempdir().unwrap();
83+
let capture = directory.path().join(format!("url.{CAPTURE}"));
84+
let scheme = format!("coven-test-517-{}", std::process::id());
85+
let _registered = register_scheme(&scheme, &capture);
86+
// The login appends four parameters with `&`. `%PATH%` is set, and
87+
// `cmd.exe` would replace it with its value; with delayed expansion on,
88+
// it would also replace `!PATH!` and drop the `^`.
89+
let endpoint = format!("{scheme}://authorize?audience=mcp%2Btools&note=%PATH%!PATH!^x");
90+
91+
// The launch waits for `cmd.exe`; bound it, should Windows ask anything.
92+
let (sent, launched) = std::sync::mpsc::channel();
93+
std::thread::spawn(move || {
94+
let _ = sent.send(initiate_xaa_login("fixture", &endpoint));
95+
});
96+
let state = launched
97+
.recv_timeout(Duration::from_secs(60))
98+
.expect("the login did not return within 60 s")
99+
.unwrap();
100+
101+
let opened = wait_for(&capture);
102+
let url = url::Url::parse(&opened).unwrap();
103+
assert_eq!(url.scheme(), scheme, "{opened}");
104+
let query: BTreeMap<_, _> = url.query_pairs().into_owned().collect();
105+
let expected = BTreeMap::from([
106+
("audience".to_string(), "mcp+tools".to_string()),
107+
("note".to_string(), "%PATH%!PATH!^x".to_string()),
108+
("response_type".to_string(), "code".to_string()),
109+
(
110+
"code_challenge".to_string(),
111+
pkce_challenge(&state.verifier),
112+
),
113+
("code_challenge_method".to_string(), "S256".to_string()),
114+
(
115+
"redirect_uri".to_string(),
116+
format!("http://127.0.0.1:{}/callback", state.redirect_port),
117+
),
118+
]);
119+
assert_eq!(query, expected, "Windows was asked to open {opened}");
120+
}
121+
122+
/// Run by Windows as the test scheme's handler, with the capture file and
123+
/// the URL as its last two arguments. It does nothing unless the first of
124+
/// those is a capture file.
125+
#[test]
126+
#[ignore = "run by Windows as the handler of the test URL scheme"]
127+
fn url_open_handler() {
128+
let mut arguments = std::env::args_os().rev();
129+
let (Some(opened), Some(capture)) = (arguments.next(), arguments.next()) else {
130+
return;
131+
};
132+
let capture = PathBuf::from(capture);
133+
if capture
134+
.extension()
135+
.is_none_or(|extension| extension != CAPTURE)
136+
{
137+
return;
138+
}
139+
let partial = capture.with_extension("partial");
140+
std::fs::write(&partial, opened.to_string_lossy().as_bytes()).unwrap();
141+
std::fs::rename(partial, capture).unwrap();
142+
}

0 commit comments

Comments
 (0)