Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 89 additions & 34 deletions laravel-lsp/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
Expand Down Expand Up @@ -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"];
Expand All @@ -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);
}
}
}
Expand All @@ -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);
}
}
}
Expand All @@ -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);
}
}
}
Expand All @@ -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);
}
}
}
Expand All @@ -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);
}
}
}
Expand Down
195 changes: 195 additions & 0 deletions laravel-lsp/src/tests/component_navigation_containment.rs
Original file line number Diff line number Diff line change
@@ -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 `<x-tag>` 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 = "<?php\nclass 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 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
// `<root>/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"
);
}
Loading