Unverified Commit 17a901a7 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Guard filesystem reads against unresolved symlinks (#97902)

### What?

Adds debug-only OS realpath validation to successful `DiskFileSystem`
file and directory reads. When a successfully canonicalized path differs
from the supplied path, the read returns a normal task error naming both
paths.

Fixes pattern/glob traversal and NFT tracing so physical filesystem
access uses resolved paths while logical paths remain available for
user-visible specifiers and complete symlink-chain recovery.

### Why?

Reading through an unresolved symlink parent gives the same filesystem
object multiple path identities. That can make Turbo Tasks dependency
tracking and invalidation inconsistent and can produce invalid
deployment ZIPs when NFT output contains files below unresolved links.

The checks return errors rather than asserting because paths can
disagree temporarily under eventual consistency. Propagating a task
error avoids panicking a worker thread while still exposing invalid
callers during development.

### How?

The validation lives directly in `DiskFileSystem::read` and
`DiskFileSystem::raw_read_dir`. It calls the OS canonicalization API
inline instead of the Turbo Tasks realpath task, keeping the diagnostic
out of the task dependency graph. The guard runs only after the OS read
succeeds, so missing/non-directory probes preserve their existing
behavior.

`read_matches` resolves each physical directory immediately before
enumeration while retaining logical `PatternMatch` paths.

`read_glob` and `track_glob` now resolve their initial directory before
enumeration. Symlinks discovered later through wildcard segments are
also traversed through resolved targets. `ReadGlobResult` deliberately
retains logical paths rooted at the supplied base, allowing consumers to
call `realpath_with_links` and recover the complete symlink chain.

Consumers follow that contract explicitly:

- NFT includes expand each logical match with `realpath_with_links`,
emit resolved files and every traversed symlink, skip resolved directory
targets, and deterministically deduplicate/sort output.
- `import.meta.glob` uses recursive logical keys as the source of
user-visible requests, while module resolution follows and tracks
symlinks.
- the hash-glob example resolves returned logical paths before reading.

Webpack-loader context dependencies are covered for both
`path/to/symlink/inner/path/*` and `path/to/*/inner/path/*`. The loader
fixture performs its directory read with Node `fs`, reports the
directory using `addContextDependency`, and Turbopack tracks the
resolved target.

### Verification

- `cargo fmt -p turbo-tasks-fs -p turbopack-ecmascript -p next-api --
--check`
- `cargo clippy -p turbo-tasks-fs -p turbopack-ecmascript -p next-api
--all-targets`
- `cargo test -p turbo-tasks-fs` (128 passed)
- `cargo test -p next-api` (7 passed)
- `cargo check -p turbo-tasks-fs --examples`
- `import.meta.glob` symlink execution fixture (1 passed)
- Nine targeted node-file-trace CI cases with `release-with-assertions`
(9 passed)
- `pnpm build-all`
- `webpack-loader-fs` Turbopack dev e2e (1 passed)
- `build-trace-extra-entries-turbo` Turbopack production e2e (1 passed)
- twoslash Turbopack production, normal mode (4 passed)
- twoslash Turbopack production, cache-components mode (4 passed)
- `bench/heavy-npm-deps` Turbopack development smoke test (HTTP 200)

### Notes

The disk guard is cross-platform, while its symlink-parent regression
test is Unix-only, matching neighbouring symlink tests. On Windows, OS
canonicalization can also normalize casing and 8.3 short names; a debug
read using a non-canonical spelling will therefore return the same
diagnostic error.

<!-- NEXT_JS_LLM -->


<!-- fleet 1d32e12c-f4ec-4f22-862a-c85f0005805c -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 6f44fd34
...@@ -10,7 +10,7 @@ use turbo_tasks::{ ...@@ -10,7 +10,7 @@ use turbo_tasks::{
FxIndexMap, FxIndexSet, ReadRef, ResolvedVc, TraitRef, TryFlatJoinIterExt, TryJoinIterExt, Vc, FxIndexMap, FxIndexSet, ReadRef, ResolvedVc, TraitRef, TryFlatJoinIterExt, TryJoinIterExt, Vc,
}; };
use turbo_tasks_fs::{ use turbo_tasks_fs::{
DirectoryEntry, FileSystemPath, DirectoryEntry, FileSystemEntryType, FileSystemPath,
glob::{Glob, GlobOptions}, glob::{Glob, GlobOptions},
}; };
use turbo_tasks_hash::HashAlgorithm; use turbo_tasks_hash::HashAlgorithm;
...@@ -193,19 +193,28 @@ async fn get_glob_includes( ...@@ -193,19 +193,28 @@ async fn get_glob_includes(
let glob_result = project_root_path.read_glob(glob).await?; let glob_result = project_root_path.read_glob(glob).await?;
// Walk the full glob_result using an explicit stack to avoid async recursion overheads. // Walk the full glob_result using an explicit stack to avoid async recursion overheads.
// Use a BTreeSet to get deterministic order (return value of `read_glob` has random order). // Deduplicate symlinks shared by many matches. The return value of `read_glob` has random
let mut result = vec![]; // order, so the result is sorted below.
let mut result = FxHashSet::default();
let mut stack = VecDeque::new(); let mut stack = VecDeque::new();
stack.push_back(glob_result); stack.push_back(glob_result);
while let Some(glob_result) = stack.pop_back() { while let Some(glob_result) = stack.pop_back() {
// Process direct results (files and directories at this level) // Process direct results (files and directories at this level).
for entry in glob_result.results.values() { for entry in glob_result.results.values() {
let (DirectoryEntry::File(file_path) | DirectoryEntry::Symlink(file_path)) = entry let (DirectoryEntry::File(file_path) | DirectoryEntry::Symlink(file_path)) = entry
else { else {
continue; continue;
}; };
result.push(file_path.clone()); // ReadGlobResult paths are logical by contract. Resolve each match here so the NFT
// includes both the physical file and every symlink needed to reach it.
let realpath = file_path.realpath_with_links().await?;
result.extend(realpath.symlinks.iter().cloned());
if let Ok(resolved_path) = &realpath.path_result
&& matches!(*resolved_path.get_type().await?, FileSystemEntryType::File)
{
result.insert(resolved_path.clone());
}
} }
for nested_result in glob_result.inner.values() { for nested_result in glob_result.inner.values() {
...@@ -216,8 +225,8 @@ async fn get_glob_includes( ...@@ -216,8 +225,8 @@ async fn get_glob_includes(
// All paths were matched from project_root_path, so they must all have the same `fs`. So it's // All paths were matched from project_root_path, so they must all have the same `fs`. So it's
// enough to sort by path. // enough to sort by path.
let mut result: Vec<_> = result.into_iter().collect();
result.sort_by(|a, b| a.path.cmp(&b.path)); result.sort_by(|a, b| a.path.cmp(&b.path));
Ok(result) Ok(result)
} }
...@@ -564,3 +573,81 @@ impl Issue for ForbiddenTracedFileIssue { ...@@ -564,3 +573,81 @@ impl Issue for ForbiddenTracedFileIssue {
Ok(Some(StyledString::Stack(stack))) Ok(Some(StyledString::Stack(stack)))
} }
} }
#[cfg(all(test, unix))]
mod tests {
use std::{
fs::{create_dir_all, write},
os::unix::fs::symlink,
};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::Vc;
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_fs::{
DiskFileSystem, FileSystem,
glob::{Glob, GlobOptions},
};
use crate::nft::get_glob_includes;
#[turbo_tasks::function(operation, root)]
async fn assert_glob_includes_operation(disk_root: RcStr) -> anyhow::Result<()> {
let root = DiskFileSystem::new(rcstr!("test"), Vc::cell(disk_root))
.root()
.owned()
.await?;
let includes = get_glob_includes(
root,
Glob::new(
rcstr!("**"),
GlobOptions {
contains: true,
..Default::default()
},
),
)
.await?;
assert_eq!(
includes
.iter()
.map(|path| path.path.as_str())
.collect::<Vec<_>>(),
[
"alias",
"alias-chain",
"dangling",
"file-link",
"real/file.txt",
]
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn glob_includes_resolve_files_and_retain_symlinks() {
let scratch = tempfile::tempdir().unwrap();
let root = scratch.path();
create_dir_all(root.join("real")).unwrap();
write(root.join("real/file.txt"), "content").unwrap();
symlink("real", root.join("alias")).unwrap();
symlink("alias", root.join("alias-chain")).unwrap();
symlink("real/file.txt", root.join("file-link")).unwrap();
symlink("missing", root.join("dangling")).unwrap();
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
noop_backing_storage(),
));
let disk_root: RcStr = root.to_str().unwrap().into();
tt.run_once(async move {
assert_glob_includes_operation(disk_root)
.read_strongly_consistent()
.await?;
anyhow::Ok(())
})
.await
.unwrap();
}
}
../../glob-target
\ No newline at end of file
const fs = require('fs')
const path = require('path') const path = require('path')
module.exports = async function (content) { module.exports = async function (content) {
...@@ -21,5 +22,13 @@ module.exports = async function (content) { ...@@ -21,5 +22,13 @@ module.exports = async function (content) {
res(data) res(data)
}) })
) )
return `module.exports = "Buffer read: ${read1 instanceof Buffer ? read1.length : 0}, string read: '${read2.trim()}', binary read: ${read3.length}"` const globDir = path.join(dir, 'path/to/symlink/inner/path')
const globEntries = await new Promise((res, rej) =>
fs.readdir(globDir, (err, entries) => {
if (err) return rej(err)
res(entries)
})
)
this.addContextDependency(globDir)
return `module.exports = "Buffer read: ${read1 instanceof Buffer ? read1.length : 0}, string read: '${read2.trim()}', binary read: ${read3.length}, glob read: '${globEntries.sort().join(',')}'"`
} }
...@@ -11,7 +11,7 @@ describe('webpack-loader-fs', () => { ...@@ -11,7 +11,7 @@ describe('webpack-loader-fs', () => {
it('should allow reading the input FS', async () => { it('should allow reading the input FS', async () => {
const $ = await next.render$('/') const $ = await next.render$('/')
expect($('#test').text()).toBe( expect($('#test').text()).toBe(
"Buffer read: 18, string read: 'this is some data', binary read: 6765" "Buffer read: 18, string read: 'this is some data', binary read: 6765, glob read: 'one.txt'"
) )
}) })
}) })
...@@ -74,8 +74,8 @@ describe('build trace with extra entries', () => { ...@@ -74,8 +74,8 @@ describe('build trace with extra entries', () => {
).toBe(true) ).toBe(true)
if (isTurbopack) { if (isTurbopack) {
// A symlink matched by outputFileTracingIncludes is traced as the symlink itself, even // A symlink matched by outputFileTracingIncludes is traced as the symlink itself, even
// when it points at a directory (this used to fail the build with // when it points at a directory. Files reached through it are traced at their resolved
// `reading file "..." Is a directory (os error 21)`). // paths so deployment includes both the link and its target contents.
// The webpack tracer globs with `nodir: true`, which drops directory symlinks, so this // The webpack tracer globs with `nodir: true`, which drops directory symlinks, so this
// only applies to Turbopack. // only applies to Turbopack.
expect( expect(
...@@ -83,11 +83,27 @@ describe('build trace with extra entries', () => { ...@@ -83,11 +83,27 @@ describe('build trace with extra entries', () => {
(file: string) => file === '../../../include-me/link-to-dir' (file: string) => file === '../../../include-me/link-to-dir'
) )
).toBe(true) ).toBe(true)
expect(
tracedFiles.some(
(file: string) => file === '../../../content/hello.json'
)
).toBe(true)
expect(
tracedFiles.some(
(file: string) =>
file === '../../../include-me/link-to-dir/hello.json'
)
).toBe(false)
expect( expect(
appDirRoute1Trace.files.some( appDirRoute1Trace.files.some(
(file: string) => file === '../../../../include-me/link-to-dir' (file: string) => file === '../../../../include-me/link-to-dir'
) )
).toBe(true) ).toBe(true)
expect(
appDirRoute1Trace.files.some(
(file: string) => file === '../../../../content/hello.json'
)
).toBe(true)
} }
expect( expect(
indexTrace.files.some((file: string) => file.includes('exclude-me')) indexTrace.files.some((file: string) => file.includes('exclude-me'))
......
...@@ -98,6 +98,9 @@ async fn hash_glob_result(result: Vc<ReadGlobResult>) -> Result<Vc<RcStr>> { ...@@ -98,6 +98,9 @@ async fn hash_glob_result(result: Vc<ReadGlobResult>) -> Result<Vc<RcStr>> {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn hash_file(file_path: FileSystemPath) -> Result<Vc<RcStr>> { async fn hash_file(file_path: FileSystemPath) -> Result<Vc<RcStr>> {
let Ok(file_path) = file_path.realpath().await? else {
return Ok(empty_string());
};
let content = file_path.read().await?; let content = file_path.read().await?;
Ok(match &*content { Ok(match &*content {
FileContent::Content(file) => hash_content(&mut file.read()), FileContent::Content(file) => hash_content(&mut file.read()),
......
...@@ -482,6 +482,22 @@ impl DiskFileSystem { ...@@ -482,6 +482,22 @@ impl DiskFileSystem {
&self.inner.root &self.inner.root
} }
#[cfg(debug_assertions)]
async fn ensure_path_is_realpath(&self, operation: &str, path: &Path) -> Result<()> {
if let Ok(realpath) = retry_blocking(|| fs_err::canonicalize(path))
.instrument(tracing::info_span!("realpath for filesystem read", name = ?path))
.concurrency_limited(&self.inner.read_semaphore)
.await
&& realpath != path
{
anyhow::bail!(
"{operation} called with unresolved path {path:?}; resolve it to {realpath:?} \
first"
);
}
Ok(())
}
pub fn invalidate(&self) { pub fn invalidate(&self) {
self.inner.invalidate(); self.inner.invalidate();
} }
...@@ -797,7 +813,12 @@ impl FileSystem for DiskFileSystem { ...@@ -797,7 +813,12 @@ impl FileSystem for DiskFileSystem {
.concurrency_limited(&self.inner.read_semaphore) .concurrency_limited(&self.inner.read_semaphore)
.await .await
{ {
Ok(file) => FileContent::new(file), Ok(file) => {
#[cfg(debug_assertions)]
self.ensure_path_is_realpath("read_file", &full_path)
.await?;
FileContent::new(file)
}
Err(e) if e.kind() == ErrorKind::NotFound || e.kind() == ErrorKind::InvalidFilename => { Err(e) if e.kind() == ErrorKind::NotFound || e.kind() == ErrorKind::InvalidFilename => {
FileContent::NotFound FileContent::NotFound
} }
...@@ -823,7 +844,11 @@ impl FileSystem for DiskFileSystem { ...@@ -823,7 +844,11 @@ impl FileSystem for DiskFileSystem {
.concurrency_limited(&self.inner.read_semaphore) .concurrency_limited(&self.inner.read_semaphore)
.await .await
{ {
Ok(dir) => dir, Ok(dir) => {
#[cfg(debug_assertions)]
self.ensure_path_is_realpath("read_dir", &full_path).await?;
dir
}
Err(e) Err(e)
if e.kind() == ErrorKind::NotFound if e.kind() == ErrorKind::NotFound
|| e.kind() == ErrorKind::NotADirectory || e.kind() == ErrorKind::NotADirectory
...@@ -1719,6 +1744,8 @@ mod tests { ...@@ -1719,6 +1744,8 @@ mod tests {
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage}; use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use super::extract_effects_operation; use super::extract_effects_operation;
#[cfg(all(unix, debug_assertions))]
use crate::{DirectoryContent, FileContent, RawDirectoryContent};
use crate::{ use crate::{
DiskFileSystem, FileSystem, FileSystemEntryType, FileSystemPath, LinkContent, DiskFileSystem, FileSystem, FileSystemEntryType, FileSystemPath, LinkContent,
LinkTarget, RealPathErrorType, WriteLinkContent, WriteLinkTarget, WriteLinkTargetType, LinkTarget, RealPathErrorType, WriteLinkContent, WriteLinkTarget, WriteLinkTargetType,
...@@ -1865,6 +1892,87 @@ mod tests { ...@@ -1865,6 +1892,87 @@ mod tests {
Ok(()) Ok(())
} }
#[cfg(all(unix, debug_assertions))]
#[turbo_tasks::function(operation, root)]
async fn assert_read_realpath_operation(root_path: FileSystemPath) -> anyhow::Result<()> {
let unresolved_dir = root_path.join("alias/child")?;
let resolved_dir = unresolved_dir
.realpath()
.await?
.expect("the linked directory should resolve");
assert_ne!(unresolved_dir, resolved_dir);
let error = unresolved_dir
.read_dir()
.await
.expect_err("a directory read through a symlinked parent must be rejected");
let message = format!("{error:#}");
assert!(message.contains("alias/child"));
assert!(message.contains("real/child"));
assert!(matches!(
&*resolved_dir.read_dir().await?,
DirectoryContent::Entries(entries) if entries.contains_key(&rcstr!("data.txt"))
));
assert!(matches!(
&*root_path.join("file-alias")?.raw_read_dir().await?,
RawDirectoryContent::NotFound
));
let unresolved_file = unresolved_dir.join("data.txt")?;
let resolved_file = unresolved_file
.realpath()
.await?
.expect("the linked file should resolve");
assert_ne!(unresolved_file, resolved_file);
let error = unresolved_file
.read()
.await
.expect_err("a file read through a symlinked parent must be rejected");
let message = format!("{error:#}");
assert!(message.contains("alias/child/data.txt"));
assert!(message.contains("real/child/data.txt"));
assert!(matches!(
&*resolved_file.read().await?,
FileContent::Content(_)
));
Ok(())
}
#[cfg(all(unix, debug_assertions))]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_reads_require_realpath() {
use std::os::unix::fs::symlink;
let scratch = tempfile::tempdir().unwrap();
let path = scratch.path().to_owned();
create_dir_all(path.join("real/child")).unwrap();
File::create_new(path.join("real/child/data.txt")).unwrap();
symlink("real", path.join("alias")).unwrap();
symlink("real/child/data.txt", path.join("file-alias")).unwrap();
let root = canonicalize_to_rcstr(&path).unwrap();
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
noop_backing_storage(),
));
tt.run_once(async move {
let fs = disk_file_system_operation(root)
.resolve()
.strongly_consistent()
.await?;
let root_path = disk_file_system_root(fs);
assert_read_realpath_operation(root_path)
.read_strongly_consistent()
.await?;
anyhow::Ok(())
})
.await
.unwrap();
}
/// `read_link` never looks at the target, so a dangling link still reads back as a valid /// `read_link` never looks at the target, so a dangling link still reads back as a valid
/// [`LinkContent::Link`]. Resolving it reports the missing target. /// [`LinkContent::Link`]. Resolving it reports the missing target.
#[cfg(unix)] #[cfg(unix)]
......
...@@ -11,7 +11,8 @@ use rustc_hash::{FxHashMap, FxHashSet}; ...@@ -11,7 +11,8 @@ use rustc_hash::{FxHashMap, FxHashSet};
use tracing::Instrument; use tracing::Instrument;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
NonLocalValue, TaskInput, ValueToString, Vc, debug::ValueDebugFormat, trace::TraceRawVcs, NonLocalValue, ReadRef, TaskInput, ValueToString, Vc, debug::ValueDebugFormat,
trace::TraceRawVcs,
}; };
use turbo_tasks_fs::{ use turbo_tasks_fs::{
FileSystemEntryType, FileSystemPath, LinkContent, RawDirectoryContent, RawDirectoryEntry, FileSystemEntryType, FileSystemPath, LinkContent, RawDirectoryContent, RawDirectoryEntry,
...@@ -1511,14 +1512,29 @@ impl PatternMatch { ...@@ -1511,14 +1512,29 @@ impl PatternMatch {
#[derive(Debug)] #[derive(Debug)]
pub struct PatternMatches(Vec<PatternMatch>); pub struct PatternMatches(Vec<PatternMatch>);
/// Reads the directory `path` points at, enumerating it through its realpath.
///
/// Callers keep the original logical `path` when constructing [`PatternMatch`] values, so symlinks
/// stay visible in the results while the directory itself is never read through a symlinked
/// parent. Resolving also registers a dependency on the symlink chain, so replacing a link
/// invalidates the enumeration.
///
/// A path that cannot be resolved (a dangling or cyclic link) is read as-is, which yields
/// [`RawDirectoryContent::NotFound`] just as it did before.
async fn raw_read_dir_resolved(path: &FileSystemPath) -> Result<ReadRef<RawDirectoryContent>> {
let resolved = path.realpath().await?.unwrap_or_else(|_| path.clone());
resolved.raw_read_dir().await
}
/// Find all files or directories that match the provided `pattern` with the /// Find all files or directories that match the provided `pattern` with the
/// specified `lookup_dir` directory. `prefix` is the already matched part of /// specified `lookup_dir` directory. `prefix` is the already matched part of
/// the pattern that leads to the `lookup_dir` directory. When /// the pattern that leads to the `lookup_dir` directory. When
/// `force_in_lookup_dir` is set, leaving the `lookup_dir` directory by /// `force_in_lookup_dir` is set, leaving the `lookup_dir` directory by
/// matching `..` is not allowed. /// matching `..` is not allowed.
/// ///
/// Symlinks will not be resolved. It's expected that the caller resolves /// Symlinks in returned matches are not resolved. Lookup directories are resolved only for
/// symlinks when they are interested in that. /// physical enumeration; logical paths are retained in [`PatternMatch`] values so callers can
/// resolve and track the symlinks they are interested in.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn read_matches( pub async fn read_matches(
lookup_dir: FileSystemPath, lookup_dir: FileSystemPath,
...@@ -1572,7 +1588,7 @@ pub async fn read_matches( ...@@ -1572,7 +1588,7 @@ pub async fn read_matches(
lookup_dir.try_join(parent_path) lookup_dir.try_join(parent_path)
}; };
if let Some(path) = path_option { if let Some(path) = path_option {
Some(e.insert((path.raw_read_dir().await?, path))) Some(e.insert((raw_read_dir_resolved(&path).await?, path)))
} else { } else {
None None
} }
...@@ -1739,7 +1755,7 @@ pub async fn read_matches( ...@@ -1739,7 +1755,7 @@ pub async fn read_matches(
prefix.pop(); prefix.pop();
prefix.pop(); prefix.pop();
} }
match &*lookup_dir.raw_read_dir().await? { match &*raw_read_dir_resolved(&lookup_dir).await? {
RawDirectoryContent::Entries(map) => { RawDirectoryContent::Entries(map) => {
for (key, entry) in map.iter() { for (key, entry) in map.iter() {
match entry { match entry {
...@@ -1917,7 +1933,8 @@ mod tests { ...@@ -1917,7 +1933,8 @@ mod tests {
use turbo_tasks_fs::{DiskFileSystem, FileSystem}; use turbo_tasks_fs::{DiskFileSystem, FileSystem};
use super::{ use super::{
Pattern, longest_common_prefix, longest_common_suffix, read_matches, split_last_segment, Pattern, PatternMatch, longest_common_prefix, longest_common_suffix, read_matches,
split_last_segment,
}; };
#[test] #[test]
...@@ -2660,6 +2677,60 @@ mod tests { ...@@ -2660,6 +2677,60 @@ mod tests {
assert_eq!(split_last_segment("../../a/"), ("../..", "a")); assert_eq!(split_last_segment("../../a/"), ("../..", "a"));
} }
#[cfg(all(unix, debug_assertions))]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_read_matches_resolves_lookup_dir_for_enumeration() {
use std::{fs::create_dir_all, os::unix::fs::symlink};
let scratch = tempfile::tempdir().unwrap();
let root = scratch.path();
create_dir_all(root.join("real")).unwrap();
std::fs::write(root.join("real/file.js"), "content").unwrap();
symlink("real", root.join("alias")).unwrap();
symlink("real/file.js", root.join("file-alias")).unwrap();
#[turbo_tasks::function(operation, root)]
async fn operation(disk_root: RcStr) -> anyhow::Result<()> {
let root = DiskFileSystem::new(rcstr!("test"), Vc::cell(disk_root))
.root()
.owned()
.await?;
let logical_dir = root.join("alias")?;
let matches = read_matches(
logical_dir.clone(),
rcstr!(""),
true,
Pattern::new(Pattern::Dynamic),
)
.await?;
assert!(matches.iter().any(|m| m
== &PatternMatch::File(rcstr!("file.js"), logical_dir.join("file.js").unwrap(),)));
let file_probe = read_matches(
root.join("file-alias")?,
rcstr!(""),
true,
Pattern::new(Pattern::Dynamic),
)
.await?;
assert!(file_probe.is_empty());
Ok(())
}
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
noop_backing_storage(),
));
let disk_root: RcStr = root.to_str().unwrap().into();
tt.run_once(async move {
operation(disk_root).read_strongly_consistent().await?;
anyhow::Ok(())
})
.await
.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_read_matches() { async fn test_read_matches() {
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new( let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
......
...@@ -460,14 +460,18 @@ impl ImportMetaGlobMap { ...@@ -460,14 +460,18 @@ impl ImportMetaGlobMap {
true true
} }
}) })
.map(|(_base_relative, path)| { .map(|(base_relative, _logical_path)| {
let origin_path = &origin_path; let origin_path = &origin_path;
let base_dir = &base_dir;
let query = &query; let query = &query;
let reference_sub_type = &reference_sub_type; let reference_sub_type = &reference_sub_type;
async move { async move {
// Compute the origin-relative path for import resolution and as the // ReadGlobResult paths are logical too, but reconstruct from its keys here so
// user-visible key in the result object. // matching and user-visible specifiers have one explicit source of truth. The
let Some(origin_relative) = origin_path.get_relative_path_to(path) else { // module resolver resolves this logical request and tracks its symlink chain.
let logical_path = base_dir.join(base_relative)?;
let Some(origin_relative) = origin_path.get_relative_path_to(&logical_path)
else {
bail!( bail!(
"import.meta.glob: failed to compute relative path from origin to \ "import.meta.glob: failed to compute relative path from origin to \
matched file" matched file"
......
...@@ -63,6 +63,16 @@ it('should support multiple patterns across directories', () => { ...@@ -63,6 +63,16 @@ it('should support multiple patterns across directories', () => {
expect(multiModules['./other/baz.js'].default).toBe('baz') expect(multiModules['./other/baz.js'].default).toBe('baz')
}) })
// The result keys stay logical while module resolution follows the directory symlink.
const symlinkModules = import.meta.glob('./linked/*.js', { eager: true })
it('should resolve modules through a symlink while preserving logical keys', () => {
const keys = Object.keys(symlinkModules).sort()
expect(keys).toEqual(['./linked/bar.js', './linked/foo.js'])
expect(symlinkModules['./linked/foo.js'].default).toBe('foo')
expect(symlinkModules['./linked/bar.js'].default).toBe('bar')
})
// import: '*' (namespace import) — should return the whole module namespace // import: '*' (namespace import) — should return the whole module namespace
// Uses ./other/*.js to avoid colliding with the eager test above (same pattern + eager + no import) // Uses ./other/*.js to avoid colliding with the eager test above (same pattern + eager + no import)
const namespaceModules = import.meta.glob('./other/*.js', { const namespaceModules = import.meta.glob('./other/*.js', {
...@@ -116,6 +126,8 @@ it('should include dotfile directories with wildcard patterns', () => { ...@@ -116,6 +126,8 @@ it('should include dotfile directories with wildcard patterns', () => {
'./CaseDir/module-lower.js', './CaseDir/module-lower.js',
'./dir/bar.js', './dir/bar.js',
'./dir/foo.js', './dir/foo.js',
'./linked/bar.js',
'./linked/foo.js',
'./other/baz.js', './other/baz.js',
]) ])
}) })
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment