CVE-2022-2400 (PHP, published 2022-07-18T15:15Z)
Description: value: External Control of File Name or Path in GitHub repository dompdf/dompdf prior to 2.0.0.
Severity: nan (CVSS v3 base score: 5.3)
Weakness: CWE-73 \u2014 External Control of File Name or Path
The product allows user input to control or influence paths or file names that are used in filesystem operations.
Repository: https://github.com/dompdf/dompdf
Files changed:
src/Css/Stylesheet.php
src/Dompdf.php
src/FontMetrics.php
src/FrameDecorator/Image.php
src/Helpers.php
src/Image/Cache.php
src/Options.php
src/Renderer/AbstractRenderer.php
tests/Css/StyleTest.php
tests/HelpersTest.php
tests/OptionsTest.php
Commit message: Update resource URI validation and handling

URI scheme (protocol) validation rules are now specified through the Options class. By default file and http(s) URIs are allowed and validation rules defined. Validation rules for PHAR URIs are defined but the scheme is not enabled by default.

Resource retrieval has been updated to use file_get_contents for schemes other than http(s).

fixes #621
fixes #2826

in lieu of #1903


Vulnerable code:
            $parsed_url = Helpers::explode_url($file);

            [$this->_protocol, $this->_base_host, $this->_base_path, $filename] = $parsed_url;
            $file = Helpers::build_url($this->_protocol, $this->_base_host, $this->_base_path, $filename);
            $options = $this->_dompdf->getOptions();
            // Download the remote file
            if (!$options->isRemoteEnabled() && ($this->_protocol !== "" && $this->_protocol !== "file://")) {
                Helpers::record_warnings(E_USER_WARNING, "Remote CSS resource '$file' referenced, but remote file download is disabled.", __FILE__, __LINE__);
                return;
            }
            if ($this->_protocol === "" || $this->_protocol === "file://") {
                $realfile = realpath($file);

                $rootDir = realpath($options->getRootDir());
                if (strpos($realfile, $rootDir) !== 0) {
                    $chroot = $options->getChroot();
                    $chrootValid = false;
                    foreach ($chroot as $chrootPath) {
                        $chrootPath = realpath($chrootPath);
                        if ($chrootPath !== false && strpos($realfile, $chrootPath) === 0) {
                            $chrootValid = true;
                            break;
                        }
                    }
                    if ($chrootValid !== true) {
                        Helpers::record_warnings(E_USER_WARNING, "Permission denied on $file. The file could not be found under the paths specified by Options::chroot.", __FILE__, __LINE__);

                if (!$realfile) {
                    Helpers::record_warnings(E_USER_WARNING, "File '$realfile' not found.", __FILE__, __LINE__);
                    return;
                }

                $file = $realfile;
            

            $parsed_url = Helpers::explode_url($val);
            if (($parsed_url["protocol"] === "" || $parsed_url["protocol"] === "file://") && ($this->_protocol === "" || $this->_protocol === "file://")) {
                $path = realpath($path);
                // If realpath returns FALSE then specifically state that there is no background image
                if ($path === false) {
                    $path = "none";
                }
            $url = $this->resolve_url($url);

            $this->load_css_file($url);
        return $rootDir . self::DEFAULT_STYLESHEET;
    /**
    * Protocol whitelist
    *
    * Protocols and PHP wrappers allowed in URLs. Full support is not
    * guaranteed for the protocols/wrappers contained in this array.
    *
    * @var array
    */
    private $allowedProtocols = ["", "file://", "http://", "https://"];

        if (file_exists($versionFile) && ($version = trim(file_get_contents($versionFile))) !== false && $version !== '$Format:<%h>$') {
            $this->version = sprintf('dompdf %s', $version);
        
        if (!in_array($protocol, $this->allowedProtocols, true)) {
        if (!$this->options->isRemoteEnabled() && ($protocol !== "" && $protocol !== "file://")) {
            throw new Exception("Remote file requested, but remote file download is disabled.");
        }

        if ($protocol === "" || $protocol === "file://") {
            $realfile = realpath($uri);

            $chroot = $this->options->getChroot();
            $chrootValid = false;
            foreach ($chroot as $chrootPath) {
                $chrootPath = realpath($chrootPath);
                if ($chrootPath !== false && strpos($realfile, $chrootPath) === 0) {
                    $chrootValid = true;
                    break;
                }
            }
            if ($chrootValid !== true) {
                throw new Exception("Permission denied on $file. The file could not be found under the paths specified by Options::chroot.");
            }

            $ext = strtolower(pathinfo($realfile, PATHINFO_EXTENSION));
                throw new Exception("Permission denied on $file. This file extension is forbidden");
            if (!$realfile) {
                throw new Exception("File '$file' not found.");

            $uri = $realfile;
                        $this->css->load_css_file($url, Stylesheet::ORIG_AUTHOR);
        if (!$this->options->isRemoteEnabled() && ($protocol !== "" && $protocol !== "file://")) {
            Helpers::record_warnings(E_USER_WARNING, "Remote font resource $remoteFile referenced, but remote file download is disabled.", __FILE__, __LINE__);
            return false;
        if ($protocol === "" || $protocol === "file://") {
            $realfile = realpath($remoteFile);

            $rootDir = realpath($this->options->getRootDir());
            if (strpos($realfile, $rootDir) !== 0) {
                $chroot = $this->options->getChroot();
                $chrootValid = false;
                foreach ($chroot as $chrootPath) {
                    $chrootPath = realpath($chrootPath);
                    if ($chrootPath !== false && strpos($realfile, $chrootPath) === 0) {
                        $chrootValid = true;
                        break;
                    }
                }
                if ($chrootValid !== true) {
                    Helpers::record_warnings(E_USER_WARNING, "Permission denied on $remoteFile. The file could not be found under the paths specified by Options::chroot.", __FILE__, __LINE__);
                    return false;
                }
            }
            if (!$realfile) {
                Helpers::record_warnings(E_USER_WARNING, "File '$realfile' not found.", __FILE__, __LINE__);
                return false;

            $remoteFile = $realfile;
            $dompdf
            //return $protocol . $host . rtrim($base_path, "/\\") . "/";
            return $protocol . $host . $base_path;
        if ((mb_strpos($url, "://") !== false && substr($url, 0, 7) !== "file://") || mb_substr($url, 0, 1) === "#" || mb_strpos($url, "data:") === 0 || mb_strpos($url, "mailto:") === 0 || mb_strpos($url, "tel:") === 0) {
        if (strpos($url, "file://") === 0) {
            $protocol = "";
        if ($protocol !== "file://") {
            $ret = $protocol;
        }
        if (!in_array(mb_strtolower($protocol), ["http://", "https://", "ftp://", "ftps://"], true)) {
        // Exclude windows drive letters...
        if (isset($arr["scheme"]) && $arr["scheme"] !== "file" && strlen($arr["scheme"]) > 1) {
            $i = mb_stripos($url, "file://");
            if ($i !== false) {
                $url = mb_substr($url, $i + 7);
            }

            $protocol = ""; // "file://"; ? why doesn't this work... It's because of
            // network filenames like //COMPU/SHARENAME

            $file = basename($url);

            $path = dirname($url);

            // Check that the path exists
            if ($path !== false) {
                $path .= '/';
                // generate a url to access the file if no real path found.
                $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';

                $host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : php_uname("n");
                if (substr($arr["path"], 0, 1) === '/') {
                    $path = dirname($arr["path"]);
                } else {
                    $path = '/' . rtrim(dirname($_SERVER["SCRIPT_NAME"]), '/') . '/' . $arr["path"];
                }
            "file" => $file];
        $is_local_path = ($protocol === "" || $protocol === "file://");
            if ($is_local_path || ini_get('allow_url_fopen')) {
            } elseif (function_exists('curl_exec')) {
use Dompdf\Dompdf;
    /**
     * Current dompdf instance
     *
     * @var Dompdf
     */
    protected static $_dompdf;

     * @param Dompdf $dompdf    The Dompdf instance
     * @throws ImageException
     * @return array             An array with two elements: The local path to the image and the image extension
    static function resolve_url($url, $protocol, $host, $base_path, Dompdf $dompdf)
        self::$_dompdf = $dompdf;
        
        $protocol = mb_strtolower($protocol);
        $parsed_url = Helpers::explode_url($url);

        $remote = ($protocol && $protocol !== "file://") || ($parsed_url['protocol'] !== "");

        $data_uri = strpos($parsed_url['protocol'], "data:") === 0;
        $full_url = null;
        $enable_remote = $dompdf->getOptions()->getIsRemoteEnabled();
        $tempfile = false;

            // Remote not allowed and is not DataURI
            if (!$enable_remote && $remote && !$data_uri) {
                throw new ImageException("Remote file access is disabled.", E_WARNING);
            
            // remote allowed or DataURI
            if (($enable_remote && $remote) || $data_uri) {
                // Download remote files to a temporary directory
                $full_url = Helpers::build_url($protocol, $host, $base_path, $url);
                // From cache
                if (isset(self::$_cache[$full_url])) {
                    $resolved_url = self::$_cache[$full_url];
                } // From remote
                else {
                    $tmp_dir = $dompdf->getOptions()->getTempDir();
                    if (($resolved_url = @tempnam($tmp_dir, "ca_dompdf_img_")) === false) {
                        throw new ImageException("Unable to create temporary image in " . $tmp_dir, E_WARNING);
                    $tempfile = $resolved_url;
                    $image = null;
                    if ($data_uri) {
                        if ($parsed_data_uri = Helpers::parse_data_uri($url)) {
                            $image = $parsed_data_uri['data'];
                        }
                    } else {
                        list($image, $http_response_header) = Helpers::getFileContent($full_url, $dompdf->getHttpContext());
                    }
                    // Image not found or invalid
                    if ($image === null) {
                        $msg = ($data_uri ? "Data-URI could not be parsed" : "Image not found");
                        throw new ImageException($msg, E_WARNING);
                    } // Image found, put in cache and process
                    else {
                        //e.g. fetch.php?media=url.jpg&cache=1
                        //- Image file name might be one of the dynamic parts of the url, don't strip off!
                        //- a remote url does not need to have a file extension at all
                        //- local cached file does not have a matching file extension
                        //Therefore get image type from the content
                        if (@file_put_contents($resolved_url, $image) === false) {
                            throw new ImageException("Unable to create temporary image in " . $tmp_dir, E_WARNING);
                        }
            } // Not remote, local image
            else {
                $resolved_url = Helpers::build_url($protocol, $host, $base_path, $url);
                if ($protocol === "" || $protocol === "file://") {
                    $realfile = realpath($resolved_url);
        
                    $rootDir = realpath($dompdf->getOptions()->getRootDir());
                    if (strpos($realfile, $rootDir) !== 0) {
                        $chroot = $dompdf->getOptions()->getChroot();
                        $chrootValid = false;
                        foreach ($chroot as $chrootPath) {
                            $chrootPath = realpath($chrootPath);
                            if ($chrootPath !== false && strpos($realfile, $chrootPath) === 0) {
                                $chrootValid = true;
                                break;
                            }
                        }
                        if ($chrootValid !== true) {
                            throw new ImageException("Permission denied on $resolved_url. The file could not be found under the paths specified by Options::chroot.", E_WARNING);
                        }
                    }
        
                    if (!$realfile) {
                        throw new ImageException("File '$realfile' not found.", E_WARNING);
                    }
        
                    $resolved_url = $realfile;
            } // Check is the file is an image
            else {
                list($width, $height, $type) = Helpers::dompdf_getimagesize($resolved_url, $dompdf->getHttpContext());
                // Known image type
                if ($width && $height && in_array($type, ["gif", "png", "jpeg", "bmp", "svg","webp"], true)) {
                    //Don't put replacement image into cache - otherwise it will be deleted on cache cleanup.
                    //Only execute on successful caching of remote image.
                    if ($enable_remote && $remote || $data_uri) {
                        self::$_cache[$full_url] = $resolved_url;
                    }
                } // Unknown image type
                else {
                    throw new ImageException("Image type unknown", E_WARNING);
                }
            $type = "png";
            unlink($file);
        $versionFile = realpath(__DIR__ . "/../VERSION");
        if (file_exists($versionFile) && ($version = trim(file_get_contents($versionFile))) !== false && $version !== '$Format:<%h>$') {
            $ver = "/$version";
            $this->_dompdf
            "local absolute" => ["url($basePath/_files/jamaica.jpg)", $basePath . DIRECTORY_SEPARATOR . "_files" . DIRECTORY_SEPARATOR . "jamaica.jpg"],
            "local relative" => ["url(../_files/jamaica.jpg)", $basePath . DIRECTORY_SEPARATOR . "_files" . DIRECTORY_SEPARATOR . "jamaica.jpg"]
            "local absolute" => ["url($basePath/_files/jamaica.jpg)", $basePath . DIRECTORY_SEPARATOR . "_files" . DIRECTORY_SEPARATOR . "jamaica.jpg"],
            "local relative" => ["url(../_files/jamaica.jpg)", $basePath . DIRECTORY_SEPARATOR . "_files" . DIRECTORY_SEPARATOR . "jamaica.jpg"]

Fixed code:
            $options = $this->_dompdf->getOptions();
            $parsed_url = Helpers::explode_url($file);
            $protocol = $parsed_url["protocol"];
            if ($file !== $this->getDefaultStylesheet()) {
                $allowed_protocols = $options->getAllowedProtocols();
                if (!array_key_exists($protocol, $allowed_protocols)) {
                    Helpers::record_warnings(E_USER_WARNING, "Permission denied on $file. The communication protocol is not supported.", __FILE__, __LINE__);
                    return;
                }
                foreach ($allowed_protocols[$protocol]["rules"] as $rule) {
                    [$result, $message] = $rule($file);
                    if (!$result) {
                        Helpers::record_warnings(E_USER_WARNING, "Error loading $file: $message", __FILE__, __LINE__);


            [$this->_protocol, $this->_base_host, $this->_base_path] = $parsed_url;
            if ($path === null) {
                $path = "none";
            $parsed_url = Helpers::explode_url($path);
            if (($url = $this->resolve_url($url)) !== "none") {
                $this->load_css_file($url);
            }
        return Helpers::build_url("file://", "", $rootDir, $rootDir . self::DEFAULT_STYLESHEET);
        if (($version = file_get_contents($versionFile)) !== false) {
            $version = trim($version);
            if ($version !== '$Format:<%h>$') {
                $this->version = sprintf('dompdf %s', $version);
            }
        $allowed_protocols = $this->options->getAllowedProtocols();
        if (!array_key_exists($protocol, $allowed_protocols)) {
        if ($protocol === "file://") {
            $ext = strtolower(pathinfo($uri, PATHINFO_EXTENSION));
                throw new Exception("Permission denied on $file: The file extension is forbidden.");
        }
        foreach ($allowed_protocols[$protocol]["rules"] as $rule) {
            [$result, $message] = $rule($uri);
            if (!$result) {
                throw new Exception("Error loading $file: $message");
                        if ($url !== null) {
                            $this->css->load_css_file($url, Stylesheet::ORIG_AUTHOR);
                        }
        $allowed_protocols = $this->options->getAllowedProtocols();
        if (!array_key_exists($protocol, $allowed_protocols)) {
            Helpers::record_warnings(E_USER_WARNING, "Permission denied on $remoteFile. The communication protocol is not supported.", __FILE__, __LINE__);
        foreach ($allowed_protocols[$protocol]["rules"] as $rule) {
            [$result, $message] = $rule($remoteFile);
            if ($result !== true) {
                Helpers::record_warnings(E_USER_WARNING, "Error loading $remoteFile: $message", __FILE__, __LINE__);

            $dompdf->getOptions()
        if (empty($protocol)) {
            $protocol = "file://";
        }
            return null;
        $url_lc = mb_strtolower($url);

        if (
            (
                mb_strpos($url_lc, "://") !== false
                && !in_array(substr($url_lc, 0, 7), ["file://", "phar://"], true)
            )
            || mb_substr($url_lc, 0, 1) === "#"
            || mb_strpos($url_lc, "data:") === 0
            || mb_strpos($url_lc, "mailto:") === 0
            || mb_strpos($url_lc, "tel:") === 0
        ) {
        $res = "";
        if (strpos($url_lc, "file://") === 0) {
            $protocol = "file://";
        } elseif (strpos($url_lc, "phar://") === 0) {
            $res = substr($url, strpos($url_lc, ".phar")+5);
            $url = substr($url, 7, strpos($url_lc, ".phar")-2);
            $protocol = "phar://";
        $is_local_path = in_array($protocol, ["file://", "phar://"], true);

        if ($is_local_path) {

            $filepath = realpath($ret);
            if ($filepath === false) {
                return null;
            }

            $ret = "$protocol$filepath$res";

        $ret = $protocol;
        $res = "";
        if (isset($arr["scheme"]) && $arr["scheme"] !== "file" && $arr["scheme"] !== "phar" && strlen($arr["scheme"]) > 1) {
            $protocol = "";
            $i = mb_stripos($url, "://");
            if ($i !== false) {
                $protocol = mb_strtolower(mb_substr($url, 0, $i + 3));
                $url = mb_substr($url, $i + 3);
                $protocol = "file://";
            }
            if ($protocol === "phar://") {
                $res = substr($url, stripos($url, ".phar")+5);
                $url = substr($url, 7, stripos($url, ".phar")-2);

            $file = basename($url);
            $path = dirname($url) . "/";
            "file" => $file,
            "resource" => $res];
        $is_local_path = in_array(strtolower($protocol), ["", "file://", "phar://"], true);
        $can_use_curl = in_array(strtolower($protocol), ["http://", "https://"], true);
            if ($is_local_path || ini_get('allow_url_fopen') || !$can_use_curl) {
            } elseif ($can_use_curl && function_exists('curl_exec')) {
use Dompdf\Options;
     * @param Options $options  An instance of Dompdf\Options
     * @return array            An array with three elements: The local path to the image, the image
     *                          extension, and an error message if the image could not be cached
    static function resolve_url($url, $protocol, $host, $base_path, Options $options)
        $tempfile = null;
        $resolved_url = null;
        $type = null;
        
            $full_url = Helpers::build_url($protocol, $host, $base_path, $url);
            if ($full_url === null) {
                throw new ImageException("Unable to parse image URL $url.", E_WARNING);
            $parsed_url = Helpers::explode_url($full_url);
            $protocol = strtolower($parsed_url["protocol"]);
            $is_data_uri = strpos($protocol, "data:") === 0;
            
            if (!$is_data_uri) {
                $allowed_protocols = $options->getAllowedProtocols();
                if (!array_key_exists($protocol, $allowed_protocols)) {
                    throw new ImageException("Permission denied on $url. The communication protocol is not supported.", E_WARNING);
                }
                foreach ($allowed_protocols[$protocol]["rules"] as $rule) {
                    [$result, $message] = $rule($full_url);
                    if (!$result) {
                        throw new ImageException("Error loading $url: $message", E_WARNING);
                }
            }
            if ($protocol === "file://") {
                $resolved_url = $full_url;
            } elseif (isset(self::$_cache[$full_url])) {
                $resolved_url = self::$_cache[$full_url];
            } else {
                $tmp_dir = $options->getTempDir();
                if (($resolved_url = @tempnam($tmp_dir, "ca_dompdf_img_")) === false) {
                    throw new ImageException("Unable to create temporary image in " . $tmp_dir, E_WARNING);
                }
                $tempfile = $resolved_url;
                $image = null;
                if ($is_data_uri) {
                    if (($parsed_data_uri = Helpers::parse_data_uri($url)) !== false) {
                        $image = $parsed_data_uri["data"];
                } else {
                    list($image, $http_response_header) = Helpers::getFileContent($full_url, $options->getHttpContext());
                // Image not found or invalid
                if ($image === null) {
                    $msg = ($is_data_uri ? "Data-URI could not be parsed" : "Image not found");
                    throw new ImageException($msg, E_WARNING);
                }

                if (@file_put_contents($resolved_url, $image) === false) {
                    throw new ImageException("Unable to create temporary image in " . $tmp_dir, E_WARNING);

                self::$_cache[$full_url] = $resolved_url;
            }
            list($width, $height, $type) = Helpers::dompdf_getimagesize($resolved_url, $options->getHttpContext());

            if (($width && $height && in_array($type, ["gif", "png", "jpeg", "bmp", "svg","webp"], true)) === false) {
                throw new ImageException("Image type unknown", E_WARNING);
            $type = "svg";
            if (file_exists($file)) {
                unlink($file);
            }
    /**
    * Protocol whitelist
    *
    * Protocols and PHP wrappers allowed in URIs. Full support is not
    * guaranteed for the protocols/wrappers specified by this array.
    *
    * @var array
    */
    private $allowedProtocols = [
        "file://" => ["rules" => []],
        "http://" => ["rules" => []],
        "https://" => ["rules" => []]
    ];

        $versionFile = realpath(__DIR__ . '/../VERSION');
        if (($version = file_get_contents($versionFile)) !== false) {
            $version = trim($version);
            if ($version !== '$Format:<%h>$') {
                $ver = "/$version";
            }
        $this->setAllowedProtocols(["file://", "http://", "https://"]);

            } elseif ($key === 'allowedProtocols') {
                $this->setAllowedProtocols($value);
        } elseif ($key === 'allowedProtocols') {
            return $this->getAllowedProtocols();
    /**
     * @return array
     */
    public function getAllowedProtocols()
    {
        return $this->allowedProtocols;
    }

    /**
     * @param array $allowedProtocols The protocols to allow as an array (["protocol://" => ["rules" => [callable]]], ...) or a string list of the protocols
     * @return $this
     */
    public function setAllowedProtocols(array $allowedProtocols)
    {
        $protocols = [];
        foreach ($allowedProtocols as $protocol => $config) {
            if (is_string($protocol)) {
                $protocols[$protocol] = [];
                if (is_array($config)) {
                    $protocols[$protocol] = $config;
                }
            } elseif (is_string($config)) {
                $protocols[$config] = [];
            }
        }
        $this->allowedProtocols = [];
        foreach ($protocols as $protocol => $config) {
            $this->addAllowedProtocol($protocol, ...($config["rules"] ?? []));
        }
        return $this;
    }

    /**
     * Adds a new protocol to the allowed protocols collection
     *
     * @param string $protocol The scheme to add (e.g. "http://")
     * @param callable $rule A callable that validates the protocol
     * @return $this
     */
    public function addAllowedProtocol(string $protocol, callable ...$rules)
    {
        $protocol = strtolower($protocol);
        if (empty($rules)) {
            $rules = [];
            switch ($protocol) {
                case "file://":
                    $rules[] = [$this, "validateLocalUri"];
                    break;
                case "http://":
                case "https://":
                    $rules[] = [$this, "validateRemoteUri"];
                    break;
                case "phar://":
                    $rules[] = [$this, "validatePharUri"];
                    break;
            }
        }
        $this->allowedProtocols[$protocol] = ["rules" => $rules];
        return $this;
    }


    public function validateLocalUri(string $uri)
    {
        if ($uri === null || strlen($uri) === 0) {
            return [false, "The URI must not be empty."];
        }

        $realfile = realpath(str_replace("file://", "", $uri));

        $dirs = $this->chroot;
        $dirs[] = $this->rootDir;
        $chrootValid = false;
        foreach ($dirs as $chrootPath) {
            $chrootPath = realpath($chrootPath);
            if ($chrootPath !== false && strpos($realfile, $chrootPath) === 0) {
                $chrootValid = true;
                break;
            }
        }
        if ($chrootValid !== true) {
            return [false, "Permission denied. The file could not be found under the paths specified by Options::chroot."];
        }

        if (!$realfile) {
            return [false, "File not found."];
        }

        return [true, null];
    }

    public function validatePharUri(string $uri)
    {
        if ($uri === null || strlen($uri) === 0) {
            return [false, "The URI must not be empty."];
        }

        $file = substr(substr($uri, 0, strpos($uri, ".phar") + 5), 7);
        return $this->validateLocalUri($file);
    }

    public function validateRemoteUri(string $uri)
    {
        if ($uri === null || strlen($uri) === 0) {
            return [false, "The URI must not be empty."];
        }

        if (!$this->isRemoteEnabled) {
            return [false, "Remote file requested, but remote file download is disabled."];
        }

        return [true, null];
    }
            $this->_dompdf->getOptions()
            "local absolute" => ["url($basePath/_files/jamaica.jpg)", "file://" . $basePath . DIRECTORY_SEPARATOR . "_files" . DIRECTORY_SEPARATOR . "jamaica.jpg"],
            "local relative" => ["url(../_files/jamaica.jpg)", "file://" . $basePath . DIRECTORY_SEPARATOR . "_files" . DIRECTORY_SEPARATOR . "jamaica.jpg"]
            "local absolute" => ["url($basePath/_files/jamaica.jpg)", "file://" . $basePath . DIRECTORY_SEPARATOR . "_files" . DIRECTORY_SEPARATOR . "jamaica.jpg"],
            "local relative" => ["url(../_files/jamaica.jpg)", "file://" . $basePath . DIRECTORY_SEPARATOR . "_files" . DIRECTORY_SEPARATOR . "jamaica.jpg"]

    
    public function testCustomProtocolParsing(): void
    {
        $uri = "mock://path/to/resource";
        $this->assertSame($uri, Helpers::build_url("", "", "", $uri));
    }

    public function testAllowedProtocols()
    {
        $options = new Options(["isRemoteEnabled" => false]);
        $options->setAllowedProtocols(["http://"]);
        $allowedProtocols = $options->getAllowedProtocols();
        $this->assertIsArray($allowedProtocols);
        $this->assertEquals(1, count($allowedProtocols));
        $this->assertArrayHasKey("http://", $allowedProtocols);
        $this->assertIsArray($allowedProtocols["http://"]);
        $this->assertArrayHasKey("rules", $allowedProtocols["http://"]);
        $this->assertIsArray($allowedProtocols["http://"]["rules"]);
        $this->assertEquals(1, count($allowedProtocols["http://"]["rules"]));
        $this->assertEquals([$options, "validateRemoteUri"], $allowedProtocols["http://"]["rules"][0]);

        [$validation_result] = $allowedProtocols["http://"]["rules"][0]("http://example.com/");
        $this->assertFalse($validation_result);

        
        $mock_protocol = [
            "mock://" => [
                "rules" => [
                    function ($uri) { return [true, null]; }
                ]
            ]
        ];
        $options->setAllowedProtocols($mock_protocol);
        $allowedProtocols = $options->getAllowedProtocols();
        $this->assertIsArray($allowedProtocols);
        $this->assertEquals(1, count($allowedProtocols));
        $this->assertArrayHasKey("mock://", $allowedProtocols);
        $this->assertIsArray($allowedProtocols["mock://"]);
        $this->assertArrayHasKey("rules", $allowedProtocols["mock://"]);
        $this->assertIsArray($allowedProtocols["mock://"]["rules"]);
        $this->assertEquals(1, count($allowedProtocols["mock://"]["rules"]));
        $this->assertEquals($mock_protocol["mock://"]["rules"][0], $allowedProtocols["mock://"]["rules"][0]);

        [$validation_result] = $allowedProtocols["mock://"]["rules"][0]("mock://example.com/");
        $this->assertTrue($validation_result);
    }