source: webkit/trunk/Source/WebCore/loader/LinkLoader.cpp

Last change on this file was 294819, checked in by Patrick Griffis, 3 years ago

Add support for Link nonces
https://bugs.webkit.org/show_bug.cgi?id=240817

This reads the nonce from link elements and Link headers.

This was implemented by Chromium in 2017 to be consistent with the HTMLPreloader:
https://chromium-review.googlesource.com/c/chromium/src/+/676769/

Reviewed by Kate Cheney.

  • LayoutTests/imported/w3c/web-platform-tests/preload/link-header-preload-nonce-expected.txt:
  • LayoutTests/imported/w3c/web-platform-tests/preload/link-header-preload-nonce.html:

These test changes were already upstream: https://github.com/web-platform-tests/wpt/commit/306dc506adba97ca84ada67bdab6227dba65bbcb

  • Source/WebCore/html/HTMLLinkElement.cpp:

(WebCore::HTMLLinkElement::process):

  • Source/WebCore/loader/LinkHeader.cpp:

(WebCore::paramterNameFromString):
(WebCore::LinkHeader::setValue):

  • Source/WebCore/loader/LinkHeader.h:

(WebCore::LinkHeader::nonce const):

  • Source/WebCore/loader/LinkLoader.cpp:

(WebCore::LinkLoader::loadLinksFromHeader):
(WebCore::LinkLoader::preloadIfNeeded):
(WebCore::LinkLoader::prefetchIfNeeded):

  • Source/WebCore/loader/LinkLoader.h:

Canonical link: https://commits.webkit.org/250972@main

  • Property svn:eol-style set to native
File size: 14.8 KB
Line 
1/*
2 * Copyright (C) 2011 Google Inc. All rights reserved.
3 * Copyright (C) 2016-2017 Apple Inc. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met:
8 *
9 * * Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following disclaimer
13 * in the documentation and/or other materials provided with the
14 * distribution.
15 * * Neither the name of Google Inc. nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 *
31 */
32
33#include "config.h"
34#include "LinkLoader.h"
35
36#include "CSSStyleSheet.h"
37#include "CachedCSSStyleSheet.h"
38#include "CachedResourceLoader.h"
39#include "CachedResourceRequest.h"
40#include "ContainerNode.h"
41#include "CrossOriginAccessControl.h"
42#include "DefaultResourceLoadPriority.h"
43#include "Document.h"
44#include "Frame.h"
45#include "FrameLoader.h"
46#include "FrameLoaderClient.h"
47#include "FrameView.h"
48#include "HTMLSrcsetParser.h"
49#include "LinkHeader.h"
50#include "LinkPreloadResourceClients.h"
51#include "LinkRelAttribute.h"
52#include "LoaderStrategy.h"
53#include "MIMETypeRegistry.h"
54#include "MediaList.h"
55#include "MediaQueryEvaluator.h"
56#include "PlatformStrategies.h"
57#include "ResourceError.h"
58#include "RuntimeEnabledFeatures.h"
59#include "Settings.h"
60#include "SizesAttributeParser.h"
61#include "StyleResolver.h"
62
63namespace WebCore {
64
65LinkLoader::LinkLoader(LinkLoaderClient& client)
66 : m_client(client)
67{
68}
69
70LinkLoader::~LinkLoader()
71{
72 if (m_cachedLinkResource)
73 m_cachedLinkResource->removeClient(*this);
74 if (m_preloadResourceClient)
75 m_preloadResourceClient->clear();
76}
77
78void LinkLoader::triggerEvents(const CachedResource& resource)
79{
80 if (resource.errorOccurred())
81 m_client.linkLoadingErrored();
82 else
83 m_client.linkLoaded();
84}
85
86void LinkLoader::notifyFinished(CachedResource& resource, const NetworkLoadMetrics&)
87{
88 ASSERT_UNUSED(resource, m_cachedLinkResource.get() == &resource);
89
90 triggerEvents(*m_cachedLinkResource);
91
92 m_cachedLinkResource->removeClient(*this);
93 m_cachedLinkResource = nullptr;
94}
95
96void LinkLoader::loadLinksFromHeader(const String& headerValue, const URL& baseURL, Document& document, MediaAttributeCheck mediaAttributeCheck)
97{
98 if (headerValue.isEmpty())
99 return;
100 LinkHeaderSet headerSet(headerValue);
101 for (auto& header : headerSet) {
102 if (!header.valid() || header.url().isEmpty() || header.rel().isEmpty())
103 continue;
104 if ((mediaAttributeCheck == MediaAttributeCheck::MediaAttributeNotEmpty && !header.isViewportDependent())
105 || (mediaAttributeCheck == MediaAttributeCheck::MediaAttributeEmpty && header.isViewportDependent())) {
106 continue;
107 }
108
109 LinkRelAttribute relAttribute(document, header.rel());
110 URL url(baseURL, header.url());
111 // Sanity check to avoid re-entrancy here.
112 if (equalIgnoringFragmentIdentifier(url, baseURL))
113 continue;
114
115 LinkLoadParameters params { relAttribute, url, header.as(), header.media(), header.mimeType(), header.crossOrigin(), header.imageSrcSet(), header.imageSizes(), header.nonce(), ReferrerPolicy::EmptyString };
116 preconnectIfNeeded(params, document);
117 preloadIfNeeded(params, document, nullptr);
118 }
119}
120
121std::optional<CachedResource::Type> LinkLoader::resourceTypeFromAsAttribute(const String& as, Document& document)
122{
123 if (equalLettersIgnoringASCIICase(as, "fetch"_s))
124 return CachedResource::Type::RawResource;
125 if (equalLettersIgnoringASCIICase(as, "image"_s))
126 return CachedResource::Type::ImageResource;
127 if (equalLettersIgnoringASCIICase(as, "script"_s))
128 return CachedResource::Type::Script;
129 if (equalLettersIgnoringASCIICase(as, "style"_s))
130 return CachedResource::Type::CSSStyleSheet;
131 if (document.settings().mediaPreloadingEnabled() && (equalLettersIgnoringASCIICase(as, "video"_s) || equalLettersIgnoringASCIICase(as, "audio"_s)))
132 return CachedResource::Type::MediaResource;
133 if (equalLettersIgnoringASCIICase(as, "font"_s))
134 return CachedResource::Type::FontResource;
135 if (equalLettersIgnoringASCIICase(as, "track"_s))
136 return CachedResource::Type::TextTrackResource;
137 return std::nullopt;
138}
139
140static std::unique_ptr<LinkPreloadResourceClient> createLinkPreloadResourceClient(CachedResource& resource, LinkLoader& loader, Document& document)
141{
142 switch (resource.type()) {
143 case CachedResource::Type::ImageResource:
144 return makeUnique<LinkPreloadImageResourceClient>(loader, downcast<CachedImage>(resource));
145 case CachedResource::Type::Script:
146 return makeUnique<LinkPreloadDefaultResourceClient>(loader, downcast<CachedScript>(resource));
147 case CachedResource::Type::CSSStyleSheet:
148 return makeUnique<LinkPreloadStyleResourceClient>(loader, downcast<CachedCSSStyleSheet>(resource));
149 case CachedResource::Type::FontResource:
150 return makeUnique<LinkPreloadFontResourceClient>(loader, downcast<CachedFont>(resource));
151 case CachedResource::Type::TextTrackResource:
152 return makeUnique<LinkPreloadDefaultResourceClient>(loader, downcast<CachedTextTrack>(resource));
153 case CachedResource::Type::MediaResource:
154 ASSERT_UNUSED(document, document.settings().mediaPreloadingEnabled());
155 FALLTHROUGH;
156 case CachedResource::Type::RawResource:
157 return makeUnique<LinkPreloadRawResourceClient>(loader, downcast<CachedRawResource>(resource));
158 case CachedResource::Type::MainResource:
159 case CachedResource::Type::Icon:
160 case CachedResource::Type::SVGFontResource:
161 case CachedResource::Type::SVGDocumentResource:
162#if ENABLE(XSLT)
163 case CachedResource::Type::XSLStyleSheet:
164#endif
165 case CachedResource::Type::Beacon:
166 case CachedResource::Type::Ping:
167 case CachedResource::Type::LinkPrefetch:
168#if ENABLE(APPLICATION_MANIFEST)
169 case CachedResource::Type::ApplicationManifest:
170#endif
171#if ENABLE(MODEL_ELEMENT)
172 case CachedResource::Type::ModelResource:
173#endif
174 // None of these values is currently supported as an `as` value.
175 ASSERT_NOT_REACHED();
176 }
177 return nullptr;
178}
179
180bool LinkLoader::isSupportedType(CachedResource::Type resourceType, const String& mimeType, Document& document)
181{
182 if (mimeType.isEmpty())
183 return true;
184 switch (resourceType) {
185 case CachedResource::Type::ImageResource:
186 return MIMETypeRegistry::isSupportedImageVideoOrSVGMIMEType(mimeType);
187 case CachedResource::Type::Script:
188 return MIMETypeRegistry::isSupportedJavaScriptMIMEType(mimeType);
189 case CachedResource::Type::CSSStyleSheet:
190 return MIMETypeRegistry::isSupportedStyleSheetMIMEType(mimeType);
191 case CachedResource::Type::FontResource:
192 return MIMETypeRegistry::isSupportedFontMIMEType(mimeType);
193 case CachedResource::Type::MediaResource:
194 if (!document.settings().mediaPreloadingEnabled())
195 ASSERT_NOT_REACHED();
196 return MIMETypeRegistry::isSupportedMediaMIMEType(mimeType);
197 case CachedResource::Type::TextTrackResource:
198 return MIMETypeRegistry::isSupportedTextTrackMIMEType(mimeType);
199 case CachedResource::Type::RawResource:
200#if ENABLE(APPLICATION_MANIFEST)
201 case CachedResource::Type::ApplicationManifest:
202#endif
203 return true;
204 default:
205 ASSERT_NOT_REACHED();
206 }
207 return false;
208}
209
210void LinkLoader::preconnectIfNeeded(const LinkLoadParameters& params, Document& document)
211{
212 const URL href = params.href;
213 if (!params.relAttribute.isLinkPreconnect || !href.isValid() || !params.href.protocolIsInHTTPFamily() || !document.frame())
214 return;
215 ASSERT(document.settings().linkPreconnectEnabled());
216 StoredCredentialsPolicy storageCredentialsPolicy = StoredCredentialsPolicy::Use;
217 if (equalLettersIgnoringASCIICase(params.crossOrigin, "anonymous"_s) && !document.securityOrigin().isSameOriginDomain(SecurityOrigin::create(href)))
218 storageCredentialsPolicy = StoredCredentialsPolicy::DoNotUse;
219 ASSERT(document.frame()->loader().networkingContext());
220 platformStrategies()->loaderStrategy()->preconnectTo(document.frame()->loader(), href, storageCredentialsPolicy, LoaderStrategy::ShouldPreconnectAsFirstParty::No, [weakDocument = WeakPtr { document }, href](ResourceError error) {
221 if (!weakDocument)
222 return;
223
224 if (!error.isNull())
225 weakDocument->addConsoleMessage(MessageSource::Network, MessageLevel::Error, makeString("Failed to preconnect to "_s, href.string(), ". Error: "_s, error.localizedDescription()));
226 else
227 weakDocument->addConsoleMessage(MessageSource::Network, MessageLevel::Info, makeString("Successfully preconnected to "_s, href.string()));
228 });
229}
230
231std::unique_ptr<LinkPreloadResourceClient> LinkLoader::preloadIfNeeded(const LinkLoadParameters& params, Document& document, LinkLoader* loader)
232{
233 if (!document.loader() || !params.relAttribute.isLinkPreload)
234 return nullptr;
235
236 ASSERT(document.settings().linkPreloadEnabled());
237 auto type = LinkLoader::resourceTypeFromAsAttribute(params.as, document);
238 if (!type) {
239 document.addConsoleMessage(MessageSource::Other, MessageLevel::Error, "<link rel=preload> must have a valid `as` value"_s);
240 return nullptr;
241 }
242 URL url;
243 if (document.settings().linkPreloadResponsiveImagesEnabled() && type == CachedResource::Type::ImageResource && !params.imageSrcSet.isEmpty()) {
244 auto sourceSize = SizesAttributeParser(params.imageSizes, document).length();
245 auto candidate = bestFitSourceForImageAttributes(document.deviceScaleFactor(), AtomString { params.href.string() }, AtomString { params.imageSrcSet }, sourceSize);
246 url = document.completeURL(URL({ }, candidate.string.toString()).string());
247 } else
248 url = document.completeURL(params.href.string());
249
250 if (!url.isValid()) {
251 if (params.imageSrcSet.isEmpty())
252 document.addConsoleMessage(MessageSource::Other, MessageLevel::Error, "<link rel=preload> has an invalid `href` value"_s);
253 else
254 document.addConsoleMessage(MessageSource::Other, MessageLevel::Error, "<link rel=preload> has an invalid `imagesrcset` value"_s);
255 return nullptr;
256 }
257 if (!MediaQueryEvaluator::mediaAttributeMatches(document, params.media))
258 return nullptr;
259 if (!isSupportedType(type.value(), params.mimeType, document))
260 return nullptr;
261
262 auto options = CachedResourceLoader::defaultCachedResourceOptions();
263 options.referrerPolicy = params.referrerPolicy;
264 options.nonce = params.nonce;
265 auto linkRequest = createPotentialAccessControlRequest(url, WTFMove(options), document, params.crossOrigin);
266 linkRequest.setPriority(DefaultResourceLoadPriority::forResourceType(type.value()));
267 linkRequest.setInitiator("link"_s);
268 linkRequest.setIgnoreForRequestCount(true);
269 linkRequest.setIsLinkPreload();
270
271 auto cachedLinkResource = document.cachedResourceLoader().preload(type.value(), WTFMove(linkRequest)).value_or(nullptr);
272
273 if (cachedLinkResource && cachedLinkResource->type() != *type)
274 return nullptr;
275
276 if (cachedLinkResource && loader)
277 return createLinkPreloadResourceClient(*cachedLinkResource, *loader, document);
278 return nullptr;
279}
280
281void LinkLoader::prefetchIfNeeded(const LinkLoadParameters& params, Document& document)
282{
283 if (!params.href.isValid() || !document.frame())
284 return;
285
286 ASSERT(document.settings().linkPrefetchEnabled());
287 std::optional<ResourceLoadPriority> priority;
288 CachedResource::Type type = CachedResource::Type::LinkPrefetch;
289
290 if (m_cachedLinkResource) {
291 m_cachedLinkResource->removeClient(*this);
292 m_cachedLinkResource = nullptr;
293 }
294 // FIXME: Add further prefetch restrictions/limitations:
295 // - third-party iframes cannot trigger prefetches
296 // - Number of prefetches of a given page is limited (to 1 maybe?)
297 ResourceLoaderOptions options = CachedResourceLoader::defaultCachedResourceOptions();
298 options.contentSecurityPolicyImposition = ContentSecurityPolicyImposition::SkipPolicyCheck;
299 options.certificateInfoPolicy = CertificateInfoPolicy::IncludeCertificateInfo;
300 options.credentials = FetchOptions::Credentials::SameOrigin;
301 options.redirect = FetchOptions::Redirect::Manual;
302 options.mode = FetchOptions::Mode::Navigate;
303 options.serviceWorkersMode = ServiceWorkersMode::None;
304 options.cachingPolicy = CachingPolicy::DisallowCaching;
305 options.referrerPolicy = params.referrerPolicy;
306 options.nonce = params.nonce;
307 m_cachedLinkResource = document.cachedResourceLoader().requestLinkResource(type, CachedResourceRequest(ResourceRequest { document.completeURL(params.href.string()) }, options, priority)).value_or(nullptr);
308 if (m_cachedLinkResource)
309 m_cachedLinkResource->addClient(*this);
310}
311
312void LinkLoader::cancelLoad()
313{
314 if (m_preloadResourceClient)
315 m_preloadResourceClient->clear();
316}
317
318void LinkLoader::loadLink(const LinkLoadParameters& params, Document& document)
319{
320 if (params.relAttribute.isDNSPrefetch) {
321 // FIXME: The href attribute of the link element can be in "//hostname" form, and we shouldn't attempt
322 // to complete that as URL <https://bugs.webkit.org/show_bug.cgi?id=48857>.
323 if (document.settings().dnsPrefetchingEnabled() && params.href.isValid() && !params.href.isEmpty() && document.frame())
324 document.frame()->loader().client().prefetchDNS(params.href.host().toString());
325 }
326
327 preconnectIfNeeded(params, document);
328
329 if (params.relAttribute.isLinkPrefetch) {
330 prefetchIfNeeded(params, document);
331 return;
332 }
333
334 if (m_client.shouldLoadLink()) {
335 auto resourceClient = preloadIfNeeded(params, document, this);
336 if (m_preloadResourceClient)
337 m_preloadResourceClient->clear();
338 if (resourceClient)
339 m_preloadResourceClient = WTFMove(resourceClient);
340 }
341}
342
343}
Note: See TracBrowser for help on using the repository browser.