Skip to content
Draft
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
17 changes: 14 additions & 3 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,24 @@ const fs = require("fs");
* whose name matches one of the entries in `name`. Stops at `parent`.
*
* @param {string} parent - Root of the workspace (walk stops here).
* @param {string} directory - Relative directory to start from.
* @param {string} directory - Relative directory to start from (must be within parent).
* @param {string|string[]} name - File name(s) to look for.
* @returns {string|null} Absolute path to the first matching file, or null.
*/
function findFiles(parent, directory, name) {
const names = [].concat(name);
const chunks = path.resolve(parent, directory).split(path.sep);
const resolvedParent = path.resolve(parent);
const resolvedStart = path.resolve(parent, directory);

// Guard: if the resolved start path is outside parent (e.g. cross-drive path
// on Windows produced by path.relative between different drives), there is
// nothing to find within the workspace boundary β€” return null immediately.
if (resolvedStart !== resolvedParent &&
!resolvedStart.startsWith(resolvedParent + path.sep)) {
return null;
}

const chunks = resolvedStart.split(path.sep);

while (chunks.length) {
let currentDir = chunks.join(path.sep);
Expand All @@ -23,7 +34,7 @@ function findFiles(parent, directory, name) {
return filePath;
}
}
if (parent === currentDir) {
if (resolvedParent === currentDir) {
break;
}
chunks.pop();
Expand Down
13 changes: 13 additions & 0 deletions test/unit.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,19 @@ describe("findFiles", () => {
assert.equal(result, null);
});

test("returns null when directory is outside parent (simulated cross-drive path)", () => {
// Simulate what happens when path.relative() returns an absolute path
// (e.g. Windows cross-drive: path.relative("C:\\ws", "D:\\other") -> "D:\\other").
// findFiles should return null immediately without walking outside parent.
mkFile("outside-guard", "phpcs.xml");
// Pass an absolute path as `directory` that is not within parent.
const outsideDir = path.join(tmpRoot, "outside-guard");
const unrelatedParent = path.join(tmpRoot, "unrelated-parent");
fs.mkdirSync(unrelatedParent, { recursive: true });
const result = findFiles(unrelatedParent, outsideDir, "phpcs.xml");
assert.equal(result, null);
});

test("handles a single-segment directory (file at root)", () => {
const expected = mkFile("single", "phpcs.xml");
const result = findFiles(path.join(tmpRoot, "single"), ".", "phpcs.xml");
Expand Down