fix(files): normalize directory paths and cover CDP upload boundaries

This commit is contained in:
ldm0
2026-11-16 19:42:47 +08:00
committed by Donough Liu
parent 8b6e73d773
commit 084b68c2ef
3 changed files with 215 additions and 12 deletions
+117 -12
View File
@@ -552,8 +552,12 @@ pub(super) fn selected_files_from_paths(
paths: &[String],
) -> Result<Vec<SelectedFile>, PendingDomCommandStartError> {
if paths.len() == 1 && Path::new(&paths[0]).is_dir() {
let root = Path::new(&paths[0]);
let parent = root.parent().unwrap_or_else(|| Path::new(""));
let root = upload_directory_root(Path::new(&paths[0])).map_err(|error| {
PendingDomCommandStartError {
code: -32000,
message: format!("Could not resolve upload directory: {error}"),
}
})?;
let mut directories = vec![root.to_path_buf()];
let mut paths = Vec::new();
while let Some(directory) = directories.pop() {
@@ -583,13 +587,7 @@ pub(super) fn selected_files_from_paths(
.into_iter()
.map(|path| {
let mut file = selected_file_from_file_path(&path)?;
file.relative_path = path
.strip_prefix(parent)
.expect("enumerated files stay below the chosen directory")
.components()
.map(|part| part.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/");
file.relative_path = upload_relative_path(&root, &path);
Ok(file)
})
.collect();
@@ -600,6 +598,30 @@ pub(super) fn selected_files_from_paths(
.collect()
}
fn upload_directory_root(root: &Path) -> std::io::Result<std::path::PathBuf> {
if root.file_name().is_some() {
// Preserve the name of an explicitly selected symlink. Only "." and
// ".." need the resolved directory's name rather than a path component.
std::path::absolute(root)
} else {
fs::canonicalize(root)
}
}
fn upload_relative_path(root: &Path, file: &Path) -> String {
root.file_name()
.into_iter()
.chain(
file.strip_prefix(root)
.expect("enumerated files stay below the chosen directory")
.components()
.map(|component| component.as_os_str()),
)
.map(|component| component.to_string_lossy())
.collect::<Vec<_>>()
.join("/")
}
fn selected_file_from_file_path(
file_path: &Path,
) -> Result<SelectedFile, PendingDomCommandStartError> {
@@ -620,10 +642,10 @@ fn selected_file_from_file_path(
})?;
let name = file_path
.file_name()
.and_then(|name| name.to_str())
.map(|name| name.to_string_lossy())
.filter(|name| !name.is_empty())
.unwrap_or(path.as_ref())
.to_owned();
.unwrap_or_else(|| path.clone())
.into_owned();
let last_modified = metadata
.modified()
.ok()
@@ -688,4 +710,87 @@ mod directory_tests {
);
fs::remove_dir_all(scratch).unwrap();
}
#[test]
fn upload_relative_paths_use_the_selected_directory_name() {
let current = std::env::current_dir().unwrap();
let root = upload_directory_root(Path::new(".")).unwrap();
assert_eq!(root, fs::canonicalize(&current).unwrap());
assert_eq!(
upload_relative_path(&root, &root.join("nested/file.txt")),
format!(
"{}/nested/file.txt",
root.file_name().unwrap().to_string_lossy()
)
);
let parent = upload_directory_root(&current.join("..")).unwrap();
assert_eq!(parent, fs::canonicalize(current.join("..")).unwrap());
}
#[cfg(unix)]
#[test]
fn upload_from_a_filesystem_root_does_not_emit_an_absolute_relative_path() {
// Exercise path derivation without enumerating the machine's root.
assert_eq!(
upload_relative_path(Path::new("/"), Path::new("/file.txt")),
"file.txt"
);
assert_eq!(
upload_relative_path(Path::new("/"), Path::new("/nested/file.txt")),
"nested/file.txt"
);
}
#[cfg(unix)]
#[test]
fn explicit_directory_symlink_is_followed_but_descendant_links_are_skipped() {
use std::os::unix::fs::symlink;
let scratch = std::env::temp_dir().join(format!(
"moli-directory-links-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let root = scratch.join("chosen");
fs::create_dir_all(root.join("nested")).unwrap();
fs::create_dir_all(scratch.join("outside")).unwrap();
fs::write(root.join("nested/real.txt"), b"real").unwrap();
fs::write(scratch.join("outside/secret.txt"), b"outside").unwrap();
symlink(scratch.join("outside"), root.join("directory-link")).unwrap();
symlink(root.join("nested/real.txt"), root.join("file-link")).unwrap();
symlink(&root, scratch.join("selected-link")).unwrap();
let selected = selected_files_from_paths(&[scratch
.join("selected-link")
.to_string_lossy()
.into_owned()])
.unwrap();
assert_eq!(selected.len(), 1);
assert_eq!(selected[0].relative_path, "selected-link/nested/real.txt");
assert_eq!(selected[0].bytes, b"real");
fs::remove_dir_all(scratch).unwrap();
}
#[cfg(unix)]
#[test]
fn non_unicode_upload_name_never_falls_back_to_the_absolute_path() {
use std::os::unix::ffi::OsStringExt;
let scratch = std::env::temp_dir().join(format!(
"moli-directory-name-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&scratch).unwrap();
let file = scratch.join(std::ffi::OsString::from_vec(b"bad-\xff.txt".to_vec()));
fs::write(&file, b"data").unwrap();
let selected =
selected_file_from_file_path(&file).unwrap_or_else(|error| panic!("{}", error.message));
assert_eq!(selected.name, "bad-\u{fffd}.txt");
assert!(selected.relative_path.is_empty());
fs::remove_dir_all(scratch).unwrap();
}
}
@@ -0,0 +1,97 @@
use super::*;
#[tokio::test(flavor = "multi_thread")]
async fn directory_upload_crosses_cdp_filelist_clone_and_multipart_boundaries() {
let scratch = std::env::temp_dir().join(format!(
"moli-cdp-directory-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let directory = scratch.join("chosen");
std::fs::create_dir_all(directory.join("nested")).unwrap();
std::fs::write(directory.join("a.txt"), b"alpha").unwrap();
std::fs::write(directory.join("nested/b.txt"), b"beta").unwrap();
for reference in ["nodeId", "backendNodeId", "objectId"] {
let mut ctx = TestContext::new();
load_bc(&mut ctx, "BID-directory");
navigate_to_data_html_async(
&mut ctx,
31000,
"<!doctype html><form id=form><input id=upload name=files type=file webkitdirectory></form>",
)
.await;
ctx.process_async(json!({"id":31001,"method":"DOM.getDocument"}))
.await;
let root = take_response_by_id(&mut ctx, 31001)["result"]["root"]["nodeId"].clone();
ctx.process_async(json!({"id":31002,"method":"DOM.querySelector","params":{"nodeId":root,"selector":"#upload"}})).await;
let node = take_response_by_id(&mut ctx, 31002)["result"]["nodeId"].clone();
let identifier = match reference {
"nodeId" => node,
"backendNodeId" => {
ctx.process_async(
json!({"id":31003,"method":"DOM.describeNode","params":{"nodeId":node}}),
)
.await;
take_response_by_id(&mut ctx, 31003)["result"]["node"]["backendNodeId"].clone()
}
"objectId" => {
ctx.process_async(json!({"id":31004,"method":"Runtime.evaluate","params":{"expression":"document.getElementById('upload')"}})).await;
take_response_by_id(&mut ctx, 31004)["result"]["result"]["objectId"].clone()
}
_ => unreachable!(),
};
assert!(!identifier.is_null(), "{reference} must resolve");
let mut params = json!({"files":[directory.to_string_lossy()]});
params[reference] = identifier;
ctx.process_and_wait_for_response_async(
json!({"id":31005,"method":"DOM.setFileInputFiles","params":params}),
)
.await;
assert_eq!(
take_response_by_id(&mut ctx, 31005)["result"],
json!({}),
"{reference}"
);
ctx.process_and_wait_for_response_async(json!({
"id":31006,"method":"Runtime.evaluate","params":{
"expression":r#"(async () => {
const input = document.getElementById('upload');
const list = input.files;
const files = [...list];
const transfer = new DataTransfer();
transfer.items.add(files[0]);
const form = new FormData(document.getElementById('form'));
form.append('renamed', files[0], 'explicit.txt');
const body = await new Response(form).text();
return {
paths: files.map(file => file.webkitRelativePath),
contents: await Promise.all(files.map(file => file.text())),
clone: structuredClone(files[0]).webkitRelativePath,
transfer: transfer.files[0].webkitRelativePath,
cached: input.files === list,
defaultFilename: body.includes('filename="chosen/nested/b.txt"'),
explicitFilename: body.includes('filename="explicit.txt"')
};
})()"#,
"awaitPromise":true,"returnByValue":true
}
}))
.await;
let reply = take_response_by_id(&mut ctx, 31006);
assert_eq!(
reply["result"]["result"]["value"],
json!({
"paths":["chosen/a.txt","chosen/nested/b.txt"],
"contents":["alpha","beta"],
"clone":"chosen/a.txt", "transfer":"chosen/a.txt", "cached":true,
"defaultFilename":true,"explicitFilename":true
}),
"{reference}: {reply}"
);
}
std::fs::remove_dir_all(scratch).unwrap();
}
@@ -659,6 +659,7 @@ fn child_default_context_id_from_events(ctx: &TestContext, child_frame_id: &str)
}
mod async_dispatch;
mod directory_upload;
mod frames;
mod geometry;
mod misc;