Home > Software engineering >  Symfony 6 - Unable to make HtmlSanitizer work properly
Symfony 6 - Unable to make HtmlSanitizer work properly

Time:09-14

Based on SF6 docs, I tried to use the new HtmlSanitizer component ( https://symfony.com/doc/current/html_sanitizer.html ) on some html that's coming from a database, nothing fancy, really:

<section >
    <div >
        <p>
            This is a paragraph, with <strong>words</strong> in it, it also has a <a href="/some/relative/link">relative link</a> and a <a href="https://www.google.com/">absolute</a> one as well.
        </p>
    </div>
</section>  

When I pass this through the default sanitizer, the html output is:

<section>
    <div>
        <p>
            This is a paragraph, with <strong>words</strong> in it, it also has a <a>relative link</a> and a <a href="https://www.google.com/">absolute</a> one as well.
        </p>
    </div>
</section>

So my class attributes are removed, relative URLs as well, but oddly enough, absolute URLs are kept.

I tried to create a custom sanitizer, with the following configuration:

framework:
    html_sanitizer:
        sanitizers:
            app.wysiwyg_sanitizer:
                allow_safe_elements: true
                allow_static_elements: true
                allow_relative_links: true
                allow_relative_medias: true

And when I use it, things almost work, except, the links containing absolute URLs, are rendered unusable:

<section >
    <div >
        <p>
            This is a paragraph, with <strong>words</strong> in it, it also has a <a href="/some/relative/link">relative link</a> and a <a>absolute</a> one as well.
        </p>
    </div>
</section>

Here's the PHP to it, not much going on:

#[Route('/', name: 'app_home')]
    public function index(HtmlSanitizerInterface $sanitizer, HtmlSanitizerInterface $appWysiwygSanitizer): Response
    {
        $html = '
        <section >
            <div >
                <p>
                    This is a paragraph, with <strong>words</strong> in it, it also has a <a href="/some/relative/link">relative link</a> and a <a href="https://www.google.com/">absolute</a> one as well.
                </p>
            </div>
        </section>';

        $response = 'Default: ' . $sanitizer->sanitize($html);
        $response .= PHP_EOL;
        $response .= 'Custom: ' . $appWysiwygSanitizer->sanitize($html);

        return new Response($response);
    }

Any idea what I am doing wrong? I just need those links to be rendered properly and I can't seem to find a way to do it.

CodePudding user response:

I think you have to explicity allow the link schemes:

framework:
    html_sanitizer:
        sanitizers:
            app.wysiwyg_sanitizer:
                ...
                allowed_link_schemes: ['http', 'https', 'mailto']

Edit: it seems necessary to do a clear:cache after the config file modification, for it to take effect

  • Related