Truly independent web browser
LibWeb: Resolve font source URLs before sharing their loaders
Andreas Kling0eec3c589f65
diff --git a/Libraries/LibWeb/CSS/Fetch.cpp b/Libraries/LibWeb/CSS/Fetch.cppindex b6e3bcd831c..991be75a5a2 100644--- a/Libraries/LibWeb/CSS/Fetch.cpp+++ b/Libraries/LibWeb/CSS/Fetch.cpp@@ -65,11 +65,16 @@ static StyleResourceContext style_resource_context(RuleOrDeclaration css_rule_orreturn { nullptr, {}, api_base_url };}+::URL::URL style_resource_base_url(RuleOrDeclaration css_rule_or_declaration)+{+ return style_resource_context(css_rule_or_declaration).url;+}+// https://drafts.csswg.org/css-values-4/#resolve-a-style-resource-url-static Optional<::URL::URL> resolve_a_style_resource_url(StyleResourceURL const& url_value, RuleOrDeclaration css_rule_or_declaration)+Optional<::URL::URL> resolve_a_style_resource_url(StyleResourceURL const& url_value, RuleOrDeclaration css_rule_or_declaration){// 1. Let baseURL be the style resource base URL given cssRuleOrDeclaration.- auto base_url = style_resource_context(css_rule_or_declaration).url;+ auto base_url = style_resource_base_url(css_rule_or_declaration);// 2. Return the result of the URL parser steps with urlValue’s url and base.return url_value.visit(diff --git a/Libraries/LibWeb/CSS/Fetch.h b/Libraries/LibWeb/CSS/Fetch.hindex 3526af14c6c..1dd3f9a43ba 100644--- a/Libraries/LibWeb/CSS/Fetch.h+++ b/Libraries/LibWeb/CSS/Fetch.h@@ -39,6 +39,12 @@ struct RuleOrDeclaration {Optional<bool> parent_style_sheet_origin_clean;};+// https://drafts.csswg.org/css-values-4/#style-resource-base-url+::URL::URL style_resource_base_url(RuleOrDeclaration);++// https://drafts.csswg.org/css-values-4/#resolve-a-style-resource-url+Optional<::URL::URL> resolve_a_style_resource_url(StyleResourceURL const&, RuleOrDeclaration);+// https://drafts.csswg.org/css-values-4/#fetch-a-style-resourceGC::Ptr<Fetch::Infrastructure::FetchController> fetch_a_style_resource(StyleResourceURL const& url, RuleOrDeclaration, Fetch::Infrastructure::Request::Destination, CorsMode, Fetch::Infrastructure::FetchAlgorithms::ProcessResponseConsumeBodyFunction process_response);diff --git a/Libraries/LibWeb/CSS/FontComputer.cpp b/Libraries/LibWeb/CSS/FontComputer.cppindex a83df9a11f0..aba17e98726 100644--- a/Libraries/LibWeb/CSS/FontComputer.cpp+++ b/Libraries/LibWeb/CSS/FontComputer.cpp@@ -647,14 +647,6 @@ GC::Ptr<FontLoader> FontComputer::load_font_face(ReadonlySpan<FontLoader::Sourcereturn {};}- StringBuilder key_builder;- for (auto const& source : sources) {- auto value = source.has<URL>()- ? source.get<URL>().to_string()- : MUST(source.get<Utf16FlyString>().view().to_utf8());- key_builder.appendff("{}{}:{}", source.has<URL>() ? 'u' : 'l', value.bytes_as_string_view().length(), value);- }-RuleOrDeclaration rule_or_declaration {.environment_settings_object = m_document ? m_document->relevant_settings_object() : *m_environment_settings_object,.value = RuleOrDeclaration::Rule {@@ -664,6 +656,28 @@ GC::Ptr<FontLoader> FontComputer::load_font_face(ReadonlySpan<FontLoader::Source.parent_style_sheet_origin_clean = {},};+ // NB: Identical source text can resolve to different URLs in style sheets with different base URLs.+ auto url_source_key = [&](URL const& url) {+ if (auto resolved_url = resolve_a_style_resource_url(url, rule_or_declaration); resolved_url.has_value())+ return URL { resolved_url->serialize(), url.type(), url.request_url_modifiers() }.to_string();+ return url.to_string();+ };++ StringBuilder key_builder;+ if (parent_style_sheet && any_of(sources, [](auto const& source) { return source.template has<URL>(); })) {+ // NB: Font fetching uses the sheet's base URL as its referrer, and may inherit its response's referrer policy.+ // Equal resolved URLs must not reuse a loader that fetches with another sheet's request context.+ auto referrer = style_resource_base_url(rule_or_declaration).serialize();+ auto policy = parent_style_sheet->fetched_referrer_policy().value_or(ReferrerPolicy::ReferrerPolicy::EmptyString);+ key_builder.appendff("r{}:{}p{};", referrer.bytes_as_string_view().length(), referrer, to_underlying(policy));+ }+ for (auto const& source : sources) {+ auto value = source.has<URL>()+ ? url_source_key(source.get<URL>())+ : MUST(source.get<Utf16FlyString>().view().to_utf8());+ key_builder.appendff("{}{}:{}", source.has<URL>() ? 'u' : 'l', value.bytes_as_string_view().length(), value);+ }+auto key = MUST(key_builder.to_string());if (auto it = m_loaders_by_source.find(key); it != m_loaders_by_source.end()) {if (on_load)diff --git a/Tests/LibWeb/Text/expected/font-face-loader-stylesheet-request-context.txt b/Tests/LibWeb/Text/expected/font-face-loader-stylesheet-request-context.txtnew file mode 100644index 00000000000..3e90474599c--- /dev/null+++ b/Tests/LibWeb/Text/expected/font-face-loader-stylesheet-request-context.txt@@ -0,0 +1,7 @@+First sheet referrer: true+Same context shares one request: true+Second sheet referrer: true+Different referrers make two requests: true+Initial policy sends referrer: true+New policy omits referrer: true+Different policies make two requests: truediff --git a/Tests/LibWeb/Text/expected/font-face-same-relative-url-different-base-urls.txt b/Tests/LibWeb/Text/expected/font-face-same-relative-url-different-base-urls.txtindex ff304adcc44..1765f327fec 100644--- a/Tests/LibWeb/Text/expected/font-face-same-relative-url-different-base-urls.txt+++ b/Tests/LibWeb/Text/expected/font-face-same-relative-url-different-base-urls.txt@@ -1,2 +1,2 @@WithFont: loaded-WithoutFont: loaded+WithoutFont: errordiff --git a/Tests/LibWeb/Text/input/font-face-loader-stylesheet-request-context.html b/Tests/LibWeb/Text/input/font-face-loader-stylesheet-request-context.htmlnew file mode 100644index 00000000000..408c07f572d--- /dev/null+++ b/Tests/LibWeb/Text/input/font-face-loader-stylesheet-request-context.html@@ -0,0 +1,88 @@+<!doctype html>+<script src="include.js"></script>+<script>+ promiseTest(async () => {+ const server = httpTestServer();+ const fontResponse = await fetch("../../Assets/HashSans.woff");+ const fontBytes = new Uint8Array(await fontResponse.arrayBuffer());+ const fontBody = btoa(Array.from(fontBytes, byte => String.fromCharCode(byte)).join(""));+ const createFont = name =>+ server.createEcho("GET", name, {+ status: 200,+ headers: { "Content-Type": "font/woff", "Cache-Control": "no-store" },+ body: fontBody,+ body_encoding: "base64",+ });+ const createSheet = (path, policy, body) =>+ server.createEcho("GET", path, {+ status: 200,+ headers: { "Content-Type": "text/css", "Cache-Control": "no-store", "Referrer-Policy": policy },+ body,+ });+ const loadSheet = url =>+ new Promise((resolve, reject) => {+ const link = document.createElement("link");+ link.rel = "stylesheet";+ link.onload = resolve;+ link.onerror = reject;+ link.href = url;+ document.head.append(link);+ });+ const loadFace = async family => {+ const face = Array.from(document.fonts).find(face => face.family === family);+ if (!face) throw new Error(`Missing font face: ${family}`);+ await face.load();+ };+ const referrer = async url => {+ const response = await fetch(server.recordedRequestHeadersURL(url), { cache: "no-store" });+ const headers = await response.json();+ return Object.entries(headers).find(([name]) => name.toLowerCase() === "referer")?.[1][0] ?? null;+ };+ const requests = url => performance.getEntriesByType("resource").filter(entry => entry.name === url).length;++ const fontURL = await createFont("/shared.woff");+ const firstSheet = await createSheet(+ "/first/sheet.css",+ "unsafe-url",+ `+ @font-face { font-family: First; src: url(../shared.woff); }+ @font-face { font-family: SameContext; src: url('${fontURL}'); }+ `+ );+ await loadSheet(firstSheet);+ await loadFace("First");+ println(`First sheet referrer: ${(await referrer(fontURL)) === firstSheet}`);+ await loadFace("SameContext");+ println(`Same context shares one request: ${requests(fontURL) === 1}`);+ const secondSheet = await createSheet(+ "/second/sheet.css",+ "unsafe-url",+ `+ @font-face { font-family: Second; src: url('${fontURL}'); }+ `+ );+ await loadSheet(secondSheet);+ await loadFace("Second");+ println(`Second sheet referrer: ${(await referrer(fontURL)) === secondSheet}`);+ println(`Different referrers make two requests: ${requests(fontURL) === 2}`);++ const policyFontURL = await createFont("/policy.woff");+ const policySheet = await createSheet(+ "/policy.css",+ "no-referrer",+ `+ @font-face { font-family: PolicySecond; src: url('${policyFontURL}'); }+ `+ );+ // NB: The base URL is identical, but only the fetched sheet inherits a response's no-referrer policy.+ const constructed = new CSSStyleSheet({ baseURL: policySheet });+ constructed.replaceSync("@font-face { font-family: PolicyFirst; src: url(policy.woff); }");+ document.adoptedStyleSheets = [constructed];+ await loadFace("PolicyFirst");+ println(`Initial policy sends referrer: ${(await referrer(policyFontURL)) === policySheet}`);+ await loadSheet(policySheet);+ await loadFace("PolicySecond");+ println(`New policy omits referrer: ${(await referrer(policyFontURL)) === null}`);+ println(`Different policies make two requests: ${requests(policyFontURL) === 2}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/font-face-loader-stylesheet-request-context.html.headers b/Tests/LibWeb/Text/input/font-face-loader-stylesheet-request-context.html.headersnew file mode 100644index 00000000000..be597bee0d7--- /dev/null+++ b/Tests/LibWeb/Text/input/font-face-loader-stylesheet-request-context.html.headers@@ -0,0 +1,2 @@+Content-Type: text/html+Referrer-Policy: unsafe-url