From 58ce9d29d9fdf10778b19e3657df698e3d015a92 Mon Sep 17 00:00:00 2001 From: Mike Bronner Date: Tue, 16 Jun 2026 09:33:37 -0700 Subject: [PATCH 1/2] chore: start work on #148 From 3b41eed68c8bf40ca9c8d4d52e178c5a86fc5c69 Mon Sep 17 00:00:00 2001 From: Mike Bronner Date: Tue, 16 Jun 2026 09:46:01 -0700 Subject: [PATCH 2/2] =?UTF-8?q?fix:=20=F0=9F=94=92=EF=B8=8F=20Enforce=20pa?= =?UTF-8?q?th=5Fwithin=5Froot=20in=20component,=20directive,=20and=20view?= =?UTF-8?q?=20goto-definition.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extend the #130 slot-navigation containment guard to the remaining filesystem-touching goto-definition flows. A loadViewsFrom-style namespace can resolve an absolute path that escapes the project root; these flows previously handed the LSP client a LocationLink pointing outside the root with only a file_exists_cached check. Add a path_within_root(&path, &config.root) guard inside each candidate loop, after the existence check and before building the link, with continue on failure (mirrors the slot-navigation pattern): - create_view_location_from_salsa - resolve_component_existing_file, over the class-backed and PSR-4 candidates component_candidate_paths appends past resolve_component_path's own root filter - create_directive_location_from_salsa, every candidate loop (@component x2, view-first-arg, @includeWhen, @includeFirst, @livewire) Cover each flow with out-of-root, in-root, and under-root-symlink containment tests in the slot_navigation_containment.rs style. Fixes: #148 --- laravel-lsp/src/main.rs | 123 +++++++--- .../tests/component_navigation_containment.rs | 195 ++++++++++++++++ .../tests/directive_navigation_containment.rs | 212 ++++++++++++++++++ laravel-lsp/src/tests/mod.rs | 3 + .../src/tests/view_navigation_containment.rs | 185 +++++++++++++++ 5 files changed, 684 insertions(+), 34 deletions(-) create mode 100644 laravel-lsp/src/tests/component_navigation_containment.rs create mode 100644 laravel-lsp/src/tests/directive_navigation_containment.rs create mode 100644 laravel-lsp/src/tests/view_navigation_containment.rs diff --git a/laravel-lsp/src/main.rs b/laravel-lsp/src/main.rs index 435a195d..3e10676b 100644 --- a/laravel-lsp/src/main.rs +++ b/laravel-lsp/src/main.rs @@ -13809,25 +13809,35 @@ return [ let possible_paths = config.resolve_view_path(&view.name); for path in possible_paths { - if self.file_exists_cached(&path).await { - if let Ok(target_uri) = Url::from_file_path(&path) { - let origin_selection_range = Range { - start: Position { - line: view.line, - character: view.column, - }, - end: Position { - line: view.line, - character: view.end_column, - }, - }; - return Some(GotoDefinitionResponse::Link(vec![LocationLink { - origin_selection_range: Some(origin_selection_range), - target_uri, - target_range: Range::default(), - target_selection_range: Range::default(), - }])); - } + if !self.file_exists_cached(&path).await { + continue; + } + // Containment guard (issue #148, extending #130): a + // `loadViewsFrom(__DIR__ . '/../../etc', 'ns')`-style namespace can + // resolve a view to an absolute path that escapes the project root. + // Refuse to hand the client a navigation target outside the root, + // matching the slot-navigation guard. `continue` rather than + // `return None` so a later in-root candidate can still resolve. + if !path_within_root(&path, &config.root) { + continue; + } + if let Ok(target_uri) = Url::from_file_path(&path) { + let origin_selection_range = Range { + start: Position { + line: view.line, + character: view.column, + }, + end: Position { + line: view.line, + character: view.end_column, + }, + }; + return Some(GotoDefinitionResponse::Link(vec![LocationLink { + origin_selection_range: Some(origin_selection_range), + target_uri, + target_range: Range::default(), + target_selection_range: Range::default(), + }])); } } None @@ -13847,9 +13857,21 @@ return [ let autoload = laravel_lsp::composer_autoload::ComposerAutoload::for_project(&root); for path in laravel_lsp::salsa_impl::component_candidate_paths(name, &config, autoload) { - if self.file_exists_cached(&path).await { - return Some(path); + if !self.file_exists_cached(&path).await { + continue; } + // Containment guard (issue #148, extending #130). `resolve_component_path` + // already filters its own candidates against the root, but + // `component_candidate_paths` appends class-backed + // (`Blade::component('tag', Class::class)`) and PSR-4 `componentNamespace` + // candidates *after* that filter — those can resolve to a class file + // outside the project root. Refuse any out-of-root target here, using + // the same `config.root` the slot-navigation guard does. `continue` so a + // later in-root candidate can still resolve. + if !path_within_root(&path, &config.root) { + continue; + } + return Some(path); } None } @@ -13996,6 +14018,15 @@ return [ let arguments = dir.arguments.as_ref()?; let config = self.get_cached_config().await?; + // Containment guard (issue #148, extending #130): every candidate loop + // below resolves a directive argument to a view/component path through + // `resolve_view_path`, which honours `loadViewsFrom`-style namespaces that + // can point an absolute path outside the project root. Each loop re-checks + // `path_within_root(&path, &config.root)` after the existence check and + // `continue`s past any out-of-root candidate, so no directive flow hands + // the client a navigation target that escapes the root. The `@feature` + // branch builds its path from `root.join(..)` and so is already contained. + // Directives where first argument is a view name let view_directives_first_arg = ["extends", "include", "includeIf", "includeUnless", "each"]; @@ -14011,17 +14042,25 @@ return [ let possible_paths = config.resolve_view_path(&component_path); for path in possible_paths { - if self.file_exists_cached(&path).await { - return self.create_location_link(dir, &path); + if !self.file_exists_cached(&path).await { + continue; } + if !path_within_root(&path, &config.root) { + continue; + } + return self.create_location_link(dir, &path); } // Also try direct view path let possible_paths = config.resolve_view_path(&component_name); for path in possible_paths { - if self.file_exists_cached(&path).await { - return self.create_location_link(dir, &path); + if !self.file_exists_cached(&path).await { + continue; } + if !path_within_root(&path, &config.root) { + continue; + } + return self.create_location_link(dir, &path); } } } @@ -14032,9 +14071,13 @@ return [ let possible_paths = config.resolve_view_path(&view_name); for path in possible_paths { - if self.file_exists_cached(&path).await { - return self.create_location_link(dir, &path); + if !self.file_exists_cached(&path).await { + continue; } + if !path_within_root(&path, &config.root) { + continue; + } + return self.create_location_link(dir, &path); } } } @@ -14045,9 +14088,13 @@ return [ let possible_paths = config.resolve_view_path(&view_name); for path in possible_paths { - if self.file_exists_cached(&path).await { - return self.create_location_link(dir, &path); + if !self.file_exists_cached(&path).await { + continue; + } + if !path_within_root(&path, &config.root) { + continue; } + return self.create_location_link(dir, &path); } } } @@ -14058,9 +14105,13 @@ return [ for view_name in view_names { let possible_paths = config.resolve_view_path(&view_name); for path in possible_paths { - if self.file_exists_cached(&path).await { - return self.create_location_link(dir, &path); + if !self.file_exists_cached(&path).await { + continue; + } + if !path_within_root(&path, &config.root) { + continue; } + return self.create_location_link(dir, &path); } } } @@ -14077,10 +14128,14 @@ return [ let possible_paths = config.resolve_view_path(&component_name); for path in possible_paths { - if self.file_exists_cached(&path).await { - // Use string_column/string_end_column for the clickable range (just the component name) - return self.create_location_link_with_string_range(dir, &path); + if !self.file_exists_cached(&path).await { + continue; + } + if !path_within_root(&path, &config.root) { + continue; } + // Use string_column/string_end_column for the clickable range (just the component name) + return self.create_location_link_with_string_range(dir, &path); } } } diff --git a/laravel-lsp/src/tests/component_navigation_containment.rs b/laravel-lsp/src/tests/component_navigation_containment.rs new file mode 100644 index 00000000..a071f7b5 --- /dev/null +++ b/laravel-lsp/src/tests/component_navigation_containment.rs @@ -0,0 +1,195 @@ +//! Tests for the root-containment guard in +//! `LaravelLanguageServer::resolve_component_existing_file` (issue #148, +//! extending #130). +//! +//! Component go-to-definition resolves a `` to a file via +//! `component_candidate_paths`. `resolve_component_path` already filters *its* +//! candidates against the project root, but `component_candidate_paths` appends +//! class-backed (`Blade::component('tag', Class::class)`) and PSR-4 +//! `componentNamespace` candidates *after* that filter — those can resolve to a +//! class file outside the root. The guard re-checks containment against +//! `config.root` — via the same `path_within_root` the slot-navigation flow uses +//! — before returning the path. These tests register a class-backed component +//! whose file lives outside the root (the unfiltered escape vector) and drive the +//! private async methods directly through `tower_lsp::LspService` / `inner()`. + +use crate::LaravelLanguageServer; +use laravel_lsp::salsa_impl::{ComponentReferenceData, LaravelConfigData}; +use std::collections::HashMap; +use std::fs; +use std::path::{Path, PathBuf}; +use tower_lsp::lsp_types::GotoDefinitionResponse; +use tower_lsp::{lsp_types::Url, LspService}; + +/// The PHP class file that backs the `card` component. Contents are irrelevant +/// to resolution — only that the file exists, so a `None` result can only come +/// from the containment guard, never a missing file. +const CARD_CLASS: &str = " LaravelLanguageServer { + let (service, _socket) = LspService::new(LaravelLanguageServer::new); + service.inner().clone() +} + +/// A minimal config rooted at `root` that registers the `card` tag as a +/// class-backed component (`Blade::component('card', Card::class)`) whose +/// resolved file is `class_file`. `component_candidate_paths` appends this +/// candidate *after* the root-containment filter in `resolve_component_path`, so +/// `class_file` is exactly the unfiltered escape vector the guard must catch. +fn config_with_class_component(root: &Path, class_file: &Path) -> LaravelConfigData { + let mut class_component_files = HashMap::new(); + class_component_files.insert("card".to_string(), class_file.to_path_buf()); + + LaravelConfigData { + root: root.to_path_buf(), + view_paths: vec![root.join("resources/views")], + component_paths: vec![(String::new(), root.join("resources/views/components"))], + livewire_path: None, + has_livewire: false, + view_namespaces: HashMap::new(), + component_namespaces: HashMap::new(), + anonymous_component_paths: HashMap::new(), + anonymous_component_namespaces: HashMap::new(), + component_aliases: HashMap::new(), + icon_aliases: HashMap::new(), + class_component_files, + } +} + +/// A `ComponentReferenceData` for `name` at the document origin — positions are +/// irrelevant to path resolution. +fn component_ref(name: &str) -> ComponentReferenceData { + ComponentReferenceData { + name: name.to_string(), + tag_name: format!("x-{name}"), + line: 0, + column: 0, + end_column: 0, + } +} + +/// Seed `config` as the cached config and set the server's root path — +/// `resolve_component_existing_file` reads `root_path` to build the composer +/// autoload before walking the candidate paths. +async fn seed(server: &LaravelLanguageServer, root: &Path, config: LaravelConfigData) { + *server.cached_config.write().await = Some(config); + *server.root_path.write().await = Some(root.to_path_buf()); +} + +/// Write `contents` to `path`, creating parent directories as needed. +fn write(path: &Path, contents: &str) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, contents).unwrap(); +} + +#[tokio::test] +async fn out_of_root_component_returns_none() { + // The `card` tag is registered to a class file OUTSIDE the project root (the + // shape a vendor `Blade::component('card', \Outside\Card::class)` produces). + // The class file exists on disk, so without the guard + // `resolve_component_existing_file` would return it; the containment guard + // must refuse it on root grounds alone and return None. + let root = tempfile::TempDir::new().unwrap(); + let outside = tempfile::TempDir::new().unwrap(); + + let class_file = outside.path().join("Card.php"); + write(&class_file, CARD_CLASS); + + let server = test_server(); + seed( + &server, + root.path(), + config_with_class_component(root.path(), &class_file), + ) + .await; + + let result = server.resolve_component_existing_file("card").await; + + assert!( + result.is_none(), + "an out-of-root component class must not resolve, even though it exists \ + on disk — the containment guard refuses it" + ); +} + +#[tokio::test] +async fn in_root_component_still_resolves() { + // Positive control: the `card` tag resolves to a class file INSIDE the + // project root, so it passes containment and component navigation resolves + // exactly as before. Assert both the low-level resolver and the public + // `create_component_location_from_salsa` to prove the full flow is intact. + let root = tempfile::TempDir::new().unwrap(); + let class_file = root.path().join("app/View/Components/Card.php"); + write(&class_file, CARD_CLASS); + + let server = test_server(); + seed( + &server, + root.path(), + config_with_class_component(root.path(), &class_file), + ) + .await; + + let resolved = server.resolve_component_existing_file("card").await; + assert_eq!( + resolved.as_deref(), + Some(class_file.as_path()), + "an in-root component class must resolve to its file" + ); + + let Some(GotoDefinitionResponse::Link(links)) = server + .create_component_location_from_salsa(&component_ref("card")) + .await + else { + panic!("an in-root component must resolve to a Link definition response"); + }; + assert_eq!(links.len(), 1, "exactly one definition link is expected"); + assert_eq!( + links[0].target_uri, + Url::from_file_path(&class_file).unwrap(), + "the definition must point at the in-root component class" + ); +} + +#[cfg(unix)] +#[tokio::test] +async fn under_root_symlink_to_outside_target_returns_none() { + // The discriminating case a lexical guard could not catch: the registered + // class file lives *under* the project root — reached through a symlink at + // `/linked` — yet canonicalizes to a file OUTSIDE the root. The file + // exists through the link, so a missing file can't explain a None result. + // Only canonicalization — `path_within_root` resolving the symlink to its + // out-of-tree target — can reject it. + let root = tempfile::TempDir::new().unwrap(); + let outside = tempfile::TempDir::new().unwrap(); + + // Real class file, outside the project root. + let target_dir = outside.path().join("app/View/Components"); + write(&target_dir.join("Card.php"), CARD_CLASS); + + // Symlink under the root that points at the outside components directory. + let link: PathBuf = root.path().join("linked"); + std::os::unix::fs::symlink(&target_dir, &link).unwrap(); + + let server = test_server(); + // Register the class file at the in-root symlink path so resolution is + // lexically inside the root; only canonicalization reveals the escape. + seed( + &server, + root.path(), + config_with_class_component(root.path(), &link.join("Card.php")), + ) + .await; + + let result = server.resolve_component_existing_file("card").await; + + assert!( + result.is_none(), + "a component class reached through an under-root symlink that resolves \ + outside the project root must not resolve — the canonicalize-based \ + containment guard refuses it even though the link path is lexically inside" + ); +} diff --git a/laravel-lsp/src/tests/directive_navigation_containment.rs b/laravel-lsp/src/tests/directive_navigation_containment.rs new file mode 100644 index 00000000..872960fd --- /dev/null +++ b/laravel-lsp/src/tests/directive_navigation_containment.rs @@ -0,0 +1,212 @@ +//! Tests for the root-containment guard in +//! `LaravelLanguageServer::create_directive_location_from_salsa` (issue #148, +//! extending #130). +//! +//! Blade directive go-to-definition (`@extends`/`@include`/`@includeWhen`/ +//! `@includeFirst`/`@component`/`@livewire`) resolves the directive's view +//! argument through `resolve_view_path`, which honours `loadViewsFrom`-style +//! namespaces. A `loadViewsFrom(__DIR__ . '/../../etc', 'pkg')`-style +//! registration can map a namespace to an absolute directory that escapes the +//! project root, so `@include('pkg::card')` would otherwise hand the LSP client +//! a `LocationLink` pointing outside the root. Every candidate loop re-checks +//! containment against `config.root` — via the same `path_within_root` the +//! slot-navigation flow uses — before building the link. These tests cover a +//! view directive (`@include`) and the `@livewire` directive, driving the +//! private async method directly through `tower_lsp::LspService` / `inner()`. + +use crate::LaravelLanguageServer; +use laravel_lsp::salsa_impl::{DirectiveReferenceData, LaravelConfigData}; +use std::collections::HashMap; +use std::fs; +use std::path::{Path, PathBuf}; +use tower_lsp::lsp_types::GotoDefinitionResponse; +use tower_lsp::{lsp_types::Url, LspService}; + +/// The Blade view that backs `pkg::card`. Contents are irrelevant to +/// resolution — only that the file exists, so a `None` result can only come from +/// the containment guard, never a missing file. +const CARD_VIEW: &str = "
card
\n"; + +/// Build a server instance for testing. `LspService::new` wires up a real +/// `Client`; `inner()` hands back the `LaravelLanguageServer` so we can call its +/// private methods directly. +fn test_server() -> LaravelLanguageServer { + let (service, _socket) = LspService::new(LaravelLanguageServer::new); + service.inner().clone() +} + +/// A minimal config rooted at `root` that registers `pkg` as a `loadViewsFrom` +/// -style view namespace pointing at `namespace_dir`. With this, +/// `@include('pkg::card')` resolves to `{namespace_dir}/card.blade.php`, letting +/// the test place that directory inside or outside the project root at will. +fn config_with_view_namespace(root: &Path, namespace_dir: &Path) -> LaravelConfigData { + let mut view_namespaces = HashMap::new(); + view_namespaces.insert("pkg".to_string(), namespace_dir.to_path_buf()); + + LaravelConfigData { + root: root.to_path_buf(), + view_paths: vec![root.join("resources/views")], + component_paths: vec![(String::new(), root.join("resources/views/components"))], + livewire_path: None, + has_livewire: false, + view_namespaces, + component_namespaces: HashMap::new(), + anonymous_component_paths: HashMap::new(), + anonymous_component_namespaces: HashMap::new(), + component_aliases: HashMap::new(), + icon_aliases: HashMap::new(), + class_component_files: HashMap::new(), + } +} + +/// A `DirectiveReferenceData` for `@{name}('{view}')` at the document origin. +/// `string_column`/`string_end_column` span the quoted view name so the +/// `@livewire` flow's `create_location_link_with_string_range` has a valid +/// clickable range; positions are otherwise irrelevant to path resolution. +fn directive_ref(name: &str, view: &str) -> DirectiveReferenceData { + DirectiveReferenceData { + name: name.to_string(), + arguments: Some(format!("'{view}'")), + line: 0, + column: 0, + end_column: (name.len() + view.len() + 4) as u32, + string_column: (name.len() + 3) as u32, + string_end_column: (name.len() + 3 + view.len()) as u32, + } +} + +/// Seed `config` as the cached config so `get_cached_config` returns it without +/// touching Salsa. +async fn seed(server: &LaravelLanguageServer, config: LaravelConfigData) { + *server.cached_config.write().await = Some(config); +} + +/// Write `contents` to `path`, creating parent directories as needed. +fn write(path: &Path, contents: &str) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, contents).unwrap(); +} + +#[tokio::test] +async fn out_of_root_include_directive_returns_none() { + // `@include('pkg::card')` where the `pkg` namespace points OUTSIDE the + // project root. The resolved `card` view exists on disk, so without the guard + // the view-directive loop would hand back a LocationLink pointing outside the + // root; the containment guard must refuse it and return None. + let root = tempfile::TempDir::new().unwrap(); + let outside = tempfile::TempDir::new().unwrap(); + + write(&outside.path().join("card.blade.php"), CARD_VIEW); + + let server = test_server(); + seed( + &server, + config_with_view_namespace(root.path(), outside.path()), + ) + .await; + + let result = server + .create_directive_location_from_salsa(&directive_ref("include", "pkg::card")) + .await; + + assert!( + result.is_none(), + "an out-of-root @include target must not resolve, even though it exists \ + on disk — the containment guard refuses it" + ); +} + +#[tokio::test] +async fn out_of_root_livewire_directive_returns_none() { + // `@livewire('pkg::card')` exercises the separate `@livewire` candidate loop + // (which builds its link via `create_location_link_with_string_range`). With + // the `pkg` namespace pointing outside the root, the resolved view exists but + // must be refused on containment grounds. + let root = tempfile::TempDir::new().unwrap(); + let outside = tempfile::TempDir::new().unwrap(); + + write(&outside.path().join("card.blade.php"), CARD_VIEW); + + let server = test_server(); + seed( + &server, + config_with_view_namespace(root.path(), outside.path()), + ) + .await; + + let result = server + .create_directive_location_from_salsa(&directive_ref("livewire", "pkg::card")) + .await; + + assert!( + result.is_none(), + "an out-of-root @livewire target must not resolve, even though it exists \ + on disk — the containment guard refuses it" + ); +} + +#[tokio::test] +async fn in_root_include_directive_still_resolves() { + // Positive control: the `pkg` namespace points INSIDE the project root, so + // `@include('pkg::card')` passes containment and directive navigation + // resolves exactly as before — no regression. + let root = tempfile::TempDir::new().unwrap(); + let namespace_dir = root.path().join("packages/pkg/resources/views"); + + let card = namespace_dir.join("card.blade.php"); + write(&card, CARD_VIEW); + + let server = test_server(); + seed( + &server, + config_with_view_namespace(root.path(), &namespace_dir), + ) + .await; + + let result = server + .create_directive_location_from_salsa(&directive_ref("include", "pkg::card")) + .await; + + let Some(GotoDefinitionResponse::Link(links)) = result else { + panic!("an in-root @include must resolve to a Link definition response"); + }; + assert_eq!(links.len(), 1, "exactly one definition link is expected"); + assert_eq!( + links[0].target_uri, + Url::from_file_path(&card).unwrap(), + "the definition must point at the in-root card view" + ); +} + +#[cfg(unix)] +#[tokio::test] +async fn under_root_symlink_to_outside_target_returns_none() { + // The discriminating case a lexical guard could not catch: the namespace + // directory lives *under* the project root — a symlink at `/linked-views` + // — yet resolves to a directory OUTSIDE the root. The `card` view exists + // through the link, so a missing file can't explain a None result. Only + // canonicalization — `path_within_root` resolving the symlink to its + // out-of-tree target — can reject it. + let root = tempfile::TempDir::new().unwrap(); + let outside = tempfile::TempDir::new().unwrap(); + + let target_dir = outside.path().join("resources/views"); + write(&target_dir.join("card.blade.php"), CARD_VIEW); + + let link: PathBuf = root.path().join("linked-views"); + std::os::unix::fs::symlink(&target_dir, &link).unwrap(); + + let server = test_server(); + seed(&server, config_with_view_namespace(root.path(), &link)).await; + + let result = server + .create_directive_location_from_salsa(&directive_ref("include", "pkg::card")) + .await; + + assert!( + result.is_none(), + "an @include reached through an under-root symlink that resolves outside \ + the project root must not resolve — the canonicalize-based containment \ + guard refuses it even though the link path is lexically inside" + ); +} diff --git a/laravel-lsp/src/tests/mod.rs b/laravel-lsp/src/tests/mod.rs index 28285232..dd7a0364 100644 --- a/laravel-lsp/src/tests/mod.rs +++ b/laravel-lsp/src/tests/mod.rs @@ -5,7 +5,9 @@ mod blade_var_rename_handler; mod cast_type_context; mod class_locator_and_properties; mod code_lens_opt_in; +mod component_navigation_containment; mod diagnostic_severity; +mod directive_navigation_containment; mod dynamic_where_sparseness; mod flux_component_context; mod flux_component_hover; @@ -24,4 +26,5 @@ mod routes_dir_gate; mod slot_navigation_containment; mod slot_variable_resolution; mod translation_namespace_check; +mod view_navigation_containment; mod vite_completion_context; diff --git a/laravel-lsp/src/tests/view_navigation_containment.rs b/laravel-lsp/src/tests/view_navigation_containment.rs new file mode 100644 index 00000000..678aecfb --- /dev/null +++ b/laravel-lsp/src/tests/view_navigation_containment.rs @@ -0,0 +1,185 @@ +//! Tests for the root-containment guard in +//! `LaravelLanguageServer::create_view_location_from_salsa` (issue #148, +//! extending #130). +//! +//! View go-to-definition resolves a `view('ns::name')` reference through +//! `resolve_view_path`, which honours `loadViewsFrom`-style namespaces. A +//! `loadViewsFrom(__DIR__ . '/../../etc', 'pkg')`-style registration can map a +//! namespace to an absolute directory that escapes the project root, so a +//! `pkg::card` reference would otherwise hand the LSP client a `LocationLink` +//! pointing outside the root. The guard re-checks containment against +//! `config.root` — via the same `path_within_root` the slot-navigation, Folio +//! cursor, and blade-var rename flows use — before building the link. These +//! tests drive the private async method directly by building the server through +//! `tower_lsp::LspService` and reaching its inner value with `inner()`. + +use crate::LaravelLanguageServer; +use laravel_lsp::salsa_impl::{LaravelConfigData, ViewReferenceData}; +use std::collections::HashMap; +use std::fs; +use std::path::{Path, PathBuf}; +use tower_lsp::lsp_types::GotoDefinitionResponse; +use tower_lsp::{lsp_types::Url, LspService}; + +/// The Blade view that backs `pkg::card`. Its contents are irrelevant to +/// resolution — only that the file exists on disk, so a `None` result can only +/// come from the containment guard, never a missing file. +const CARD_VIEW: &str = "
card
\n"; + +/// Build a server instance for testing. `LspService::new` wires up a real +/// `Client`; `inner()` hands back the `LaravelLanguageServer` so we can call its +/// private methods directly. +fn test_server() -> LaravelLanguageServer { + let (service, _socket) = LspService::new(LaravelLanguageServer::new); + service.inner().clone() +} + +/// A minimal config rooted at `root` that registers `pkg` as a `loadViewsFrom` +/// -style view namespace pointing at `namespace_dir`. With this, `pkg::card` +/// resolves to `{namespace_dir}/card.blade.php`, letting the test place that +/// directory inside or outside the project root at will. +fn config_with_view_namespace(root: &Path, namespace_dir: &Path) -> LaravelConfigData { + let mut view_namespaces = HashMap::new(); + view_namespaces.insert("pkg".to_string(), namespace_dir.to_path_buf()); + + LaravelConfigData { + root: root.to_path_buf(), + view_paths: vec![root.join("resources/views")], + component_paths: vec![(String::new(), root.join("resources/views/components"))], + livewire_path: None, + has_livewire: false, + view_namespaces, + component_namespaces: HashMap::new(), + anonymous_component_paths: HashMap::new(), + anonymous_component_namespaces: HashMap::new(), + component_aliases: HashMap::new(), + icon_aliases: HashMap::new(), + class_component_files: HashMap::new(), + } +} + +/// A `ViewReferenceData` for `name` at the document origin — positions are +/// irrelevant to path resolution. +fn view_ref(name: &str) -> ViewReferenceData { + ViewReferenceData { + name: name.to_string(), + line: 0, + column: 0, + end_column: 0, + is_route_view: false, + } +} + +/// Seed `config` as the cached config so `get_cached_config` returns it without +/// touching Salsa. +async fn seed(server: &LaravelLanguageServer, config: LaravelConfigData) { + *server.cached_config.write().await = Some(config); +} + +/// Write `contents` to `path`, creating parent directories as needed. +fn write(path: &Path, contents: &str) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, contents).unwrap(); +} + +#[tokio::test] +async fn out_of_root_view_returns_none() { + // The `pkg` namespace points OUTSIDE the project root (the shape a + // `loadViewsFrom(__DIR__ . '/../../etc', 'pkg')` produces). The resolved + // `card` view exists on disk, so without the guard + // `create_view_location_from_salsa` would hand back a LocationLink pointing + // outside the root; the containment guard must refuse it on root grounds + // alone and return None. + let root = tempfile::TempDir::new().unwrap(); + let outside = tempfile::TempDir::new().unwrap(); + + write(&outside.path().join("card.blade.php"), CARD_VIEW); + + let server = test_server(); + seed( + &server, + config_with_view_namespace(root.path(), outside.path()), + ) + .await; + + let result = server + .create_view_location_from_salsa(&view_ref("pkg::card")) + .await; + + assert!( + result.is_none(), + "an out-of-root view must not resolve, even though it exists on disk — \ + the containment guard refuses it" + ); +} + +#[tokio::test] +async fn in_root_view_still_resolves() { + // Positive control: the `pkg` namespace points to a directory INSIDE the + // project root, so the resolved `card` view passes containment and view + // navigation resolves exactly as before — no regression. + let root = tempfile::TempDir::new().unwrap(); + let namespace_dir = root.path().join("packages/pkg/resources/views"); + + let card = namespace_dir.join("card.blade.php"); + write(&card, CARD_VIEW); + + let server = test_server(); + seed( + &server, + config_with_view_namespace(root.path(), &namespace_dir), + ) + .await; + + let result = server + .create_view_location_from_salsa(&view_ref("pkg::card")) + .await; + + let Some(GotoDefinitionResponse::Link(links)) = result else { + panic!("an in-root view must resolve to a Link definition response"); + }; + assert_eq!(links.len(), 1, "exactly one definition link is expected"); + assert_eq!( + links[0].target_uri, + Url::from_file_path(&card).unwrap(), + "the definition must point at the in-root card view" + ); +} + +#[cfg(unix)] +#[tokio::test] +async fn under_root_symlink_to_outside_target_returns_none() { + // The discriminating case a lexical guard could not catch: the namespace + // directory lives *under* the project root — a symlink at + // `/linked-views` — yet it resolves to a directory OUTSIDE the root. + // The `card` view exists through the link, so a missing file can't explain a + // None result. A purely lexical `starts_with` check would admit the path + // (the link is under the root); only canonicalization — `path_within_root` + // resolving the symlink to its out-of-tree target — can reject it. + let root = tempfile::TempDir::new().unwrap(); + let outside = tempfile::TempDir::new().unwrap(); + + // Real view file, outside the project root. + let target_dir = outside.path().join("resources/views"); + write(&target_dir.join("card.blade.php"), CARD_VIEW); + + // Symlink under the root that points at the outside views directory. + let link: PathBuf = root.path().join("linked-views"); + std::os::unix::fs::symlink(&target_dir, &link).unwrap(); + + let server = test_server(); + // Register the namespace at the in-root symlink path so resolution is + // lexically inside the root; only canonicalization reveals the escape. + seed(&server, config_with_view_namespace(root.path(), &link)).await; + + let result = server + .create_view_location_from_salsa(&view_ref("pkg::card")) + .await; + + assert!( + result.is_none(), + "a view reached through an under-root symlink that resolves outside the \ + project root must not resolve — the canonicalize-based containment guard \ + refuses it even though the link path is lexically inside" + ); +}