From be8d79e9c4b6148a0b3f8a1f81f05fbf5fbf6880 Mon Sep 17 00:00:00 2001 From: Paul Nothaft Date: Fri, 4 Sep 2026 20:39:43 +0200 Subject: [PATCH 1/9] fix(gallery): release the canvas-mode decode, and drop a now-duplicate sanitizer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two follow-ups to yesterday's merges. Both were already known; neither depends on the open question in #1287. 1. Canvas mode pinned every decoded image for the component's lifetime. `AuthenticatedImage` keeps a detached Image in `imageRef` so drawToCanvas can read it. The effect cleanup nulled onload/onerror and never cleared that ref, so the Image — and the decode behind it — stayed held by a live JS reference. A decoded in the document is evictable under memory pressure; one held by a ref is not. That is not academic at gallery scale. The photo grid is NOT virtualised, so a 546-photo event mounts 546 of these and none ever unmount — nothing was ever released. The ref is cleared and the src dropped, so the browser can reclaim without waiting for GC. This is NOT presented as the fix for #1287. That investigation is still open: the reporter has since shown the backend idle during a stall and the renderer itself unresponsive for 45s, which rules out the theories tried so far. This is a real leak on the same path, worth fixing on its own terms while that question is settled. 2. newsletterService no longer carries its own remote-url() stripper. It was added because the shared sanitizeCSS "blocked" remote URLs with a CSS comment that parsers discard. #1290 replaced that with a lexer, so the local copy is dead weight — and two definitions of "disallowed" would drift apart. Verified the shared function covers every case the local one did, including the quoted-paren and CSS-escape forms found in review. Three tests on the release path, two of which fail without the fix: unmount clears the ref and drops the src, the blob URL is revoked, and a src change releases the previous image rather than accumulating one pinned decode per photo a recycled tile has shown. --- backend/src/services/newsletterService.js | 36 ++---- .../components/common/AuthenticatedImage.tsx | 14 +++ .../AuthenticatedImage.canvasRelease.test.tsx | 104 ++++++++++++++++++ 3 files changed, 126 insertions(+), 28 deletions(-) create mode 100644 frontend/src/components/common/__tests__/AuthenticatedImage.canvasRelease.test.tsx diff --git a/backend/src/services/newsletterService.js b/backend/src/services/newsletterService.js index 46da3528..eaec1f76 100644 --- a/backend/src/services/newsletterService.js +++ b/backend/src/services/newsletterService.js @@ -141,44 +141,24 @@ function sanitizeCampaignBody(html) { }, }) // sanitize-html keeps the style ATTRIBUTE contents verbatim. Clean each. + // sanitizeCSS blocks remote url() properly as of #1290 — it lexes the CSS + // rather than pattern-matching it, so the local pass this used to need is + // gone. Keeping a second copy would mean two definitions of "disallowed" + // drifting apart. .replace(/style="([^"]*)"/gi, (match, css) => { const { sanitized } = sanitizeCSS(css); - const cleaned = stripRemoteCssUrls(sanitized); - return cleaned ? `style="${cleaned.replace(/"/g, '')}"` : ''; + return sanitized ? `style="${sanitized.replace(/"/g, '')}"` : ''; }); } -/** - * Remove every `url(...)` that is not an inline data: image. - * - * The shared `sanitizeCSS` *detects* a remote url() and prefixes it with a - * `/* BLOCKED URL *\/` comment — but a CSS comment is stripped during - * tokenization, so the declaration a mail client actually parses still - * carries the live URL. Verified: - * - * sanitizeCSS('.a{background:url(https://x/p.gif)}').sanitized - * → '.a{background:/* BLOCKED URL *\/ url(https://x/p.gif)}' - * - * In a newsletter that is a tracking pixel delivered to every recipient, so - * this pass actually removes the token. Scoped to the newsletter path on - * purpose: the same weakness affects gallery custom CSS, but changing shared - * sanitizer behaviour is a separate change with its own blast radius. - */ -function stripRemoteCssUrls(css) { - if (!css) return ''; - return String(css) - .replace(/\/\*\s*BLOCKED URL\s*\*\//gi, '') - .replace(/url\s*\(\s*(['"]?)([^)'"]*)\1\s*\)/gi, (match, _quote, target) => - (/^data:image\/(?:jpeg|jpg|png|gif|webp)/i.test(target.trim()) ? match : 'none')); -} - /** * Sanitize a campaign's optional `'); }); }); + +describe('inline CSS is re-checked after template substitution', () => { + // The stored body is sanitized, but safeTemplateReplace rewrites it + // afterwards — so the string that was validated is not the string that is + // sent. A conditional inside a style attribute can delete the quoting that + // made a url() inert, which no amount of lexer correctness can catch. + const payload = + `

hi

`; + + it('neutralises a url() that substitution would activate', () => { + const stored = sanitizeCampaignBody(payload); + // Correctly left alone at write time: the url() really is inside a CSS + // string while the conditionals are still in place. + expect(stored).toContain('evil.example'); + + const substituted = safeTemplateReplace(stored, { company_name: '' }, { escapeHtml: true }); + // Expansion removed the quotes, so without the recheck this ships live. + expect(substituted).toMatch(/background:url\(https:\/\/evil\.example/); + + const rendered = sanitizeInlineStylesAfterSubstitution(substituted); + expect(rendered).not.toMatch(/url\(\s*['"]?https:\/\/evil\.example/); + expect(rendered).toContain('background:none'); + }); + + it('leaves a body without style attributes untouched', () => { + const html = '

Hello {{first_name}}

'; + expect(sanitizeInlineStylesAfterSubstitution(html)).toBe(html); + }); + + it('keeps legitimate inline styles through the recheck', () => { + const html = '

hi

'; + const out = sanitizeInlineStylesAfterSubstitution(html); + expect(out).toContain('color:red'); + expect(out).toContain('font-size:14px'); + }); + + it('is safe on empty and nullish input', () => { + expect(sanitizeInlineStylesAfterSubstitution('')).toBe(''); + expect(sanitizeInlineStylesAfterSubstitution(null)).toBeNull(); + }); +}); diff --git a/backend/src/services/newsletterService.js b/backend/src/services/newsletterService.js index 8a29f79a..9c991ef2 100644 --- a/backend/src/services/newsletterService.js +++ b/backend/src/services/newsletterService.js @@ -154,10 +154,37 @@ function sanitizeCampaignBody(html) { // inside a real string, then makes the url() request — while the scanner // saw the apostrophe open a string and skipped everything after it. The // scanner has to be shown what the browser will actually parse. - .replace(/style="([^"]*)"/gi, (match, css) => { - const { sanitized } = sanitizeCSS(decodeHtmlEntities(css)); - return sanitized ? `style="${encodeForAttribute(sanitized)}"` : ''; - }); + .replace(STYLE_ATTRIBUTE, sanitizeStyleAttribute); +} + +/** Shared by the write-time sanitize and the post-substitution recheck. */ +const STYLE_ATTRIBUTE = /style="([^"]*)"/gi; + +function sanitizeStyleAttribute(match, css) { + const { sanitized } = sanitizeCSS(decodeHtmlEntities(css)); + return sanitized ? `style="${encodeForAttribute(sanitized)}"` : ''; +} + +/** + * Re-check inline CSS AFTER template substitution. + * + * Sanitizing runs on the stored body, but `safeTemplateReplace` rewrites it + * afterwards — so the string that was validated is not the string that gets + * sent. A conditional inside a style attribute can delete the very characters + * that made a URL inert: + * + * style="--x:x{{#if company_name}}'{{/if}};background:url(https://evil…)" + * + * At sanitize time the url() sits inside a CSS string and is correctly left + * alone; once the conditional is expanded the quotes are gone and the + * background is live. No amount of lexer correctness fixes that, because the + * text being lexed is not the text being delivered — the check has to run + * again on the final output. Substitution cannot introduce a `"` (values are + * HTML-escaped), so the attribute regex still matches what it should. + */ +function sanitizeInlineStylesAfterSubstitution(html) { + if (!html) return html; + return String(html).replace(STYLE_ATTRIBUTE, sanitizeStyleAttribute); } /** @@ -330,7 +357,12 @@ async function renderForRecipient(campaign, customer, options = {}) { // Substitution happens AFTER sanitizing, with escaping on: a customer's own // company name is untrusted text and must not be able to inject markup by // riding in through a variable the sanitizer never saw. - const body = safeTemplateReplace(safeBody, variables, { escapeHtml: true }); + // Re-checked after substitution, not only before it: expansion can remove + // the quoting that made a url() inert at sanitize time. See + // sanitizeInlineStylesAfterSubstitution. + const body = sanitizeInlineStylesAfterSubstitution( + safeTemplateReplace(safeBody, variables, { escapeHtml: true }) + ); const subject = safeTemplateReplace(campaign.subject || '', variables); const { css } = sanitizeCampaignCss(campaign.body_css); @@ -942,6 +974,7 @@ async function sendTest(campaignId, toEmail, adminId) { module.exports = { sanitizeCampaignBody, + sanitizeInlineStylesAfterSubstitution, sanitizeCampaignCss, unsubscribeToken, verifyUnsubscribeToken, From 1151e96144a9ada7170461e829d2f3d5dcc8edb2 Mon Sep 17 00:00:00 2001 From: Paul Nothaft Date: Sat, 5 Sep 2026 15:30:04 +0200 Subject: [PATCH 9/9] fix(security): validate CSS urls last, after every pass that moves text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fifth bypass, and the same root cause as the first: sanitizeCSS validated, then kept rewriting. `<[^>]*>` deletes the span it matches, and `<">` takes a quote with it. So `--x:x<">;background:url(https://evil.example/p.gif);--y:x<">` was scanned with the url() safely inside a string, and the tag strip below then removed the quotes that made it so — shipping a live remote background with no warning. The file already carried the rule: "any pass that can join tokens has to happen before validation, not after." It has now been broken three separate times — by the HTML-comment strip (#1290), the control- character strip, and the tag strip. Rather than fix a third instance in place, the URL scan is now the LAST step, so what is validated is always the bytes that get served. All eight known bypass classes are pinned, together with the legitimate data: URI, quoted font stack and escaped selector that must survive untouched. Refs #1264 --- .../utils/cssSanitizer.remoteUrls.test.js | 11 +++++++++++ backend/src/utils/cssSanitizer.js | 16 +++++++++++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/backend/__tests__/utils/cssSanitizer.remoteUrls.test.js b/backend/__tests__/utils/cssSanitizer.remoteUrls.test.js index be8c39fe..30d1e035 100644 --- a/backend/__tests__/utils/cssSanitizer.remoteUrls.test.js +++ b/backend/__tests__/utils/cssSanitizer.remoteUrls.test.js @@ -260,6 +260,17 @@ describe('sanitizeCSS', () => { expect(asParsed(sanitized)).not.toContain('evil.example'); }); + it('blocks a url() the TAG strip would have un-quoted', () => { + // `<[^>]*>` deletes the span it matches, and `<">` takes a quote with it. + // Running that after the URL scan meant the scanner saw the url() safely + // inside a string and this pass then removed the quotes that made it so. + // URL validation has to be the last thing that looks at the text. + const { sanitized } = sanitizeCSS( + '--x:x<">;background:url(https://evil.example/p.gif);--y:x<">' + ); + expect(asParsed(sanitized)).not.toContain('evil.example'); + }); + it('does not treat NBSP as CSS whitespace inside url()', () => { // JS `\s` matches U+00A0; CSS whitespace does not. Skipping it let the // scanner read the following quote as a legitimate data: URI and swallow diff --git a/backend/src/utils/cssSanitizer.js b/backend/src/utils/cssSanitizer.js index 98df28ea..b8780d68 100644 --- a/backend/src/utils/cssSanitizer.js +++ b/backend/src/utils/cssSanitizer.js @@ -345,6 +345,19 @@ function sanitizeCSS(cssContent) { // below it then produced exactly the request the scan was there to // prevent. Any pass that can join tokens has to happen before validation, // not after. + // Remove any remaining script-like content. This is the LAST pass that can + // move text, and so it must run before the URL scan, not after: it deletes + // the matched span, and a span like `<">` takes a quote with it. That is + // how `--x:x<">;background:url(https://evil.example/p.gif);--y:x<">` shipped + // a live background — the scanner saw the url() safely inside a string, and + // this line then removed the quotes that made it so. + sanitized = sanitized.replace(/<[^>]*>/g, '/* BLOCKED TAG */'); + + // URL validation runs LAST, deliberately. Every pass above rewrites the + // text, and each one that did so after this point has produced a bypass: + // the HTML-comment strip (#1290), the control-character strip, and the tag + // strip immediately above. Validating anything other than the final bytes + // means validating a string that is not the one that gets served. const urlPass = stripDisallowedUrls(sanitized); if (urlPass.blocked > 0) { warnings.push( @@ -354,9 +367,6 @@ function sanitizeCSS(cssContent) { sanitized = urlPass.sanitized; } - // Remove any remaining script-like content - sanitized = sanitized.replace(/<[^>]*>/g, '/* BLOCKED TAG */'); - return { sanitized: sanitized.trim(), warnings }; }