Repository navigation
fix(platform): harden untrusted content serving and email HTML escaping - #3133
Merged
Merged
Conversation
renderActionableEmailContent built bodyHtml by re-interpolating the
ALREADY-interpolated body, so the escapeHtml transform saw no
placeholders left and external text (inbound conversation subjects,
agent question excerpts, task/document titles, user display names)
landed raw in outbound HTML email; a hostile param containing a
literal {title} was even substituted a second time. Interpolate the
template once with the escape transform at the single point params
enter HTML; subject and plain-text lanes stay unescaped by design.
Regression tests cover hostile params, single-pass escaping, and the
placeholder-shaped-param case.
Two lanes served untrusted markup executable on the app origin: - POST /canvas-preview echoed caller HTML under a script-permissive CSP with no session check — a cross-site form POST rendered attacker script on the app origin (reflected XSS). The route (and its dev/ preview middleware twin) now requires a valid session via the backend auth oracle, and the response CSP carries 'sandbox allow-scripts allow-modals' — the same flags the in-app iframe embed already imposes — so any top-level navigation yields an inert opaque-origin document. The secureHeaders exemption is scoped to the POST so GET /canvas-preview keeps the strict SPA policy. - /branding/images served org-admin-uploaded SVGs as same-origin documents (stored XSS against every user of every org). Prod and dev/preview now deliver branding images under a bare 'sandbox' CSP plus nosniff — img/link-rel-icon embeds are unaffected, navigations are inert. Intake additionally rejects SVGs carrying script elements, on* handlers, or javascript: URLs with a dedicated error code and toast (en/de/fr); the serving headers remain the guarantee. The dev middleware also stops serving unknown extensions as octet-stream, matching prod's allowlist-or-404.
s3PresignPutUrl accepted opts.contentType and silently ignored it (and aws4fetch drops content-type from signing without allHeaders), so an uploader could mint a URL for one type and land the bytes as any other — text/html included, which the same-origin bucket proxy then served inline on navigation: stored XSS on the app origin. Two seams close the class: - PUT: a declared contentType is now signed into X-Amz-SignedHeaders, so the store refuses a PUT whose header differs. Every in-repo executor already sends the identical header; the REST mint binds only when the caller declared a type (bare curl -T clients keep working) and the API reference (en/de/fr + OpenAPI description) documents the contract. - GET: every presigned GET now signs response-content-disposition=attachment. Embeds and fetch-based previews ignore Content-Disposition, so no preview lane changes; only direct navigation becomes a download. The sandbox-blob re-stream route gets the same attachment + nosniff treatment. Also caught in the sweep: the document-replacement presign was the one browser-executed PUT not signed via browserFacing, so replacement uploads were unreachable on deployments with an internal store endpoint — now wrapped like every other browser-handed presign. backend:integration 279/279 green against a throwaway MinIO.
The Node-side test shim fed Buffer's Uint8Array<ArrayBufferLike> to new Blob(), which TS 5.7 rejects as a BlobPart; copy into a fresh Uint8Array so the backing store is a plain ArrayBuffer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes the verified class from the deep review: untrusted content served executable on the app origin, and HTML injection in outbound email. Four findings, all verified in code; none refuted. Three commits, one per seam.
Findings
1. Unauthenticated
/canvas-previewechoes attacker HTML (critical, reflected XSS)Threat: a crafted cross-site form POST navigates a victim top-level onto the app origin with attacker HTML running under
unsafe-inline/unsafe-eval— full same-origin reach (the legit flow's iframesandboxattribute exists only on the embedder, never on a top-level navigation).Fix (
server.ts,lib/canvas-preview-shell.ts,vite-plugins/serve-canvas-preview.ts):/api/sse/authoracle (the/events/filepattern; this process has no DB). The dev/preview Vite middleware mirrors the gate.buildCanvasPreviewCspnow emitssandbox allow-scripts allow-modals(noallow-same-origin) — byte-identical flags to the documented iframe embed, so the legit preview semantics are unchanged, while any top-level navigation renders an inert opaque-origin document (no cookies, no storage, no credentialed same-origin fetch, links/forms dead).secureHeadersexemption is now scoped to the POST —GET /canvas-preview(SPA fallback) previously served the shell with no CSP at all; it now keeps the strict nonce policy.Context: the canvas pane that consumed this endpoint was removed in the 0.5 rewrite (#2857); the endpoint, vendored canvas-libs, and browser tests remain as infrastructure. The hardening preserves the documented embed contract for its return.
Regression tests (
server.test.ts): unauthenticated POST → 401 without echoing the payload and without calling the oracle; oracle-refused session → 401; response CSP contains the sandbox directive and neverallow-same-origin; GET keeps strict headers. Proven failing on the unfixed source (6 failures), green with the fix. Canvas shell browser suite (real Chromium) 3/3 green.2. Branding SVG upload is stored XSS on the shared app origin (high, tenant isolation)
Threat: any org admin uploads a scripted SVG logo; navigating to
/branding/images/<org>/logo.svgexecutes it same-origin against every user of every org on the deployment.Fix (
server.ts,vite-plugins/serve-branding-images.ts,domains/branding/service.ts,core/branding/file_utils.ts):Content-Security-Policy: sandbox+X-Content-Type-Options: nosniffvia a dedicated path-scopedsecureHeadersbranch (handler-set headers get overwritten by the middleware, so it must branch there). The frontend embeds logos exclusively as<img>/<link rel=icon>(verified across the app) — those ignore a response CSP, so nothing user-visible changes; navigation becomes an inert opaque-origin document. Dev/preview middleware mirrors the headers and stops serving unknown extensions asapplication/octet-stream(now allowlist-or-404 like prod).saveBrandingImagerejects SVGs containing script elements,on*=handlers, orjavascript:URLs with a dedicatedIMAGE_SVG_ACTIVE_CONTENTcode, mapped to a precise toast in en/de/fr. Documented as best-effort (XML entity tricks can evade any regex) — the serve-side sandbox is the invariant.Regression tests: middleware-branch headers on the branding path; a real scripted SVG served from a temp config tree gets
CSP: sandbox+image/svg+xml+ nosniff (both proven failing on unfixed source); intake corpus tests (hostile/benign SVGs, non-SVG bytes not scanned); toast-key mapping test.3. Presigned PUT ignores contentType; uploaded HTML serves inline (high, stored XSS)
Threat:
s3PresignPutUrlacceptedopts.contentTypeand never signed it, so the uploader's PUT could set anyContent-Type. On default deployments the bucket is proxied same-origin (publicEndpoint= SITE_URL, Caddy forwards/<bucket>/*verbatim with zero security headers), so a presigned GET of uploader-typedtext/htmlrendered as a same-origin document.Fix (
core/lib/storage/object_store.ts+ lanes):contentTypeis signed intoX-Amz-SignedHeaders(requires aws4fetchallHeaders: true—content-typeis on its UNSIGNABLE_HEADERS list, so plainheadersis silently dropped; that trap is exactly how the original no-op happened). The store now refuses a PUT whose header differs. Every in-repo executor already sends the identical header (documents XHR, files fetch, WebDAV service PUT, knowledge-entry blobs, replacement XHR — all verified). The REST mint (/api/v1/projects/:id/uploads) binds only when the caller declared a type, so barecurl -Tclients that never declared one keep working; the API reference (en/de/fr) and the OpenAPI description now state the contract, andpublic/openapi.jsonis regenerated.response-content-disposition: attachment(named when a filename is given). Embeds andfetch()-based previews ignore Content-Disposition — all document previews fetch+DOMPurify or use<img>(verified) — so the only behavior change is that directly navigating a blob URL downloads instead of rendering. The/api/sandbox-blobre-stream gets explicitContent-Disposition: attachment+ nosniff (its consumer is in-sandbox curl/fetch, which ignores both).Also fixed in the sweep:
documents/replacement.tswas the one browser-executed presign not wrapped inbrowserFacing— replacement uploads signed against the internalobject-store:9000endpoint were unreachable from real browsers on default deployments (the integration harness runs in-cluster and cannot see it). Now wrapped like the other four browser-handed sites;backend/MIGRATION.md's "exactly four sites" is a historical increment record and was left as history.Regression tests (
object_store.test.ts, new): declared type appears inX-Amz-SignedHeaders(content-type;host), distinct types produce distinct signatures, undeclared stayshost-only; every GET carriesattachment, filename naming + control-char/quote stripping preserved. 3/7 proven failing on unfixed source.4. Notification emails embed unescaped external HTML (high)
Threat:
renderActionableEmailContentre-interpolated the already-interpolated body, so theescapeHtmltransform saw no placeholders — external text (inbound-email conversation subjects, which need no auth to set; agent question excerpts; task/document titles; user display names) landed raw in outbound HTML email. A param containing a literal{title}was even substituted a second time.Fix (
core/notifications/notification_messages.ts): the HTML lane interpolates the template exactly once with the escape transform at the single point params enter HTML; subject and plain-text lanes stay raw by design. Sweep result: this is the only HTML-email builder in the backend (no invite/digest/support/auth mail HTML exists), and the Slack lane already escapes single-pass.Regression tests: hostile params (
<script>, quotes,&, pre-entitied input escaped exactly once), placeholder-shaped params not re-interpolated, text/subject lanes unescaped, unknown-key fallback escaped. 4 proven failing on unfixed source.Refuted
None — all four findings verified in code before fixing.
Interaction with #3132 (not merged)
Sibling PR #3132 adds
GET /api/app/files/serve— a proxy-served blob route that is absent from this branch (verified). This branch hardens what exists on main. When #3132 lands, its serve route re-introduces an inline-serving surface on the app origin for these same blobs and must apply the same doctrine: safe-type allowlist for inline, otherwiseContent-Disposition: attachment+nosniff(the WebDAV GET handler and the sandbox-blob route in this branch are the in-tree templates). With this branch's PUT binding, a blob's stored Content-Type is trustworthy wherever the mint declared one — which makes that allowlist meaningful.Cross-class discoveries (not addressed here)
domains/sso/routes.tsinterpolatesBASE_PATHunescaped into an inline script string and hrefs — operator-controlled env, not user input; worth a defensive escape someday.method: "POST"response for the platform-storage lane; the 0.5 handoff answersPUTfor the S3 lane — example drift predates this branch.browserFacingas identity (nopublicEndpointin its seeded store), so it structurally cannot catch a missing-browserFacingregression — the class the replacement-lane bug sat in.Verification
server+pii): 375 files / 72,309 tests green (worktree reinstall was needed for 3 pre-existing vite fs-deny failures in app-route suites — unrelated to this diff).test:ui: 447 files / 3,453 green (locale parity + usage for the new toast key).@tale/ui(i18n framework checks) 124/1,173 green;@tale/docsgreen.oxlint --type-aware: clean. Pre-commit opengrep SAST: 0 findings.backend:integrationagainst a throwaway tale-db + MinIO: 279/279 green — covers presign→PUT→bind, REST v1 uploads, replacement lanes, knowledge RAG, audit export, BYO residency with the binding + attachment changes live.git stashruns) before passing with the fix.