Skip to content

Add contains() to check whether a given path exists in a base path - #376

Merged
thekid merged 6 commits into
xp-framework:mainfrom
thekid:feature/path-contains
Nov 22, 2026
Merged

thekid merged 6 commits into
xp-framework:mainfrom
thekid:feature/path-contains

Conversation

@thekid

@thekid thekid commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Use realpath semantics to verify a given path is inside a base path, expanding links while resolving the path.

Example

use io\Path;
use util\cmd\Console;

$base= new Path('/home/example');
$file= new Path($argv[1]);

Console::writeLine($file, ' in ', $base, ' ? ', $base->contains($file));
  • ✅ /home/example
  • ✅ /home/example/README.md
  • ⛔ /home
  • ⛔ /usr/bin
  • ⛔ /home/example/symlink-to-parent (-> ..)

@thekid

thekid commented Nov 22, 2026 •

Copy link
Copy Markdown
Member Author

From https://gist.github.com/thekid/404eb8e1817d6316aef1e89870a9a40e:

diff --git a/LocalFiles.class.php b/LocalFiles.class.php
index a23580a..28cd662 100755
--- a/LocalFiles.class.php
+++ b/LocalFiles.class.php
@@ -8,13 +8,13 @@ class LocalFiles {

   /** @param string|io.Path $base */
   public function __construct($base) {
-    $this->base= $base instanceof Path ? (string)$base->asRealpath() : realpath($base);
+    $this->base= $base instanceof Path ? $base : new Path($base);
   }

   /** @throws lang.IllegalAccessException */
   public function resolve(string $path): Path {
-    $resolved= (new Path($path))->asRealpath($this->base);
-    if (0 !== strncmp($this->base, $resolved, strlen($this->base))) {
+    $resolved= Path::real($path, $this->base);
+    if (!$this->base->contains($resolved)) {
       throw new IllegalAccessException('Path '.$resolved.' outside of '.$this->base);
     }
     return $resolved;

👉 Inside resolve(), new Path($this->base, $path) would have worked, too, but we want the path to be resolved when it is returned.

@thekid

thekid commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

This should be backported to XP12

@thekid
thekid merged commit a300528 into xp-framework:main Nov 22, 2026
14 checks passed
thekid added a commit that referenced this pull request Nov 22, 2026
@thekid

thekid commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant