Skip to content

Truly independent web browser

LibWeb: Don’t hold the PDF viewer to the CSP of the PDF it shows

sideshowbarkerce11b6d75f87
diff --git a/Base/res/ladybird/pdfjs/pdfjs-ladybird-transport.mjs b/Base/res/ladybird/pdfjs/pdfjs-ladybird-transport.mjs
index 8efa4a7e6b5..641a022a72f 100644
--- a/Base/res/ladybird/pdfjs/pdfjs-ladybird-transport.mjs
+++ b/Base/res/ladybird/pdfjs/pdfjs-ladybird-transport.mjs
@@ -10,6 +10,14 @@ async function openPdf(response) {
const contentLength = parseInt(response.headers.get("Content-Length") ?? "0", 10);
const { PDFDataRangeTransport } = globalThis.pdfjsLib;
const transport = new PDFDataRangeTransport(contentLength, new Uint8Array());
+ // Marks the document once a page has been drawn without error, for tests to wait on.
+ window.PDFViewerApplication.eventBus.on(
+ "pagerendered",
+ event => {
+ if (!event.error) document.documentElement.setAttribute("data-ladybird-page-rendered", "");
+ },
+ { once: true }
+ );
window.PDFViewerApplication.open({ range: transport, disableRange: true });
if (response.body) {
const reader = response.body.getReader();
diff --git a/Libraries/LibWeb/DOM/DocumentLoading.cpp b/Libraries/LibWeb/DOM/DocumentLoading.cpp
index 42b0895bc4f..ec92f3315a5 100644
--- a/Libraries/LibWeb/DOM/DocumentLoading.cpp
+++ b/Libraries/LibWeb/DOM/DocumentLoading.cpp
@@ -27,6 +27,7 @@
#include <LibWeb/DOM/IDLEventListener.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/MIME.h>
#include <LibWeb/Fetch/Response.h>
+#include <LibWeb/HTML/BrowsingContext.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/HTMLHeadElement.h>
#include <LibWeb/HTML/HTMLImageElement.h>
@@ -37,6 +38,7 @@
#include <LibWeb/HTML/Parser/HTMLEncodingDetection.h>
#include <LibWeb/HTML/Parser/HTMLParser.h>
#include <LibWeb/HTML/Parser/IncrementalDocumentParser.h>
+#include <LibWeb/HTML/PolicyContainers.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/SharedResourceRequest.h>
#include <LibWeb/HTML/Window.h>
@@ -486,6 +488,19 @@ static GC::Ref<DOM::Document> load_pdf_document(HTML::NavigationParams const& na
static NeverDestroyed<ByteBuffer> viewer_bytes { MUST(Core::Resource::load_from_uri("resource://ladybird/pdfjs/web/viewer.html"sv))->clone_data() };
auto document = MUST(DOM::Document::create_and_initialize(DOM::Document::Type::HTML, "text/html"_utf16_fly_string, navigation_params));
+ // The viewer is the user agent's own page, which brings its own CSP. The PDF response's policies are for the PDF,
+ // and would stop the viewer — a base-uri or script-src directive alone refuses its resources. So the viewer gets a
+ // new policy container, which keeps only the insecure requests policy inherited from the container document.
+ auto policy_container = HTML::PolicyContainer::create();
+ if (navigation_params.navigable->parent()) {
+ auto container_state = navigation_params.navigable->container_state();
+ policy_container->inherit_insecure_requests_policy(container_state.document_insecure_requests_policy, container_state.document_upgrade_insecure_navigations_set);
+ }
+ document->set_policy_container(policy_container);
+
+ // The sandboxing flags of the PDF response's CSP would stop the viewer's scripts too, so the viewer keeps only the
+ // sandboxing flags that don't come from the response.
+ document->set_active_sandboxing_flag_set(navigation_params.final_sandboxing_flag_set & HTML::determine_the_creation_sandboxing_flags(*document->browsing_context(), *navigation_params.navigable));
add_pdf_viewer_ready_listener(document, GC::Ref(*navigation_params.response));
diff --git a/Libraries/LibWebView/CanonicalNavigable.cpp b/Libraries/LibWebView/CanonicalNavigable.cpp
index e3959132820..3f4e8917874 100644
--- a/Libraries/LibWebView/CanonicalNavigable.cpp
+++ b/Libraries/LibWebView/CanonicalNavigable.cpp
@@ -1179,6 +1179,12 @@ void CanonicalNavigable::did_create_populated_document_with_an_origin_of_its_own
auto origin = is_inline_content ? *populated_document->inline_content_origin : URL::Origin { "resource"_string, String {}, {} };
auto url = is_inline_content ? URL::about_error() : populated_document->document->creation_url();
+
+ // The PDF viewer keeps only the sandboxing flags that don't come from the CSP of the PDF response.
+ auto sandboxing_flags = populated_document->document->active_sandboxing_flag_set();
+ if (!is_inline_content)
+ sandboxing_flags &= snapshot_target_snapshot_params().sandboxing_flags;
+
NavigationLoader::ResponseDocument response_document {
.is_inline_content = is_inline_content,
.coop_enforcement_result = { .url = url, .origin = origin, .opener_policy = {} },
@@ -1187,7 +1193,7 @@ void CanonicalNavigable::did_create_populated_document_with_an_origin_of_its_own
.origin = origin,
.opener_policy = {},
.embedder_policy = {},
- .final_sandboxing_flag_set = populated_document->document->active_sandboxing_flag_set(),
+ .final_sandboxing_flag_set = sandboxing_flags,
.environment_id = environment_id,
.document_id = document_id,
};
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index f376b22dfa3..dee55a1d3ed 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -28,6 +28,9 @@ if (BUILD_TESTING AND NOT WIN32)
ladybird_python_test(test-webdriver-error-keep-alive.py ARGS $<TARGET_FILE:WebDriver>)
ladybird_python_test(test-webdriver-force-dark.py ARGS $<TARGET_FILE:WebDriver>)
ladybird_python_test(test-webdriver-permissions-settings.py ARGS $<TARGET_FILE:WebDriver>)
+ if (PDFJS_FOUND)
+ ladybird_python_test(test-webdriver-pdf-viewer-ignores-the-csp-of-its-pdf.py ARGS $<TARGET_FILE:WebDriver>)
+ endif()
ladybird_python_test(test-webdriver-search-engine-settings.py ARGS $<TARGET_FILE:WebDriver>)
ladybird_python_test(test-webdriver-set-permission.py ARGS $<TARGET_FILE:WebDriver>)
ladybird_python_test(test-webdriver-settings-changes.py ARGS $<TARGET_FILE:WebDriver>)
diff --git a/Tests/LibWebView/test-webdriver-pdf-viewer-ignores-the-csp-of-its-pdf.py b/Tests/LibWebView/test-webdriver-pdf-viewer-ignores-the-csp-of-its-pdf.py
new file mode 100755
index 00000000000..72d38795c0f
--- /dev/null
+++ b/Tests/LibWebView/test-webdriver-pdf-viewer-ignores-the-csp-of-its-pdf.py
@@ -0,0 +1,82 @@
+#!/usr/bin/env python3
+#
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+import argparse
+import http.server
+import runpy
+import subprocess
+import tempfile
+import threading
+import time
+
+from pathlib import Path
+
+helpers = runpy.run_path(str(Path(__file__).with_name("test-webdriver-delete-session.py")))
+
+PDF = (
+ b"%PDF-1.1\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n"
+ b"3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]>>endobj\ntrailer<</Root 1 0 R>>\n%%EOF\n"
+)
+
+
+class PdfHandler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ self.send_response(200)
+ self.send_header("Content-Type", "application/pdf")
+ self.send_header("Content-Length", str(len(PDF)))
+ # Each of these directives alone would stop the viewer's scripts: base-uri refuses the viewer's base element,
+ # default-src its scripts and stylesheet, and sandbox runs no scripts at all.
+ self.send_header("Content-Security-Policy", "default-src 'self'; base-uri 'self'; sandbox")
+ self.end_headers()
+ self.wfile.write(PDF)
+
+ def log_message(self, format, *args):
+ pass
+
+
+# The CSP of a PDF's response is for the PDF, so it mustn't stop the PDF viewer, which brings its own: The viewer still
+# draws the PDF's first page.
+def run_test(webdriver_binary):
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), PdfHandler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+
+ with tempfile.TemporaryDirectory() as directory:
+ process, port = helpers["launch_webdriver"](webdriver_binary, "--headless", "--profile-path", directory)
+ session = None
+ try:
+ session = helpers["create_session"](port)
+
+ def command(path, body):
+ status, payload, raw = helpers["request"](port, "POST", f"/session/{session}/{path}", body)
+ assert status == 200, raw
+ return payload["value"]
+
+ command("url", {"url": f"http://127.0.0.1:{server.server_address[1]}/document.pdf"})
+
+ deadline = time.monotonic() + 30
+ script = "return document.documentElement.hasAttribute('data-ladybird-page-rendered');"
+ while not command("execute/sync", {"script": script, "args": []}):
+ assert time.monotonic() < deadline, "The viewer never drew the PDF's first page"
+ time.sleep(0.1)
+ print("PASS: the PDF viewer draws a PDF whose CSP would stop its scripts")
+ finally:
+ try:
+ if session is not None:
+ helpers["request"](port, "DELETE", f"/session/{session}")
+ finally:
+ process.terminate()
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait()
+ server.shutdown()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("webdriver_binary")
+ run_test(parser.parse_args().webdriver_binary)