Skip to content

Commit 3a8ca39

Browse files
committed
feat: Add Path::isWithin() to check containment within a base directory
Lexical segment-wise check with the base defaulting to the current working directory, so a bare isWithin() call doubles as a path-traversal guard for user input (analogous to Go's filepath.IsLocal). A path equal to the base counts as within it. Assisted-By: Claude Fable 5 <noreply@anthropic.com>
1 parent 1d69465 commit 3a8ca39

2 files changed

Lines changed: 191 additions & 0 deletions

File tree

‎src/Path.php‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,42 @@ public function tryRelative(self|string $base): ?self
319319
return self::create($parts === [] ? '.' : \implode(self::DS, $parts));
320320
}
321321

322+
/**
323+
* Check whether this path is located inside the given base directory.
324+
*
325+
* The check is lexical: both paths are resolved to absolute form and compared
326+
* segment by segment, the filesystem is not accessed. A path equal to the base
327+
* is considered within it. Case sensitivity follows the OS: case-insensitive
328+
* on Windows, case-sensitive on Unix.
329+
*
330+
* With the default base `.` the method answers whether the path stays inside
331+
* the current working directory, which makes it a convenient guard against
332+
* path traversal in user input.
333+
*
334+
* @param self|non-empty-string $base Base directory to check against.
335+
* Defaults to the current working directory. A relative base is
336+
* resolved against the current working directory first.
337+
*
338+
* @throws \RuntimeException If current working directory cannot be determined.
339+
*/
340+
public function isWithin(self|string $base = '.'): bool
341+
{
342+
$thisParts = self::segments($this->absolute()->path);
343+
$baseParts = self::segments(self::create($base)->absolute()->path);
344+
345+
if (\count($baseParts) > \count($thisParts)) {
346+
return false;
347+
}
348+
349+
foreach ($baseParts as $i => $segment) {
350+
if (!self::sameSegment($thisParts[$i], $segment)) {
351+
return false;
352+
}
353+
}
354+
355+
return true;
356+
}
357+
322358
/**
323359
* Match the path against a pattern using shell wildcard pattern matching.
324360
*

‎tests/Unit/PathTest.php‎

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,90 @@ public static function provideTryRelativeUnrelatedRoots(): \Generator
185185
];
186186
}
187187

188+
public static function provideIsWithin(): \Generator
189+
{
190+
$isWindows = \DIRECTORY_SEPARATOR === '\\';
191+
$root = $isWindows ? 'C:' : '';
192+
193+
yield 'path directly in base' => [
194+
'path' => "$root/var/www/app/file.php",
195+
'base' => "$root/var/www/app",
196+
'expected' => true,
197+
];
198+
199+
yield 'path deep inside base' => [
200+
'path' => "$root/var/www/app/src/deep/file.php",
201+
'base' => "$root/var/www/app",
202+
'expected' => true,
203+
];
204+
205+
yield 'path equals base' => [
206+
'path' => "$root/var/www/app",
207+
'base' => "$root/var/www/app",
208+
'expected' => true,
209+
];
210+
211+
yield 'sibling directory' => [
212+
'path' => "$root/var/www/other",
213+
'base' => "$root/var/www/app",
214+
'expected' => false,
215+
];
216+
217+
yield 'parent of base' => [
218+
'path' => "$root/var/www",
219+
'base' => "$root/var/www/app",
220+
'expected' => false,
221+
];
222+
223+
yield 'partially matching segment' => [
224+
'path' => "$root/var/www-old",
225+
'base' => "$root/var/www",
226+
'expected' => false,
227+
];
228+
229+
yield 'partially matching segment with children' => [
230+
'path' => "$root/var/www-old/app/file.php",
231+
'base' => "$root/var/www",
232+
'expected' => false,
233+
];
234+
235+
yield 'base is root' => [
236+
'path' => "$root/var/www/app",
237+
'base' => "$root/",
238+
'expected' => true,
239+
];
240+
241+
yield 'root is within root' => [
242+
'path' => "$root/",
243+
'base' => "$root/",
244+
'expected' => true,
245+
];
246+
247+
yield 'root is not within nested base' => [
248+
'path' => "$root/",
249+
'base' => "$root/var",
250+
'expected' => false,
251+
];
252+
253+
yield 'different windows drives' => [
254+
'path' => 'D:/var/www/app',
255+
'base' => 'C:/var/www',
256+
'expected' => false,
257+
];
258+
259+
yield 'unix root against windows drive' => [
260+
'path' => '/var/www/app',
261+
'base' => 'C:/var/www',
262+
'expected' => false,
263+
];
264+
265+
yield 'windows drive against unix root' => [
266+
'path' => 'C:/var/www/app',
267+
'base' => '/var/www',
268+
'expected' => false,
269+
];
270+
}
271+
188272
public function testCreateReturnsPathInstance(): void
189273
{
190274
$path = Path::create('test/path');
@@ -747,4 +831,75 @@ public function testTryRelativeResultJoinedBackToBaseGivesOriginalPath(): void
747831
Assert::same((string) $base->join($result), (string) $path);
748832
}
749833

834+
/**
835+
* @param non-empty-string $path
836+
* @param non-empty-string $base
837+
*/
838+
#[DataProvider('provideIsWithin')]
839+
public function testIsWithin(string $path, string $base, bool $expected): void
840+
{
841+
$result = Path::create($path)->isWithin($base);
842+
843+
Assert::same($result, $expected, "Path '$path' should " . ($expected ? '' : 'not ') . "be within '$base'");
844+
}
845+
846+
public function testIsWithinWithPathObjectAsBase(): void
847+
{
848+
$isWindows = DIRECTORY_SEPARATOR === '\\';
849+
$base = Path::create($isWindows ? 'C:/var/www/app' : '/var/www/app');
850+
$inside = Path::create($isWindows ? 'C:/var/www/app/src/file.php' : '/var/www/app/src/file.php');
851+
$outside = Path::create($isWindows ? 'C:/var/www/other' : '/var/www/other');
852+
853+
Assert::true($inside->isWithin($base));
854+
Assert::false($outside->isWithin($base));
855+
}
856+
857+
public function testIsWithinDefaultBaseIsCurrentDirectory(): void
858+
{
859+
$relativeInside = Path::create('src/Path.php');
860+
$currentDir = Path::create('.');
861+
$traversal = Path::create('../outside/file.php');
862+
863+
Assert::true($relativeInside->isWithin(), 'Relative path should be within the current directory');
864+
Assert::true($currentDir->isWithin(), 'Current directory should be within itself');
865+
Assert::false($traversal->isWithin(), 'Path traversal should not be within the current directory');
866+
}
867+
868+
public function testIsWithinDefaultBaseForAbsolutePath(): void
869+
{
870+
$cwd = \getcwd();
871+
$cwd === false and throw new SkipTest('Cannot get current working directory');
872+
873+
$inside = Path::create($cwd)->join('src', 'Path.php');
874+
$outside = Path::create($cwd)->parent()->join('definitely-outside');
875+
876+
Assert::true($inside->isWithin());
877+
Assert::false($outside->isWithin());
878+
}
879+
880+
public function testIsWithinWithRelativeBaseResolvesAgainstCwd(): void
881+
{
882+
$cwd = \getcwd();
883+
$cwd === false and throw new SkipTest('Cannot get current working directory');
884+
885+
$path = Path::create($cwd)->join('project', 'app', 'src', 'file.php');
886+
887+
Assert::true($path->isWithin('project/app'));
888+
Assert::false($path->isWithin('project/other'));
889+
}
890+
891+
public function testIsWithinIsCaseSensitiveDependingOnOs(): void
892+
{
893+
$isWindows = DIRECTORY_SEPARATOR === '\\';
894+
$path = Path::create($isWindows ? 'C:/var/WWW/app' : '/var/WWW/app');
895+
$base = $isWindows ? 'C:/var/www' : '/var/www';
896+
897+
$result = $path->isWithin($base);
898+
899+
if ($isWindows) {
900+
Assert::true($result, 'On Windows, segment comparison is case-insensitive');
901+
} else {
902+
Assert::false($result, 'On Unix, segment comparison is case-sensitive');
903+
}
904+
}
750905
}

0 commit comments

Comments
 (0)