MDL Shield

PeerTube

filter_peertube

Published by Dag Klimas (aka Moodle-Guide)

Plugin Information

A Moodle text filter that turns PeerTube video links (bare URLs or complete <a> tags) pointing at administrator-allowlisted PeerTube instances into a responsive, sandboxed <iframe> embed rendered from a Mustache template. It has one admin setting, a textarea of allowed https:// hosts.

Version:2026111900
Release:v0.4
Reviewed for:5.3
Privacy API
Unit Tests
Behat Tests
Reviewed:2026-11-20
9 files·656 lines
Grade Justification

No security vulnerabilities were found. Every exploit path we traced ends in harmless output:

  • The filter runs at the post_clean stage of format_text(), so its input has already been through HTML Purifier.
  • The only values that reach the template are an admin-validated https:// hostname and a video ID limited to [A-Za-z0-9_-]+. Mustache escapes both.
  • The regex requires /w/ straight after the allowlisted host, so look-alike domains cannot match.

The main defect is that the raw-URL regex also matches inside HTML attribute values. That corrupts markup, but it cannot become XSS. Core's purifier writes attribute values double-quoted and passes them through htmlspecialchars(), so any author text left over after the break-out shows up as plain text. Only the author's own content is affected.

The second low finding is an admin-only normalisation bug. A source saved with a trailing slash through the CLI or config.php never matches. The remaining finding is an info-level styling suggestion.

The code is small and readable, and it has tests:

  • The privacy provider matches core's own embed plugins.
  • The MOODLE_INTERNAL guards are placed correctly.
  • The plugin ships with PHPUnit tests that include a look-alike domain case.

Overall it is clean apart from minor code-quality issues.

AI Summary

filter_peertube is a small text filter: one filter class, one Mustache template, one admin setting and a PHPUnit test. It turns PeerTube links that point at administrator-allowlisted instances into a sandboxed, responsive <iframe>. It has no database tables, web services, JavaScript, outbound HTTP or file handling.

The security posture is good. The filter runs after core's HTML Purifier pass. The embed URL can only be built from an admin-validated https:// hostname plus an ID limited to [A-Za-z0-9_-]+, and Mustache escapes the result. The regex is anchored so that look-alike domains such as allowed.host.attacker.tld never match. No path we traced lets a student or teacher inject script or point the iframe at a host that isn't on the allowlist.

The finding most worth acting on is that the bare-URL alternative of the regex also matches URLs inside HTML attribute values, for example an image alt, a title, or another link's query string. It splices the iframe markup into the attribute and leaves broken HTML. Core's attribute escaping stops this from becoming XSS, but it's a real rendering bug, and the filter also ignores the usual nolink opt-out. A smaller bug: trailing slashes are trimmed when the regex is built but not when the allowlist is checked, so a source saved through the CLI with a trailing slash never embeds.

Findings

code qualityLow
PeerTube URLs inside HTML attributes are replaced, producing broken markup

The second alternative of the regex built in get_replace_pattern() matches any https://<allowed-host>/w/<id> substring in the HTML, with no regard for tag boundaries. When the URL sits inside an attribute value, the whole <div><iframe …></div> embed is spliced into that attribute. Examples include an image alt/title, or the query string of an unrelated link such as …/mod/url/view.php?u=https://peertube.example/w/abc. The template's first " closes the author's attribute early, which leaves malformed tags, stray attribute text shown as content, and truncated hrefs. The filter also ignores Moodle's nolink opt-out, so an author cannot keep a PeerTube link as a plain link. Core URL filters (filter_urltolink, filter_mediaplugin) avoid this by splitting the text on tags and only rewriting text nodes or whole <a> elements.

Risk Assessment

Low risk. This is a rendering and data-integrity defect, not an injection. Core's HTML Purifier writes every attribute value double-quoted and escapes ", < and > (HTMLPurifier_Generator::generateAttributes()), so after the break-out the author's remaining text appears only as visible text. It only affects the author's own content, but it is easy to trigger by accident, for example when a teacher puts a video URL in an image's alt text.

Context

filter() runs in the post_clean stage of format_text(), after clean_text(), and its output is not cleaned again. The anchor alternative only handles <a> tags whose href is the PeerTube URL. Every other occurrence, including those inside attributes of any element, falls through to the bare-URL alternative.

Identified Code
        return '#<a\b[^>]*href=["\']?(' . $sourcesregex . ')/w/([A-Za-z0-9_-]+)[^"\']*["\']?[^>]*>.*?</a>|'
        . '(' . $sourcesregex . ')/w/([A-Za-z0-9_-]+)(\?[^<\s"]*)?#is';
Suggested Fix

Split the HTML on tags (as core's filter_mediaplugin does) and only apply the bare-URL pattern to text chunks, skipping nolink regions (e.g. with filter_save_ignore_tags()):

$parts = preg_split('#(<a\b[^>]*>.*?</a>|<[^>]*>)#is', $text, -1,
    PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
foreach ($parts as $i => $part) {
    if (preg_match('#^<a\b#i', $part)) {
        $parts[$i] = preg_replace_callback($anchorpattern, [$this, 'replace_callback'], $part);
    } else if ($part[0] !== '<') {
        $parts[$i] = preg_replace_callback($rawurlpattern, [$this, 'replace_callback'], $part);
    }
}
return implode('', $parts);

Add unit tests for URLs inside alt/title attributes and inside another link's href.

code qualityLow
Trailing slash trimmed for the regex but not for the allowlist check

get_replace_pattern() deliberately strips a trailing / from each source before building the regex. The comment notes that CLI-set values may contain one. get_replace_sources() returns the untrimmed values, though, and replace_callback() compares the matched host against that untrimmed list with in_array(). A source stored as https://peertube.example.com/ therefore matches the regex, fails the allowlist check, and is left unchanged, so the filter silently does nothing for that instance. The admin UI rejects such values in validate(), but admin/cli/cfg.php (set_config()) and $CFG->forced_plugin_settings both skip that validation, which is exactly the case the comment describes.

Risk Assessment

Low risk. This is a functional bug that only an administrator configuring the site outside the settings form can hit. It has no security impact, because it fails closed: nothing is embedded.

Context

The quick stripos() pre-check, the regex, and the in_array() check in the callback each read the source list. The only normalisation is the rtrim() applied in the regex builder.

Identified Code
        return array_map('strtolower', $sources);
Suggested Fix

Normalise once, where the list is built, and drop the rtrim() from get_replace_pattern():

return array_map(fn($source) => strtolower(rtrim($source, '/')), $sources);

You could also re-apply the https:// + hostname check here, so that values that bypassed validate() are skipped.

Identified Code
            return preg_quote(rtrim($source, '/'), '#');
Suggested Fix
            return preg_quote($source, '#');
best practiceInfo
Embed template hard-codes layout in inline style attributes

The embed's centring, 16:9 aspect ratio, maximum width and iframe positioning are all set with inline style attributes. Inline styles can only be overridden with !important and cannot be changed through the theme, and they are blocked by any site that deploys a Content Security Policy without 'unsafe-inline' for styles. Moodle 5.3's Boost theme already ships Bootstrap 5's ratio/ratio-16x9 helpers (present in the compiled theme/boost/style/moodle.css), which give the same responsive container without inline CSS. Any extra rules (such as max-width) can go in a plugin styles.css under a scoped class.

Risk Assessment

No security risk. This is a maintainability and theming suggestion only.

Context

The template is rendered once per matched PeerTube link by text_filter::get_html_from_template(), and its markup is inserted directly into the filtered content.

Identified Code
<div style="text-align: center;">
    {{! Responsive container maintaining a 16:9 aspect ratio and fitting mobile screens. }}
    <div style="position: relative; width: 100%; max-width: 640px; margin: 0 auto; aspect-ratio: 16 / 9;">
        {{! Iframe element embedding the video with secure sandbox permissions and fullscreen support. }}
        <iframe style="border: 0px; position: absolute; top: 0; left: 0; width: 100%; height: 100%;"
Suggested Fix
<div class="filter_peertube_embed mx-auto">
    <div class="ratio ratio-16x9">
        <iframe class="border-0" title="{{#str}}iframetitle, filter_peertube{{/str}}" src="{{embedurl}}" …></iframe>
    </div>
</div>

Then add .filter_peertube_embed { max-width: 640px; } to a plugin styles.css.

Additional AI Notes

How the embed sink is protected. We checked the data flow against core rather than assuming it was safe:

  • format_text() (lib/classes/formatting.php) calls the filter only at the post_clean stage.
  • format_string() runs clean_text() or strip_tags() on the filter's output afterwards.
  • The iframe src is built only from an allowlisted host and a video ID captured by [A-Za-z0-9_-]+, and {{embedurl}} is HTML-escaped by Mustache.
  • The sandbox="allow-scripts allow-same-origin allow-popups" combination is safe here because the framed document is always cross-origin to Moodle.

Query parameters are discarded. The bare-URL pattern captures ?… (group 5) and then throws it away, so options such as PeerTube's ?start= timestamp or ?autoplay= are lost. The anchor alternative does the same. If authors are expected to share timestamped links, consider passing a small allowlist of embed parameters through to the embed URL.

Privacy. Each embed makes the viewer's browser contact the third-party PeerTube instance, which receives their IP address, user agent and the Moodle origin as referrer. Using a null_provider matches core's own media_youtube, but a short note in the setting description that allowlisted instances receive these details would help administrators with GDPR assessments.

Minor docblock inconsistency. get_html_from_template() declares a native string return type but its docblock says @return bool|string, and the same mismatch is repeated in the test's anonymous class. The setUp() method in tests/text_filter_test.php also declares an unused global $CFG;.

This review was generated by an AI system and may contain inaccuracies. Findings should be verified by a human reviewer before acting on them.

Published reviews of this plugin

2026-11-20v0.4CurrentA