Skip to content

Opaque-origin published viewer and opt-in opaque editor preview - #56

Draft
erseco wants to merge 116 commits into
mainfrom
feature/secure-iframe-sandbox
Draft

erseco wants to merge 116 commits into
mainfrom
feature/secure-iframe-sandbox

Conversation

@erseco

@erseco erseco commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Published viewer

Extracted packages render in a sandboxed opaque-origin iframe, so author HTML
and JavaScript cannot reach the WordPress page, its cookies or the REST nonce.
External video still plays: the shared shim demotes each provider iframe inside
the package and a relay on the trusted page overlays the real player.

EXELEARNING_UNSAFE_LEGACY_IFRAME is a development-only escape hatch for the
php-wasm Playground. It is not an administration setting and never applies to the
editor preview.

Editor preview

Filtered by default. Enabling active content POSTs the project as one snapshot
to an authenticated route and serves it from an authless capability URL under a
sandbox CSP, with a 30-minute idle TTL:

POST/DELETE  {REST}/exelearning/v1/preview-session/*   cookie + X-WP-Nonce + upload_files
GET          {REST}/exelearning/v1/preview/{id}/*      authless, unguessable UUID

Snapshots are capped at 1 GB and 10 000 entries, both overridable
(EXELEARNING_PREVIEW_MAX_BYTES / exelearning_preview_max_bytes, and the
_files equivalents). Over the limit the grant fails closed and the filtered
preview stays. Archives are vetted before a byte is written: entry count,
declared uncompressed size, path traversal, reserved names and symlinks.

Also here

A loading indicator while an embedded package paints, and the attachment UI
aligned with native WordPress.

The frontend shortcode and Gutenberg block embedded .elpx content with
sandbox="allow-scripts allow-same-origin allow-popups", served same-origin. With
allow-same-origin the arbitrary author HTML/JS can read the WordPress page's
cookies/DOM and reach window.parent. Add an exelearning_iframe_sandbox_mode option
(secure default | legacy): secure drops allow-same-origin so the content runs in an
opaque origin and is isolated from the page; legacy restores the previous behaviour
for environments that need it (e.g. WordPress Playground, whose service worker only
serves same-origin documents).

A single ExeLearning_Iframe_Sandbox helper owns the option and the per-mode sandbox
tokens, consumed by both the shortcode and the block. Teacher mode used same-origin
contentDocument access, which cannot run against an opaque iframe; in secure mode the
desired state is carried on the iframe src (exe-teacher / exe-teacher-toggler) and the
content proxy applies it server-side (hide-toggler style and mode-teacher class), so
no parent-to-iframe DOM access is involved. The legacy contentDocument path is kept
for legacy mode. No CSP change is needed: the proxy's existing default-src 'self'
resolves to the serving origin and loads same-host subresources under the opaque
origin (verified in a browser). An admin setting under Settings -> eXeLearning lets
admins switch modes, and the Playground blueprint forces legacy.

Adds unit tests for the helper, the shortcode and block sandbox tokens per mode, the
secure teacher-mode src params, and the proxy's server-side teacher-mode injection.
@github-actions

github-actions Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Test in WordPress Playground

Test the plugin with the code from this branch:

Preview in WordPress Playground

ℹ️ The eXeLearning editor is fetched from the shared release and unpacked into the plugin when the playground boots, so the first load may take a few extra seconds. ELP upload, shortcode, Gutenberg block and preview work normally.

erseco added 3 commits June 13, 2026 17:44
Adds the new "Security" settings card strings to the POT and translates them in all
maintained locales (ca, ca_valencia, de_DE, eo, es_ES, eu, gl_ES, it_IT, pt_PT, ro_RO)
so the untranslated-strings check passes. Also drops the redundant card subtitle and
shortens the field help text.
… hardening)

Even with the secure iframe, the proxied content is served same-origin with an
executable CSP, so opening the raw /wp-json/exelearning/v1/content/{hash}/index.html URL
top-level (e.g. manual navigation) would run author JS as the WordPress origin. Add a
`sandbox allow-scripts allow-popups` CSP directive for HTML in secure mode so the
document keeps an opaque origin however it is loaded; legacy is unchanged. Extracted a
testable build_html_csp() helper.

Verified in wp-env: opening the raw content URL top-level now reports
window.origin === 'null' and document.cookie throws SecurityError, while the content
still renders.
@erseco

erseco commented Jun 13, 2026

Copy link
Copy Markdown
Contributor Author

Live verification (secure mode, default)

Brought this branch up with wp-env (:8890) and embedded an .elpx via [exelearning id=…]. Inspecting the rendered iframe from the host page:

  • sandbox="allow-scripts allow-popups" — no allow-same-origin → opaque origin.
  • From the parent: iframe.contentDocument is null and iframe.contentWindow.location throws SecurityError.

By the symmetry of the same-origin policy, the author content cannot read the WordPress DOM, cookies or nonce, nor reach window.parent. The same-origin escape chain (forge an authenticated request with a nonce scraped from the parent) is cut.

The backing content-proxy hardening checks out: HTML responses carry script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; frame-ancestors …; form-action 'self' and, in secure mode, a response-level sandbox allow-scripts allow-popups directive — so the content keeps an opaque origin even when opened directly (new tab / escaped popup / raw content URL), and connect-src 'self' blocks external exfiltration.

External-embed compatibility (worth a docs note). Because the content runs in an opaque origin and connect-src/frame-src are restricted:

  • External images and direct HTML5 video/audio files over https work (img-src/media-src include https:).
  • YouTube/Vimeo <iframe> are allowed by frame-src https: but the no-allow-same-origin sandbox propagates to the nested player, which then loses its own origin/cookies and typically fails — i.e. third-party video embeds do not work in secure mode. A plain PDF in an <iframe> may still render; <object>/<embed> are blocked (object-src).

This is an inherent trade-off of opaque-origin isolation, not a bug — just worth documenting for authors.

Note on #54 (asset proxy): both PRs touch class-content-proxy.php and class-admin-settings.php — expect a merge conflict, and a combined test that a proxied .js still executes inside the opaque iframe would be worthwhile.

erseco added 6 commits June 14, 2026 06:02
In secure mode the .elpx content runs in an opaque-origin sandbox, so cross-origin
players (YouTube/Vimeo) and PDFs render blank (the sandbox flag propagates to nested
iframes; Chrome also blocks its PDF viewer without allow-same-origin). Promote those
embeds to the embedding page: the content proxy injects a shim that replaces
whitelisted-video / .pdf iframes with placeholders and reports their geometry via
postMessage; a relay enqueued on the shortcode/block page validates + rebuilds the URL
and overlays the real player inline over each placeholder.

- assets/js/exe-embed-shim.js / exe-embed-relay.js: the shared shim + relay.
- class-content-proxy.php: inject the shim into served HTML (secure only).
- class-iframe-sandbox.php: embed_whitelist() + enqueue_embed_relay().
- class-shortcodes.php / class-elp-upload-block.php: enqueue the relay (secure).

PDFs: local package PDFs always render; any https .pdf renders; same-origin PDFs must
belong to this package (served as application/pdf, never executable HTML). Tests in
ContentProxyTest + IframeSandboxTest. Verified live in wp-env: YouTube, Vimeo and
remote + local PDF render inline; a non-whitelisted iframe is not promoted.
The shim runs inside the content, so it resolves each iframe src against the content
location and reports the ABSOLUTE URL. The parent relay resolves URLs against the host
page, so a relative src (e.g. a locally-packaged PDF) would otherwise be rejected.
Keeps parity with the mod_exelearning + omeka shim.
Add a self-contained Playwright/Firefox end-to-end test that loads the
real exe-embed shim and relay against a static harness (no WordPress
runtime needed) and verifies that whitelisted video and local PDF embeds
are promoted to inline players on the parent page while other origins are
rejected. Document the external-embed flow and how to run the test in the
README.
…ywright config

The dedicated playwright-embed.config.cjs runs the external-embed e2e in Firefox against
its own static harness; the main config (chromium + wp-env) was auto-discovering it and
failing. Exclude it via testIgnore. Also assert the non-whitelisted host with an exact
hostname check (new URL().hostname) instead of a URL substring match.
…av fix

Bring the WordPress embed relay/shim in line with the canonical mod_exelearning
source:

- Add Dailymotion and EducaMadrid/Mediateca de Madrid external-embed providers
  (allowlist hosts + per-provider canonical-URL validators in the relay).
- Clamp the relayed player overlay to the placeholder box (clickjacking defence in
  depth; the overlay already clips with overflow:hidden).
- Add allow-forms to the secure sandbox tokens, including the response-level CSP
  sandbox directive, so the form-based eXeLearning iDevices can submit inside the
  opaque sandbox. Align the legacy tokens with the canonical set.
- Fix a lingering external embed when the eXe content pages to another view: the
  in-iframe shim restarts its embed-id counter per page, so a reused id could keep
  the previous page's player; tag each player with its URL and replace it when a
  reused id maps to a different URL.

Update the IframeSandbox and ContentProxy unit tests for the new tokens and hosts.
@erseco
erseco marked this pull request as draft June 14, 2026 12:21
erseco added 14 commits June 14, 2026 16:16
…) + embed policy

Bring the WordPress embed relay/shim in line with the canonical mod_exelearning DEC-0061
change: drop the host allowlist for the default 'open' policy and promote any iframe whose
src is https AND cross-origin to the WordPress host (rejecting same-origin, sub/superdomains,
IP/loopback/local hosts and userinfo); a 'strict' policy keeps the allowlist + per-provider
reconstruction. The promoted video player is sandboxed (allow-scripts allow-same-origin
allow-popups allow-forms allow-presentation; no top-navigation/modals) so an arbitrary embed
cannot redirect the tab while the cross-origin provider still renders; PDFs stay unsandboxed.
Add the D1 same-origin-landing guard and the D2 forged-message defence (promoted players
tagged data-exe-embed-player, excluded from the content-source lookup).

Add an exelearning_embed_mode option (open default, fail-safe to strict) + an "External embed
policy" select in the admin Security settings, inject {mode, whitelist} into the relay config,
and update the IframeSandbox tests. Mirrors mod's logic (no drift).
…pen default + exelearning_embed_mode option

The 10 maintained .po files require every string translated; the new select
labels were untranslated and no canonical pot regeneration is available here.
The embed policy still resolves from the exelearning_embed_mode option
(default open), so the feature is unchanged; a localized UI can follow.
- Relay/shim: port the trailing-dot FQDN-root host normalization
  (normalizeHost) so the served host in 'host.' form is treated as same-host
  and not promoted as a cross-origin player.
- Relay: hoist the content-iframe rect read out of the per-embed loop (one
  reflow per sync) and adopt the canonical dual-export tail (Node-requireable
  for tests; browser auto-run unchanged).
- Content proxy: drop the unused window.__exeEmbedWhitelist injection;
  Referrer-Policy same-origin -> no-referrer on served files.
- Sandbox: ship the embed whitelist only in strict mode.
- Add a Vitest relay unit suite (happy-dom) covering the structural gate,
  including the trailing-dot cases.
…-sandbox

# Conflicts:
#	languages/exelearning-ca.mo
#	languages/exelearning-ca.po
#	languages/exelearning-ca_valencia.mo
#	languages/exelearning-ca_valencia.po
#	languages/exelearning-de_DE.mo
#	languages/exelearning-de_DE.po
#	languages/exelearning-eo.mo
#	languages/exelearning-eo.po
#	languages/exelearning-es_ES.mo
#	languages/exelearning-es_ES.po
#	languages/exelearning-eu.mo
#	languages/exelearning-eu.po
#	languages/exelearning-gl_ES.mo
#	languages/exelearning-gl_ES.po
#	languages/exelearning-it_IT.mo
#	languages/exelearning-it_IT.po
#	languages/exelearning-pt_PT.mo
#	languages/exelearning-pt_PT.po
#	languages/exelearning-ro_RO.mo
#	languages/exelearning-ro_RO.po
#	languages/exelearning.pot
#	tests/unit/ContentProxyTest.php
Reconcile teacher-mode handling with main (#58). main retired host-side CSS/JS
injection in favour of the package's own ?exe-teacher=1 URL parameter, so the
secure-iframe branch is aligned to the same contract:

- public/class-shortcodes.php, includes/class-elp-upload-block.php: keep the
  secure-mode embed-relay enqueue and opaque-iframe rendering, but drop the
  legacy teacher injection. The selector is offered by appending ?exe-teacher=1
  to the iframe src when teacher_mode_visible (or the legacy teacher_mode attr)
  is on. This rides through the secure-mode content proxy too: the package reads
  its own location.search even under the opaque origin, so no host injection is
  needed.
- includes/class-content-proxy.php: retire inject_teacher_mode() and the
  exe-teacher-toggler / exe-teacher server-side rewriting. It injected the exact
  #teacher-mode-toggler-wrapper CSS that #58 retired and, worse, auto-activated
  mode-teacher on ?exe-teacher=1 — which contradicts core (the parameter only
  offers the selector, it never auto-reveals). Keep inject_embed_shim().
- Tests: update ShortcodesTest / ElpUploadBlockTest secure-mode cases to assert
  the param-based contract (exe-teacher=1, no exe-teacher-toggler, no
  contentDocument) and drop the ContentProxyTest inject_teacher_mode cases.

Other conflicts:
- package.json: union — main's @playwright/test and @wordpress/env bumps plus
  the branch's vitest + happy-dom (used by tests/js). Lockfile regenerated.
- languages: msgcat union of both sides (main's strings authoritative, the
  branch's secure-mode admin strings preserved), .mo recompiled, JED .json taken
  from main (elp-upload.js is byte-identical to main), .pot unioned. CI
  regenerates references.

The admin block-editor live preview (assets/js/elp-upload.js) keeps main's
same-origin preview behaviour unchanged.
…067)

Mirror the id-only channel (extractProvider/reconstructProvider) into the embed shim/relay. Add exe-media-policy.js + exe-media-host.js (vendored from mod_exelearning) and enqueue_media_host() in ExeLearning_Iframe_Sandbox, called from the block + shortcode renderers: parent-side host for the interactive-video iDevice via raw postMessage (no YouTube IFrame API/Vimeo SDK). No-op in legacy.
… on re-open

M-3: makePlayer() rendered a cross-origin .pdf in a fully unsandboxed iframe, so
an author-supplied https://evil/x.pdf serving HTML could top-navigate the host
tab to a phishing page (reachable in both open and strict mode). Mirror the
canonical Moodle 3-way branch: a same-origin package PDF stays unsandboxed (the
browser PDF viewer needs it), a cross-origin PDF gets sandbox="allow-same-origin"
(no allow-scripts, no allow-top-navigation).

L-2: the modal media host appended a new <dialog> and overwrote session.adapter
on every 'open' without tearing down the previous one, so repeated 'open'
commands could stack modals and orphan provider players. openMedia() now discards
the prior media/poll-timer/dialog first (single active media per session).

Tests: cross-origin vs same-origin PDF sandbox; media-host single-active teardown.
…nly escape hatch

The content iframe is now always opaque-origin: the same-origin admin mode was removed.
A dev-only escape hatch (EXELEARNING_UNSAFE_LEGACY_IFRAME constant, default off, never in
the admin UI) restores same-origin only for environments that cannot serve opaque subframes
(the php-wasm WordPress Playground). It surfaces a loud admin warning when active.

- class-iframe-sandbox: mode() is always secure unless the unsafe constant is defined;
  embed_mode() defaults to strict (open is opt-in); add a CSP profile (strict default,
  exelearning_csp_profile filter -> compatible).
- content-proxy: build_html_csp() strict by default (no bare https: in script/img/media-src;
  frame-src limited to the maintained providers) with a documented-weaker compatible profile.
- admin settings: replace the secure/legacy selector with a read-only status + escape-hatch
  warning. blueprint.json defines the unsafe constant instead of update_option('...','legacy').
- Tests: legacy option ignored, strict embed/CSP defaults, compatible profile, escape hatch
  off by default. Add testing-the-sandbox.elpx fixture.

NOTE: validated locally by php -l + vitest (28 JS tests). The PHPUnit + phpcs run in PR CI
(no composer/WP test harness here).
…ways-secure settings card

The php-wasm Playground service worker only serves same-origin documents, so the opaque
content iframe could not load its CSS/JS. The escape hatch is now delivered by a Playground-only
mu-plugin (loads before all plugins, defines a real boolean EXELEARNING_UNSAFE_LEGACY_IFRAME)
instead of defineWpConfigConsts, and is_unsafe_legacy() accepts any truthy value (filter_var).

Also removes the read-only "always secure" Security card from the admin settings (it only
stated the obvious); the dev-only escape-hatch warning now renders only when the hatch is active.
…u-plugin

The admin-settings warning for the EXELEARNING_UNSAFE_LEGACY_IFRAME escape hatch was
the only new translatable string in this PR, and the check-untranslated CI gate requires
every languages/*.po to be fully translated — so it failed. The warning only ever shows
when the dev-only hatch is active, which in practice is the WordPress Playground. Move it
into the Playground-only mu-plugin (plain English, not scanned by make-pot) as an
admin_notices banner, and drop render_security_section() from the shipped plugin. The
hatch itself (is_unsafe_legacy) is unchanged and still covered by IframeSandboxTest.
…yground comment

Two PHPUnit tests still drove the same-origin sandbox via the removed admin option
(update_option(OPTION, MODE_LEGACY)) and asserted allow-same-origin. Always-opaque
ignores that option, so they failed once the untranslated gate (which masked them)
passed. Rewrite both as regression guards: the ignored legacy option must keep the
content/block iframe opaque (no allow-same-origin); the dev-only constant hatch is the
only same-origin path (covered by IframeSandboxTest). Also trim the Playground mu-plugin
comment — the full php-wasm rationale now lives in the PR description.
eXeLearning core (public/app/common/exe_embed_bridge/) is now the canonical source
for the promote-to-parent embed relay/shim; this copy mirrors it. Header comment only —
no logic change (verified by core's scripts/check-embed-sync.mjs: no drift).
@erseco

erseco commented Jul 2, 2026

Copy link
Copy Markdown
Contributor Author

The external-embed bridge (exe-embed-shim.js / exe-embed-relay.js) header now declares this copy as a mirror of eXeLearning core, the canonical source: exelearning/exelearning public/app/common/exe_embed_bridge/ (PR exelearning/exelearning#1968). Comment-only change; no logic change (the invariant checker scripts/check-embed-sync.mjs in core reports no drift). Note: this copy is an older structural revision reformatted to this project's code style — functionally in sync with core; a full structural re-vendor from core is a documented follow-up, not required now.

erseco added 2 commits July 6, 2026 13:19
…rence)

Mirror of the eXeLearning core canonical contract
(exelearning/doc/development/preview-serving-contract.md): serve the editor
preview of untrusted author content over an authless capability URL in an opaque
origin, via this host's own cookieless serving primitive, so the preview gets
real per-page URLs (working navigation + open-in-new-tab) instead of the srcdoc
fallback. The sandbox-first CSP is emitted verbatim from core's previewCspHeader()
on every scriptable document type (text/html, image/svg+xml, application/xml,
application/xhtml+xml). Reference endpoint + docs; the session store, management
API and tests are follow-up per repo.
Remove stray markdown (a code fence + wiring-notes prose) accidentally left after
the class closing brace, convert the aligned route-list inline comment to a block
comment, capitalize a docblock short description, and end the file with a single
newline. phpcs --standard=.phpcs.xml.dist now clean.
erseco added a commit that referenced this pull request Sep 26, 2026
Package HTML uploaded by any author is served on the WordPress origin, and
the Media Library grid, attachment details and attachment meta box framed it
with allow-scripts allow-same-origin: an admin opening the Media Library ran
the author's script with full access to wp-admin. Drop allow-same-origin from
those three previews so the package gets an opaque origin. The package's
teacher-mode toggle cannot initialise there (no storage in an opaque origin);
the preview otherwise renders unchanged. The published viewer and the new-tab
links are left to the opaque-origin viewer work in #56.

The editor modal accepted a relayed request-save from any window, and the
bridge inside the editor iframe accepted save/export/project-info commands
from any sender. The modal now only accepts the relay from its own window and
origin; the bridge only from its parent, and from the declared parent origin
when one is configured.
erseco added a commit that referenced this pull request Sep 26, 2026
Playground serves every request from a Service Worker, which does not handle
opaque-origin subframes, so the now-sandboxed wp-admin previews rendered blank
there. Add the dev-only EXELEARNING_UNSAFE_LEGACY_IFRAME escape hatch (same
name and semantics as #56) that restores allow-same-origin for these previews,
and define it from a Playground-only mu-plugin in blueprint.json, which also
shows an admin notice that the unsafe mode is on. Production sites never set
it and keep the opaque origin.
erseco and others added 4 commits September 26, 2026 10:04
…-sandbox

# Conflicts:
#	languages/exelearning-ca.po
#	languages/exelearning-ca_valencia.po
#	languages/exelearning-de_DE.po
#	languages/exelearning-eo.po
#	languages/exelearning-es_ES.po
#	languages/exelearning-eu.po
#	languages/exelearning-gl_ES.po
#	languages/exelearning-it_IT.po
#	languages/exelearning-pt_PT.po
#	languages/exelearning-ro_RO.po
#	languages/exelearning.pot
…-sandbox

# Conflicts:
#	admin/views/editor-bootstrap.php
#	tests/unit/ElpUploadBlockTest.php
Resolve conflicts with #156 (package .elpx download button):

- Shortcode, block, Media Library meta box and block editor preview keep
  the ExeLearning_Iframe_Sandbox tokens instead of main's hard-coded
  same-origin sandbox string.
- Content proxy keeps select_csp()/build_html_csp() and gains main's
  worker-src 'self' blob: so fflate can rebuild the .elpx.
- wp-exe-download.js routing from #156 merges unchanged.

Carry ADR-156-01 into the opaque viewer: add allow-downloads to
TOKENS_SECURE and TOKENS_LEGACY, build the response-level CSP sandbox
from TOKENS_SECURE (HTML and non-HTML types), and update the JS
fallback tokens, so the package's own download button still saves its
file. The editor preview CSP is unchanged.
erseco and others added 7 commits October 7, 2026 13:06
Tested end to end: in the opaque viewer the package's own "Download .elpx" button saved an empty archive (22 bytes). Its rebuild fetch()es every package file relative to the document, i.e. through the REST content proxy, and from a null origin each request is cross-origin; the proxy sent no Access-Control-Allow-Origin, so all of them failed with "Failed to fetch".

Send Access-Control-Allow-Origin: * on every proxied file in secure mode. The route's permission_callback is open and the hash is its only credential (no cookie, no post-status check), and * never pairs with credentials, so another origin reads only what an anonymous GET already returns. The preview route already does this.

With it, the same click in Chrome against wp-env on this branch saves a 148-entry .elpx; the entries still missing are absent from that package's own manifest (content.xml, exelearning/exelearning#2196) or listed under paths it does not contain.
Tested end to end: in the opaque editor preview the package's "Download .elpx" button did nothing. Its fflate compression runs in blob: workers; the preview CSP sets child-src but no worker-src, so Chrome falls back to child-src and blocks them ("'worker-src' was not explicitly set, so 'child-src' is used as a fallback"). allow-downloads was already there.

Add worker-src 'self' blob:, the same addition the viewer CSP (ADR-156-01) and the Omeka, Nextcloud and Moodle previews make. With it the click saves the rebuilt .elpx (148 entries).
happy-dom 21 gates iframe page loading behind the new enableIframePageLoading
setting, so clearing disableIframePageLoading alone left every content frame
with a null contentWindow and the forged-message test matched the content
iframe by null === null.
Resolve the CSP conflict in ExeLearning_Content_Proxy::send_headers(): keep
select_csp()/build_html_csp() (sandbox in secure mode) and carry the video
player script origins from #202 into the strict profile through SCRIPT_ORIGINS.
html_content_security_policy() is superseded and removed; its tests now run
against build_html_csp().
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.

3 participants