Skip to content

fix(message): render received external SVG images - #13142

Open
joeldj-nl wants to merge 12 commits into
nextcloud:mainfrom
joeldj-nl:fix/render-received-svg-images
Open

joeldj-nl wants to merge 12 commits into
nextcloud:mainfrom
joeldj-nl:fix/render-received-svg-images

Conversation

@joeldj-nl

@joeldj-nl joeldj-nl commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Received emails containing external SVG images did not render. The message showed only the broken-image placeholder and the image's alt text or name. External images are fetched through the image proxy, which served every response as application/octet-stream. Browsers happily sniff raster formats (PNG/JPEG/GIF) out of an tag regardless of content type, but they refuse to render SVG unless it is served as image/svg+xml, so SVG logos and graphics stayed blank.

Changes

  • Detect SVG markup in proxied responses and serve it with the image/svg+xml content type so browsers render it.
  • Add an SvgSanitizer service that strips active content (scripts, event handlers, external/javascript: references) and rejects DOCTYPE/entity declarations, as defence in depth against XXE and stored XSS even though the context does not execute scripts.

The first screenshot shows the issue; the second screenshot shows it has been resolved.

svg-not-rendering svg-rendering-succeeded

Assisted-by: Claude:claude-opus-4-8

Summary by CodeRabbit

Release Notes

  • New Features

    • SVG content is automatically detected during proxying and sanitized before being served.
    • Sanitized SVGs are returned with the correct image/svg+xml content type; unsafe/invalid content is replaced with a blocked-image fallback.
  • Bug Fixes

    • Improved handling of proxy responses that don’t return valid image payloads, reducing failures and ensuring consistent output.
  • Tests

    • Added unit tests for SVG sanitization security rules and updated controller tests to verify sanitized SVG delivery.

External images are fetched through the image proxy and served with a
generic application/octet-stream content type. Browsers sniff raster
formats in <img> tags, but they refuse to render SVG unless it is served
as image/svg+xml, so SVG logos stayed blank and only the alt text and
placeholder were shown.

Detect SVG markup in the proxied response and serve it as a sanitised
image/svg+xml document. A new SvgSanitizer service strips active content
(scripts, event handlers, external/javascript references) and rejects
DOCTYPE/entity declarations as XXE defence in depth, even though the
<img> context does not execute scripts.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Joël de Jager <contact@joeldejager.nl>
@ChristophWurst

Copy link
Copy Markdown
Member

Thanks for the contribution

@ChristophWurst

Copy link
Copy Markdown
Member

@coderabbitai review and scan for new vulnerabilities

@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Get the list of changed files in this PR
gh pr view 13142 --repo nextcloud/mail --json files --jq '.files[].path'

Length of output: 416


🏁 Script executed:

#!/bin/bash
# Read the new SvgSanitizer and any modified proxy/controller files
fd -e php . lib/ --exec echo {} \; | grep -i 'svg\|proxy\|image' | sort
cat -n lib/Service/SvgSanitizer.php 2>/dev/null || echo "NOT FOUND"

Length of output: 4248


🏁 Script executed:

#!/bin/bash
# Find and read all relevant new/changed files
fd -e php . lib/ | xargs grep -l -i 'svg\|SvgSanitizer' 2>/dev/null | sort

# Also find proxy-related files
fd -e php . lib/ | xargs grep -l -i 'proxy\|imageproxy\|image_proxy' 2>/dev/null | sort

Length of output: 730


🏁 Script executed:

#!/bin/bash
cat -n lib/Controller/ProxyController.php

Length of output: 6202


🏁 Script executed:

#!/bin/bash
cat -n tests/Unit/Service/SvgSanitizerTest.php
cat -n tests/Unit/Controller/ProxyControllerTest.php

Length of output: 14218



@ChristophWurst Overall the implementation is solid — HMAC gating, LIBXML_NONET, DOCTYPE/entity rejection, event-handler stripping, and namespace-aware element removal are all good defence-in-depth measures. A few security gaps are worth closing before merge:


🔴 Security findings

1. src attribute not stripped (SVG <image> – tracking / SSRF when navigated directly)

SvgSanitizer::stripDangerousAttributes() only checks href and xlink:href. SVG 2.0 <image> also accepts a plain src attribute that some browsers honour. When a user opens the proxy URL directly (non-<img> context), an unstripped <image src="https://tracker.example/pixel.gif"/> would trigger an outbound request.

// lib/Service/SvgSanitizer.php  Line 100
if (in_array($name, ['href', 'xlink:href'], true) && !str_starts_with($value, '#')) {

Suggested fix – extend the stripped attribute list and tighten the check to cover all URL-bearing SVG attributes:

private const URL_ATTRIBUTES = ['href', 'xlink:href', 'src', 'action', 'formaction'];

// in stripDangerousAttributes():
if (in_array($name, self::URL_ATTRIBUTES, true) && !str_starts_with($value, '#')) {
    $element->removeAttributeNode($attribute);
    continue;
}

2. <style> elements and style="" attributes not sanitized (CSS url() exfiltration on direct navigation)

The sanitizer removes dangerous elements and attributes but leaves <style> blocks and inline style="" attributes intact. CSS url() expressions can load external resources when the SVG is opened directly via the proxy URL (not as an <img> source). Example:

<svg xmlns="http://www.w3.org/2000/svg">
  <style>rect { fill: url(https://tracker.example/pixel.gif) }</style>
  <rect width="100" height="100"/>
</svg>

Suggested fix – add style to FORBIDDEN_ELEMENTS or walk <style> text nodes and strip url(...) expressions that reference non-fragment URLs:

private const FORBIDDEN_ELEMENTS = [
    'script', 'style',           // ← add style
    'foreignObject', 'handler', 'listener', 'set',
];

If preserving safe style rules matters (e.g., fill: red), a regex pass over <style> text content can strip only url(...) values that do not begin with #.


3. No size limit before DOMDocument::loadXML() (potential DoS)

A malicious upstream server could return a huge payload that passes looksLikeSvg(). loadXML() will attempt to hold the whole document in memory. Consider capping the input size before parsing:

// lib/Service/SvgSanitizer.php  – top of sanitize()
private const MAX_SVG_BYTES = 2 * 1024 * 1024; // 2 MiB

public function sanitize(string $svg): string {
    if (trim($svg) === '' || strlen($svg) > self::MAX_SVG_BYTES) {
        return '';
    }
    // …

🟡 Minor / behavioural findings

4. Empty body served on sanitizer rejection

When sanitize() returns '' (DOCTYPE detected, parse failure, etc.) the proxy still returns:

return new ProxyDownloadResponse($content, $src, 'image/svg+xml');
// ProxyController.php  Line 131 — $content is '' at this point

This sends a 200 with an empty image/svg+xml body instead of the blocked-image.png fallback. Consider:

if ($this->looksLikeSvg($content)) {
    $sanitized = $this->svgSanitizer->sanitize($content);
    if ($sanitized === '') {
        $content = (string)file_get_contents(__DIR__ . '/../../img/blocked-image.png');
        return new ProxyDownloadResponse($content, $src, 'application/octet-stream');
    }
    return new ProxyDownloadResponse($sanitized, $src, 'image/svg+xml');
}

5. looksLikeSvg() — <!-- prefix is overly broad

// ProxyController.php  Line 142
|| str_starts_with($start, '<!--')

Any response starting with an HTML comment (common in HTML pages) combined with any embedded <svg> element will pass through to the DOM parser, which will reject it and return ''. No security impact, but it means tracking-pixel HTML pages are unnecessarily parsed. Consider dropping the <!-- branch or checking that <svg follows before the first non-comment, non-PI token.


✅ What looks good

Concern Status
HMAC validation before proxying ✅
LIBXML_NONET prevents network fetch during parse ✅
DOCTYPE / <!ENTITY pre-rejected by regex ✅
on* event-handler attributes stripped ✅
Namespace-aware element removal (local-name()) ✅
External href / xlink:href stripped ✅
Rate-limiting (#[UserRateLimit]) ✅
LocalServerException caught (SSRF guard) ✅
Test coverage for sanitizer + controller ✅
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

A new SvgSanitizer service parses and filters SVG markup. ProxyController now validates proxied bodies, sanitizes detected SVG responses, centralizes blocked-image loading, and returns sanitized SVG or fallback content with appropriate response types.

Changes

SVG Sanitization Feature

Layer / File(s) Summary
SvgSanitizer service
lib/Service/SvgSanitizer.php
Adds XML parsing, unsafe element and attribute removal, DOCTYPE/ENTITY rejection, and sanitized SVG serialization.
ProxyController SVG response handling
lib/Controller/ProxyController.php
Injects SvgSanitizer, validates response bodies, sanitizes SVG content, handles empty sanitization results, and centralizes blocked-image loading with ServiceException failures.
Sanitization and proxy integration tests
tests/Unit/Service/SvgSanitizerTest.php, tests/Unit/Controller/ProxyControllerTest.php
Covers SVG filtering, unsafe markup rejection, safe graphics preservation, SVG response headers, and updated controller dependency construction.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Suggested reviewers: christophwurst, gretad, kesselb

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: fixing rendering of received external SVG images.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (1)
lib/Controller/ProxyController.php (1)

137-146: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Move SVG detection heuristic out of the controller.

looksLikeSvg() is business logic and makes ProxyController less of a thin HTTP handler. Consider moving this heuristic into SvgSanitizer (or a dedicated detector service) and call it from here.

As per coding guidelines, lib/Controller/**/*.php: “Controllers must be thin HTTP handlers; business logic must live in services”.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 26c52dd2-524b-4c89-9e7f-305d15c812e0

📥 Commits

Reviewing files that changed from the base of the PR and between 9808f3e and ccb4252.

📒 Files selected for processing (4)
  • lib/Controller/ProxyController.php
  • lib/Service/SvgSanitizer.php
  • tests/Unit/Controller/ProxyControllerTest.php
  • tests/Unit/Service/SvgSanitizerTest.php

Comment thread lib/Controller/ProxyController.php Resolved
Comment thread lib/Controller/ProxyController.php Resolved
Comment thread lib/Service/SvgSanitizer.php Resolved
Comment thread lib/Service/SvgSanitizer.php Resolved
Comment thread lib/Service/SvgSanitizer.php Resolved
Comment thread tests/Unit/Service/SvgSanitizerTest.php Resolved
@ChristophWurst

Copy link
Copy Markdown
Member

Yes

- Extend URL attribute stripping to cover src, action, formaction
- Strip external CSS url() references from <style> elements and style=""
  attributes while preserving fragment references (url(#...))
- Reject SVG payloads exceeding 2 MiB before DOM parsing (DoS guard)
- Fall back to blocked-image.png instead of serving empty body when
  sanitizer rejects an SVG document
- Drop misleading <!-- branch from looksLikeSvg() heuristic
- Move looksLikeSvg() from ProxyController into SvgSanitizer service

Assisted-by: Claude:claude-sonnet-4-6
Signed-off-by: Joël de Jager <contact@joeldejager.nl>
@joeldj-nl

Copy link
Copy Markdown
Contributor Author

The recommended changes have been implemented.

@ChristophWurst

Copy link
Copy Markdown
Member

@coderabbitai re-review

@coderabbitai

coderabbitai Bot commented Jun 23, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
cat -n lib/Service/SvgSanitizer.php
echo "---"
cat -n lib/Controller/ProxyController.php

Length of output: 11368



@ChristophWurst All five previously flagged issues have been resolved in the current implementation:

# Finding Status
1 src attribute not stripped ✅ Fixed — src, action, formaction added to URL_ATTRIBUTES constant (Line 34)
2 <style> / style="" CSS url() not sanitized ✅ Fixed — <style> text content and inline style attributes are both run through stripCssUrls(), which replaces external references with none while preserving same-document url(#…) fragments
3 No size limit before DOMDocument::loadXML() ✅ Fixed — 2 MiB cap via MAX_SVG_BYTES constant, checked before parsing (Line 45)
4 Empty image/svg+xml response on sanitizer rejection ✅ Fixed — ProxyController now checks $sanitized === '' and falls back to blocked-image.png with application/octet-stream
5 <!-- prefix in looksLikeSvg() overly broad ✅ Fixed — <!-- branch removed; detection now only triggers on <?xml or <svg prefix

The implementation is clean and all security measures are in place.

[approve]

@github-actions

github-actions Bot commented Jul 7, 2026

Copy link
Copy Markdown

Hello there,
Thank you so much for taking the time and effort to create a pull request to our Nextcloud project.

We hope that the review process is going smooth and is helpful for you. We want to ensure your pull request is reviewed to your satisfaction. If you have a moment, our community management team would very much appreciate your feedback on your experience with this PR review process.

Your feedback is valuable to us as we continuously strive to improve our community developer experience. Please take a moment to complete our short survey by clicking on the following link: https://cloud.nextcloud.com/apps/forms/s/i9Ago4EQRZ7TWxjfmeEpPkf6

Thank you for contributing to Nextcloud and we hope to hear from you soon!

(If you believe you should not receive this message, you can add yourself to the blocklist.)

Comment thread lib/Controller/ProxyController.php Resolved

@ChristophWurst ChristophWurst left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 otherwise

thanks

@ChristophWurst

Copy link
Copy Markdown
Member

The branch needs an update because there is a conflict

Signed-off-by: Joël de Jager <contact@joeldejager.nl>
Assisted-by: Codex:gpt-5
Signed-off-by: Joël de Jager <contact@joeldejager.nl>
@joeldj-nl

Copy link
Copy Markdown
Contributor Author

The branch needs an update because there is a conflict

Updated!

@joeldj-nl
joeldj-nl requested a review from ChristophWurst July 22, 2026 08:38
Comment thread lib/Controller/ProxyController.php Resolved
Assisted-by: Codex:gpt-5
Signed-off-by: Joël de Jager <contact@joeldejager.nl>
@joeldj-nl
joeldj-nl requested a review from ChristophWurst July 22, 2026 11:21
@ChristophWurst

Copy link
Copy Markdown
Member

@coderabbitai review again

@coderabbitai

coderabbitai Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

@ChristophWurst The Comment images show the original rendering failure: one displays a broken-image icon with the alt text main.svg, and the other displays a grey placeholder labeled 400×600. I’ll re-review the updated branch, including the conflict resolution, for regressions and new security issues.

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 537ec8a0-7baa-4b21-b7c6-209350983019

📥 Commits

Reviewing files that changed from the base of the PR and between ccb4252 and a47fda5.

📒 Files selected for processing (1)
  • lib/Controller/ProxyController.php

Comment thread lib/Controller/ProxyController.php Resolved
Comment thread lib/Controller/ProxyController.php Resolved
Comment thread lib/Controller/ProxyController.php Resolved
Assisted-by: Codex:gpt-5
Signed-off-by: Joël de Jager <contact@joeldejager.nl>
@joeldj-nl

Copy link
Copy Markdown
Contributor Author

@ChristophWurst the new findings by CodeRabbitAI have been resolved.

@kesselb

kesselb commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Thanks for your pr 👍

We reject SVG's with XLS/Transform in server (c.f. nextcloud/server#59835) and should apply the same hardening here.

Signed-off-by: Joël de Jager <contact@joeldejager.nl>
@joeldj-nl

Copy link
Copy Markdown
Contributor Author

@kesselb thanks for your input. This should be fixed now.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes external SVG images not rendering in proxied email content by detecting SVG payloads and serving them as image/svg+xml, adding an SVG sanitization layer to reduce XSS/XXE risk when proxying untrusted markup.

Changes:

  • Add SvgSanitizer service to detect SVG markup and strip active/dangerous content.
  • Update ProxyController to read streamed proxy responses safely and to sanitize/serve SVG with the correct content type.
  • Add unit tests for the sanitizer and for proxying sanitized SVG responses.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
lib/Controller/ProxyController.php Reads stream bodies, detects SVG responses, sanitizes them, and serves with image/svg+xml (fallbacks to blocked image on unsafe SVG).
lib/Service/SvgSanitizer.php New sanitizer that parses SVG with libxml hardening and strips scripts/event handlers/external references.
tests/Unit/Controller/ProxyControllerTest.php Adds test coverage for streamed bodies and SVG sanitization/content-type behavior in the proxy.
tests/Unit/Service/SvgSanitizerTest.php Adds unit tests for sanitizer security rules and SVG detection heuristics.

Comment thread lib/Controller/ProxyController.php Resolved
Comment thread lib/Service/SvgSanitizer.php Resolved
Comment thread lib/Service/SvgSanitizer.php Resolved
Comment thread lib/Service/SvgSanitizer.php Resolved
Comment thread lib/Controller/ProxyController.php Resolved
joeldj-nl and others added 3 commits August 10, 2026 20:50
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Joël de Jager <contact@joeldejager.nl>
Assisted-by: ClaudeCode:claude-fable-5
Signed-off-by: Joël de Jager <contact@joeldejager.nl>
Assisted-by: ClaudeCode:claude-fable-5
Signed-off-by: Joël de Jager <contact@joeldejager.nl>
@joeldj-nl

Copy link
Copy Markdown
Contributor Author

Added new commits to resolve the issues.

@joeldj-nl
joeldj-nl requested a review from kesselb August 10, 2026 19:07
Signed-off-by: Christoph Wurst <1374172+ChristophWurst@users.noreply.github.com>

# Conflicts:
#	lib/Controller/ProxyController.php

@ChristophWurst ChristophWurst left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks Joël, the root cause is spot on and the tests are appreciated.

Main concern: the headline case doesn't work for typical exported SVGs yet. Anything with a plain <!DOCTYPE svg PUBLIC …> header (Illustrator, older Inkscape) is rejected, files starting with a comment or DOCTYPE aren't detected, and data: images are stripped, so those logos stay blank. Second concern: the hand-rolled sanitizer has gaps (see inline notes, the CSS ones are reproducible with a short snippet). In an <img> context the impact is low, but it describes itself as defence in depth.

Please also trim the comments per AGENTS.md. Could you try an Illustrator-style export with DOCTYPE, an SVG using <style> classes and one with an embedded base64 PNG, and tell us what renders?

This touches security-relevant parsing, so a second reviewer on the sanitizer would be good.

Assisted by ClaudeCode:claude-sonnet-5-5


// A DOCTYPE or entity declaration is not needed for plain SVG graphics
// and is a common XXE / entity-expansion vector. Reject such documents.
if (preg_match('/<!DOCTYPE|<!ENTITY/i', $inspectable) === 1) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any document with a DOCTYPE is rejected, including the standard <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "…svg11.dtd"> header that Illustrator and older Inkscape exports carry. Those now show the blocked placeholder. Could we reject only <!ENTITY / internal subsets ([) and tolerate the plain public DOCTYPE? The parser runs without LIBXML_NOENT/LIBXML_DTDLOAD, so it isn't resolved anyway.

/**
* Heuristically decide whether the given bytes are an SVG document.
*/
public function looksLikeSvg(string $content): bool {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two problems with the heuristic: (1) files starting with <!-- Generator: … --> or a bare <!DOCTYPE svg return false, so they stay application/octet-stream and blank. (2) Any XML that merely mentions <svg, e.g. <?xml …?><html><svg/></html>, returns true. Checking that the parsed root element is svg in the SVG namespace would be more robust than string prefixes.

* @return string|null Null if the payload is not in an accepted encoding
*/
private function normalize(string $svg): ?string {
$encoding = mb_detect_encoding($svg, self::ALLOWED_ENCODINGS, true);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ISO-8859-1 matches any byte string, so this never returns false; random bytes and UTF-16 both detect as ISO-8859-1. The null branch is dead and "anything else is rejected outright" isn't true. Also, the string checks run on this normalised copy while loadXML at :80 gets the original bytes with their declared encoding, so the two can see different documents. The DOM pass is what actually protects here; I'd say so rather than claim the pre-checks are exhaustive.


// Only allow same-document references; strip javascript:, external
// and data: URLs from links and resource references.
if (in_array($localName, self::URL_ATTRIBUTES, true) && !str_starts_with($value, '#')) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also strips href="data:image/png;base64,…" on <image>, so logos with an embedded bitmap render empty. data:image/* can't make a request, so it could be allowed for image elements. Related: XHTML-namespaced elements pass through untouched (<h:iframe srcdoc>, <h:object data>, <h:meta http-equiv=refresh>, srcset, poster).

}
}

// Sanitise <style> element content: strip external CSS url() references.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The CSS url() stripping misses things. I ran these: u\72l(http://e.com/x) (CSS escape) and image-set("http://e.com/x" 1x) both survive in <style>; quoted URLs containing ) get mangled (url("http://e.com/)x") becomes nonex")). Regex CSS handling will keep having holes. Dropping <style> and style altogether is simpler but breaks class-styled SVGs, so either parse the CSS properly or use a maintained library.

continue;
}

// Strip external CSS url() references from inline style attributes.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only the style attribute is sanitised. Presentation attributes aren't: <rect fill="url(http://e.com/x)"/> passes through untouched, same for filter, mask, clip-path, marker-*, cursor. Apply stripCssUrls to every attribute value?

*/
class SvgSanitizer {
/** Elements that can carry or execute active content. */
private const FORBIDDEN_ELEMENTS = [

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

<animate>, <animateTransform> and <animateMotion> aren't forbidden: <animate attributeName="href" values="javascript:…"/> survives (only <set> is removed). Harmless in <img>, but it contradicts the "strips javascript: references" claim.

* not execute, but they are still sanitised as defence in depth: any document
* that cannot be parsed safely is dropped entirely.
*/
class SvgSanitizer {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was a maintained library (e.g. enshrined/svg-sanitize) or an element/attribute allowlist considered instead of a blocklist? The gaps above are the typical failure mode of blocklists. nit: the class docblock mentions messages and a "CID context", but this is only used by the proxy.

nit: this PR adds a lot of explanatory comments; AGENTS.md asks for essentially none beyond a non-obvious why. The nextcloud/server#62162 reference belongs in the commit message.

// Detect and sanitise SVG markup so external SVG logos are displayed
// instead of staying blank. Sanitising also strips any active content in
// case the response is fetched through a direct (non-<img>) navigation.
if ($this->svgSanitizer->looksLikeSvg($content)) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 4-line comment above restates what the code does; per AGENTS.md please drop or cut it down. Also worth a manual check: the inherited default-src 'none' CSP may block <style> / style="" inside the SVG when loaded through <img> (GitHub adds style-src 'unsafe-inline' to raw SVGs for this reason).

$this->assertFalse($this->sanitizer->looksLikeSvg("\x89PNG\r\n"));
}

public function testLooksLikeSvgReturnsFalseForHtmlComment(): void {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add cases for the ordinary inputs and for the bypasses above: an Illustrator-style file with a public DOCTYPE, a data: image, a leading <!-- … --> comment, non-SVG XML in looksLikeSvg, escaped url(), image-set, fill="url(…)" and <animate>. nit: the new controller tests repeat the 12-line constructor call; a createController() helper would help.

This branch has not been deployed

No deployments
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.

4 participants