Skip to content

fix(platform): harden untrusted content serving and email HTML escaping - #3133

Merged
larryro merged 4 commits into
mainfrom
fix/xss-content-hardening
Sep 3, 2026
Merged

larryro merged 4 commits into
mainfrom
fix/xss-content-hardening

Conversation

@larryro

@larryro larryro commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

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-preview echoes 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 iframe sandbox attribute 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):

  • The route now requires a valid session, validated against the backend /api/sse/auth oracle (the /events/file pattern; this process has no DB). The dev/preview Vite middleware mirrors the gate.
  • buildCanvasPreviewCsp now emits sandbox allow-scripts allow-modals (no allow-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).
  • The secureHeaders exemption 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 never allow-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.svg executes 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):

  • Serve side (the guarantee): branding images are delivered under a bare Content-Security-Policy: sandbox + X-Content-Type-Options: nosniff via a dedicated path-scoped secureHeaders branch (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 as application/octet-stream (now allowlist-or-404 like prod).
  • Intake (UX nicety): saveBrandingImage rejects SVGs containing script elements, on*= handlers, or javascript: URLs with a dedicated IMAGE_SVG_ACTIVE_CONTENT code, 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: s3PresignPutUrl accepted opts.contentType and never signed it, so the uploader's PUT could set any Content-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-typed text/html rendered as a same-origin document.

Fix (core/lib/storage/object_store.ts + lanes):

  • PUT: a declared contentType is signed into X-Amz-SignedHeaders (requires aws4fetch allHeaders: true — content-type is on its UNSIGNABLE_HEADERS list, so plain headers is 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 bare curl -T clients that never declared one keep working; the API reference (en/de/fr) and the OpenAPI description now state the contract, and public/openapi.json is regenerated.
  • GET: every presigned GET now signs response-content-disposition: attachment (named when a filename is given). Embeds and fetch()-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-blob re-stream gets explicit Content-Disposition: attachment + nosniff (its consumer is in-sandbox curl/fetch, which ignores both).

Also fixed in the sweep: documents/replacement.ts was the one browser-executed presign not wrapped in browserFacing — replacement uploads signed against the internal object-store:9000 endpoint 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 in X-Amz-SignedHeaders (content-type;host), distinct types produce distinct signatures, undeclared stays host-only; every GET carries attachment, filename naming + control-char/quote stripping preserved. 3/7 proven failing on unfixed source.

4. Notification emails embed unescaped external HTML (high)

Threat: renderActionableEmailContent re-interpolated the already-interpolated body, so the escapeHtml transform 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, otherwise Content-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.ts interpolates BASE_PATH unescaped into an inline script string and hrefs — operator-controlled env, not user input; worth a defensive escape someday.
  • The REST upload doc example still shows a method: "POST" response for the platform-storage lane; the 0.5 handoff answers PUT for the S3 lane — example drift predates this branch.
  • The integration harness signs browserFacing as identity (no publicEndpoint in its seeded store), so it structurally cannot catch a missing-browserFacing regression — the class the replacement-lane bug sat in.

Verification

  • Platform unit suites (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/docs green.
  • Browser project (real Chromium): canvas shell 3/3.
  • Typecheck: 0 errors. oxlint --type-aware: clean. Pre-commit opengrep SAST: 0 findings.
  • backend:integration against 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.
  • Every new regression test demonstrated failing against the unfixed source (via git stash runs) before passing with the fix.

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.
@larryro
larryro marked this pull request as ready for review September 3, 2026 03:51
@larryro
larryro merged commit 7db2b78 into main Sep 3, 2026
23 checks passed
@larryro
larryro deleted the fix/xss-content-hardening branch September 3, 2026 03:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant