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

Last change on this file was 294470, checked in by Diego Pino Garcia, 3 years ago

Unreviewed, non-unified build fixes after 250693@main

  • Property svn:eol-style set to native
File size: 34.1 KB
Line 
1/*
2 * Copyright (C) 2011, 2012 Google Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
13 * distribution.
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31#include "config.h"
32#include "DocumentThreadableLoader.h"
33
34#include "CachedRawResource.h"
35#include "CachedResourceLoader.h"
36#include "CachedResourceRequest.h"
37#include "CachedResourceRequestInitiators.h"
38#include "CrossOriginAccessControl.h"
39#include "CrossOriginPreflightChecker.h"
40#include "CrossOriginPreflightResultCache.h"
41#include "DOMWindow.h"
42#include "Document.h"
43#include "DocumentLoader.h"
44#include "Frame.h"
45#include "FrameDestructionObserverInlines.h"
46#include "FrameLoader.h"
47#include "InspectorInstrumentation.h"
48#include "InspectorNetworkAgent.h"
49#include "LegacySchemeRegistry.h"
50#include "LoaderStrategy.h"
51#include "MixedContentChecker.h"
52#include "Performance.h"
53#include "PlatformStrategies.h"
54#include "ProgressTracker.h"
55#include "ResourceError.h"
56#include "ResourceRequest.h"
57#include "ResourceTiming.h"
58#include "RuntimeApplicationChecks.h"
59#include "RuntimeEnabledFeatures.h"
60#include "SecurityOrigin.h"
61#include "Settings.h"
62#include "SharedBuffer.h"
63#include "SubresourceIntegrity.h"
64#include "SubresourceLoader.h"
65#include "ThreadableLoaderClient.h"
66#include <wtf/Assertions.h>
67#include <wtf/Ref.h>
68
69#if PLATFORM(IOS_FAMILY)
70#include <wtf/cocoa/RuntimeApplicationChecksCocoa.h>
71#endif
72
73namespace WebCore {
74
75void DocumentThreadableLoader::loadResourceSynchronously(Document& document, ResourceRequest&& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options, RefPtr<SecurityOrigin>&& origin, std::unique_ptr<ContentSecurityPolicy>&& contentSecurityPolicy, std::optional<CrossOriginEmbedderPolicy>&& crossOriginEmbedderPolicy)
76{
77 // The loader will be deleted as soon as this function exits.
78 Ref<DocumentThreadableLoader> loader = adoptRef(*new DocumentThreadableLoader(document, client, LoadSynchronously, WTFMove(request), options, WTFMove(origin), WTFMove(contentSecurityPolicy), WTFMove(crossOriginEmbedderPolicy), String(), ShouldLogError::Yes));
79 ASSERT(loader->hasOneRef());
80}
81
82void DocumentThreadableLoader::loadResourceSynchronously(Document& document, ResourceRequest&& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
83{
84 loadResourceSynchronously(document, WTFMove(request), client, options, nullptr, nullptr, std::nullopt);
85}
86
87RefPtr<DocumentThreadableLoader> DocumentThreadableLoader::create(Document& document, ThreadableLoaderClient& client,
88ResourceRequest&& request, const ThreadableLoaderOptions& options, RefPtr<SecurityOrigin>&& origin,
89std::unique_ptr<ContentSecurityPolicy>&& contentSecurityPolicy, std::optional<CrossOriginEmbedderPolicy>&& crossOriginEmbedderPolicy, String&& referrer, ShouldLogError shouldLogError)
90{
91 RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, client, LoadAsynchronously, WTFMove(request), options, WTFMove(origin), WTFMove(contentSecurityPolicy), WTFMove(crossOriginEmbedderPolicy), WTFMove(referrer), shouldLogError));
92 if (!loader->isLoading())
93 loader = nullptr;
94 return loader;
95}
96
97RefPtr<DocumentThreadableLoader> DocumentThreadableLoader::create(Document& document, ThreadableLoaderClient& client, ResourceRequest&& request, const ThreadableLoaderOptions& options, String&& referrer)
98{
99 return create(document, client, WTFMove(request), options, nullptr, nullptr, std::nullopt, WTFMove(referrer), ShouldLogError::Yes);
100}
101
102static inline bool shouldPerformSecurityChecks()
103{
104 return platformStrategies()->loaderStrategy()->shouldPerformSecurityChecks();
105}
106
107bool DocumentThreadableLoader::shouldSetHTTPHeadersToKeep() const
108{
109 if (m_options.mode == FetchOptions::Mode::Cors && shouldPerformSecurityChecks())
110 return true;
111
112#if ENABLE(SERVICE_WORKER)
113 if (m_options.serviceWorkersMode == ServiceWorkersMode::All && m_async)
114 return m_options.serviceWorkerRegistrationIdentifier || m_document.activeServiceWorker();
115#endif
116
117 return false;
118}
119
120DocumentThreadableLoader::DocumentThreadableLoader(Document& document, ThreadableLoaderClient& client, BlockingBehavior blockingBehavior, ResourceRequest&& request, const ThreadableLoaderOptions& options, RefPtr<SecurityOrigin>&& origin, std::unique_ptr<ContentSecurityPolicy>&& contentSecurityPolicy, std::optional<CrossOriginEmbedderPolicy>&& crossOriginEmbedderPolicy, String&& referrer, ShouldLogError shouldLogError)
121 : m_client(&client)
122 , m_document(document)
123 , m_options(options)
124 , m_origin(WTFMove(origin))
125 , m_referrer(WTFMove(referrer))
126 , m_sameOriginRequest(securityOrigin().canRequest(request.url()))
127 , m_simpleRequest(true)
128 , m_async(blockingBehavior == LoadAsynchronously)
129 , m_delayCallbacksForIntegrityCheck(!m_options.integrity.isEmpty())
130 , m_contentSecurityPolicy(WTFMove(contentSecurityPolicy))
131 , m_crossOriginEmbedderPolicy(WTFMove(crossOriginEmbedderPolicy))
132 , m_shouldLogError(shouldLogError)
133{
134 relaxAdoptionRequirement();
135
136 // Setting a referrer header is only supported in the async code path.
137 ASSERT(m_async || m_referrer.isEmpty());
138
139 if (document.settings().disallowSyncXHRDuringPageDismissalEnabled() && !m_async && (!document.page() || !document.page()->areSynchronousLoadsAllowed())) {
140 document.didRejectSyncXHRDuringPageDismissal();
141 logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, request.url(), "Synchronous loads are not allowed at this time"_s));
142 return;
143 }
144
145 // Referrer and Origin headers should be set after the preflight if any.
146 ASSERT(!request.hasHTTPReferrer() && !request.hasHTTPOrigin());
147
148 ASSERT_WITH_SECURITY_IMPLICATION(isAllowedByContentSecurityPolicy(request.url(), ContentSecurityPolicy::RedirectResponseReceived::No));
149
150 m_options.storedCredentialsPolicy = (m_options.credentials == FetchOptions::Credentials::Include || (m_options.credentials == FetchOptions::Credentials::SameOrigin && m_sameOriginRequest)) ? StoredCredentialsPolicy::Use : StoredCredentialsPolicy::DoNotUse;
151
152 ASSERT(!request.httpHeaderFields().contains(HTTPHeaderName::Origin));
153
154 // Copy headers if we need to replay the request after a redirection.
155 if (m_options.mode == FetchOptions::Mode::Cors)
156 m_originalHeaders = request.httpHeaderFields();
157
158 if (shouldSetHTTPHeadersToKeep())
159 m_options.httpHeadersToKeep = httpHeadersToKeepFromCleaning(request.httpHeaderFields());
160
161 bool shouldDisableCORS = document.isRunningUserScripts() && LegacySchemeRegistry::isUserExtensionScheme(request.url().protocol());
162 if (auto* page = document.page())
163 shouldDisableCORS |= page->shouldDisableCorsForRequestTo(request.url());
164
165 if (shouldDisableCORS) {
166 m_options.mode = FetchOptions::Mode::NoCors;
167 m_options.filteringPolicy = ResponseFilteringPolicy::Disable;
168 m_responsesCanBeOpaque = false;
169 }
170
171 m_options.cspResponseHeaders = m_options.contentSecurityPolicyEnforcement != ContentSecurityPolicyEnforcement::DoNotEnforce ? this->contentSecurityPolicy().responseHeaders() : ContentSecurityPolicyResponseHeaders { };
172 m_options.crossOriginEmbedderPolicy = this->crossOriginEmbedderPolicy();
173
174 // As per step 11 of https://fetch.spec.whatwg.org/#main-fetch, data scheme (if same-origin data-URL flag is set) and about scheme are considered same-origin.
175 if (request.url().protocolIsData())
176 m_sameOriginRequest = options.sameOriginDataURLFlag == SameOriginDataURLFlag::Set;
177
178 if (m_sameOriginRequest || m_options.mode == FetchOptions::Mode::NoCors || m_options.mode == FetchOptions::Mode::Navigate) {
179 loadRequest(WTFMove(request), SecurityCheckPolicy::DoSecurityCheck);
180 return;
181 }
182
183 if (m_options.mode == FetchOptions::Mode::SameOrigin) {
184 logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, request.url(), "Cross origin requests are not allowed when using same-origin fetch mode."_s));
185 return;
186 }
187
188 makeCrossOriginAccessRequest(WTFMove(request));
189}
190
191bool DocumentThreadableLoader::checkURLSchemeAsCORSEnabled(const URL& url)
192{
193 // Cross-origin requests are only allowed for HTTP and registered schemes. We would catch this when checking response headers later, but there is no reason to send a request that's guaranteed to be denied.
194 if (!LegacySchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(url.protocol())) {
195 logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, url, "Cross origin requests are only supported for HTTP."_s, ResourceError::Type::AccessControl));
196 return false;
197 }
198 return true;
199}
200
201void DocumentThreadableLoader::makeCrossOriginAccessRequest(ResourceRequest&& request)
202{
203 ASSERT(m_options.mode == FetchOptions::Mode::Cors);
204
205#if PLATFORM(IOS_FAMILY)
206 bool needsPreflightQuirk = IOSApplication::isMoviStarPlus() && !linkedOnOrAfterSDKWithBehavior(SDKAlignedBehavior::NoMoviStarPlusCORSPreflightQuirk) && (m_options.preflightPolicy == PreflightPolicy::Consider || m_options.preflightPolicy == PreflightPolicy::Force);
207#else
208 bool needsPreflightQuirk = false;
209#endif
210
211 if ((m_options.preflightPolicy == PreflightPolicy::Consider && isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields())) || m_options.preflightPolicy == PreflightPolicy::Prevent || (shouldPerformSecurityChecks() && !needsPreflightQuirk)) {
212 if (checkURLSchemeAsCORSEnabled(request.url()))
213 makeSimpleCrossOriginAccessRequest(WTFMove(request));
214 } else {
215#if ENABLE(SERVICE_WORKER)
216 if (m_options.serviceWorkersMode == ServiceWorkersMode::All && m_async) {
217 if (m_options.serviceWorkerRegistrationIdentifier || document().activeServiceWorker()) {
218 ASSERT(!m_bypassingPreflightForServiceWorkerRequest);
219 m_bypassingPreflightForServiceWorkerRequest = WTFMove(request);
220 m_options.serviceWorkersMode = ServiceWorkersMode::Only;
221 loadRequest(ResourceRequest { m_bypassingPreflightForServiceWorkerRequest.value() }, SecurityCheckPolicy::SkipSecurityCheck);
222 return;
223 }
224 }
225#endif
226 if (!needsPreflightQuirk && !checkURLSchemeAsCORSEnabled(request.url()))
227 return;
228
229 m_simpleRequest = false;
230 if (auto* page = document().page(); page && CrossOriginPreflightResultCache::singleton().canSkipPreflight(page->sessionID(), securityOrigin().toString(), request.url(), m_options.storedCredentialsPolicy, request.httpMethod(), request.httpHeaderFields()))
231 preflightSuccess(WTFMove(request));
232 else
233 makeCrossOriginAccessRequestWithPreflight(WTFMove(request));
234 }
235}
236
237void DocumentThreadableLoader::makeSimpleCrossOriginAccessRequest(ResourceRequest&& request)
238{
239 ASSERT(m_options.preflightPolicy != PreflightPolicy::Force || shouldPerformSecurityChecks());
240 ASSERT(m_options.preflightPolicy == PreflightPolicy::Prevent || isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields()) || shouldPerformSecurityChecks());
241
242 updateRequestForAccessControl(request, securityOrigin(), m_options.storedCredentialsPolicy);
243 loadRequest(WTFMove(request), SecurityCheckPolicy::DoSecurityCheck);
244}
245
246void DocumentThreadableLoader::makeCrossOriginAccessRequestWithPreflight(ResourceRequest&& request)
247{
248 if (m_async) {
249 m_preflightChecker.emplace(*this, WTFMove(request));
250 m_preflightChecker->startPreflight();
251 return;
252 }
253 CrossOriginPreflightChecker::doPreflight(*this, WTFMove(request));
254}
255
256DocumentThreadableLoader::~DocumentThreadableLoader()
257{
258 if (m_resource)
259 m_resource->removeClient(*this);
260}
261
262void DocumentThreadableLoader::cancel()
263{
264 Ref<DocumentThreadableLoader> protectedThis(*this);
265
266 // Cancel can re-enter and m_resource might be null here as a result.
267 if (m_client && m_resource) {
268 // FIXME: This error is sent to the client in didFail(), so it should not be an internal one. Use FrameLoaderClient::cancelledError() instead.
269 ResourceError error(errorDomainWebKitInternal, 0, m_resource->url(), "Load cancelled"_s, ResourceError::Type::Cancellation);
270 m_client->didFail(error);
271 }
272 clearResource();
273 m_client = nullptr;
274}
275
276void DocumentThreadableLoader::computeIsDone()
277{
278 if (!m_async || m_preflightChecker || !m_resource) {
279 if (m_client)
280 m_client->notifyIsDone(m_async && !m_preflightChecker && !m_resource);
281 return;
282 }
283 platformStrategies()->loaderStrategy()->isResourceLoadFinished(*m_resource, [this, weakThis = WeakPtr { *this }](bool isDone) {
284 if (weakThis && m_client)
285 m_client->notifyIsDone(isDone);
286 });
287}
288
289void DocumentThreadableLoader::setDefersLoading(bool value)
290{
291 if (m_resource)
292 m_resource->setDefersLoading(value);
293 if (m_preflightChecker)
294 m_preflightChecker->setDefersLoading(value);
295}
296
297void DocumentThreadableLoader::clearResource()
298{
299 // Script can cancel and restart a request reentrantly within removeClient(),
300 // which could lead to calling CachedResource::removeClient() multiple times for
301 // this DocumentThreadableLoader. Save off a copy of m_resource and clear it to
302 // prevent the reentrancy.
303 if (CachedResourceHandle<CachedRawResource> resource = m_resource) {
304 m_resource = nullptr;
305 resource->removeClient(*this);
306 }
307 if (m_preflightChecker)
308 m_preflightChecker = std::nullopt;
309}
310
311void DocumentThreadableLoader::redirectReceived(CachedResource& resource, ResourceRequest&& request, const ResourceResponse& redirectResponse, CompletionHandler<void(ResourceRequest&&)>&& completionHandler)
312{
313 ASSERT(m_client);
314 ASSERT_UNUSED(resource, &resource == m_resource);
315
316 Ref<DocumentThreadableLoader> protectedThis(*this);
317 --m_options.maxRedirectCount;
318
319 if (m_client)
320 m_client->redirectReceived(request.url());
321
322 // FIXME: We restrict this check to Fetch API for the moment, as this might disrupt WorkerScriptLoader.
323 // Reassess this check based on https://github.com/whatwg/fetch/issues/393 discussions.
324 // We should also disable that check in navigation mode.
325 if (!request.url().protocolIsInHTTPFamily() && m_options.initiator == cachedResourceRequestInitiators().fetch) {
326 reportRedirectionWithBadScheme(request.url());
327 clearResource();
328 return completionHandler(WTFMove(request));
329 }
330
331 if (platformStrategies()->loaderStrategy()->havePerformedSecurityChecks(redirectResponse)) {
332 completionHandler(WTFMove(request));
333 return;
334 }
335
336 if (!isAllowedByContentSecurityPolicy(request.url(), redirectResponse.isNull() ? ContentSecurityPolicy::RedirectResponseReceived::No : ContentSecurityPolicy::RedirectResponseReceived::Yes, redirectResponse.url())) {
337 reportContentSecurityPolicyError(redirectResponse.url());
338 clearResource();
339 return completionHandler(WTFMove(request));
340 }
341
342 // Allow same origin requests to continue after allowing clients to audit the redirect.
343 if (isAllowedRedirect(request.url()))
344 return completionHandler(WTFMove(request));
345
346 // Force any subsequent request to use these checks.
347 m_sameOriginRequest = false;
348
349 ASSERT(m_resource);
350 ASSERT(m_originalHeaders);
351
352 // Use a unique for subsequent loads if needed.
353 // https://fetch.spec.whatwg.org/#concept-http-redirect-fetch (Step 10).
354 ASSERT(m_options.mode == FetchOptions::Mode::Cors);
355 if (!securityOrigin().canRequest(redirectResponse.url()) && !protocolHostAndPortAreEqual(redirectResponse.url(), request.url()))
356 m_origin = SecurityOrigin::createUnique();
357
358 // Except in case where preflight is needed, loading should be able to continue on its own.
359 // But we also handle credentials here if it is restricted to SameOrigin.
360 if (m_options.credentials != FetchOptions::Credentials::SameOrigin && m_simpleRequest && isSimpleCrossOriginAccessRequest(request.httpMethod(), *m_originalHeaders))
361 return completionHandler(WTFMove(request));
362
363 if (m_options.credentials == FetchOptions::Credentials::SameOrigin)
364 m_options.storedCredentialsPolicy = StoredCredentialsPolicy::DoNotUse;
365
366 clearResource();
367
368 m_referrer = request.httpReferrer();
369 if (m_referrer.isNull())
370 m_options.referrerPolicy = ReferrerPolicy::NoReferrer;
371
372 // Let's fetch the request with the original headers (equivalent to request cloning specified by fetch algorithm).
373 // Do not copy the Authorization header if removed by the network layer.
374 if (!request.httpHeaderFields().contains(HTTPHeaderName::Authorization))
375 m_originalHeaders->remove(HTTPHeaderName::Authorization);
376 request.setHTTPHeaderFields(*m_originalHeaders);
377
378#if ENABLE(SERVICE_WORKER)
379 if (redirectResponse.source() != ResourceResponse::Source::ServiceWorker && redirectResponse.source() != ResourceResponse::Source::MemoryCache)
380 m_options.serviceWorkersMode = ServiceWorkersMode::None;
381#endif
382 makeCrossOriginAccessRequest(ResourceRequest(request));
383 completionHandler(WTFMove(request));
384}
385
386void DocumentThreadableLoader::dataSent(CachedResource& resource, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
387{
388 ASSERT(m_client);
389 ASSERT_UNUSED(resource, &resource == m_resource);
390 m_client->didSendData(bytesSent, totalBytesToBeSent);
391}
392
393void DocumentThreadableLoader::responseReceived(CachedResource& resource, const ResourceResponse& response, CompletionHandler<void()>&& completionHandler)
394{
395 ASSERT_UNUSED(resource, &resource == m_resource);
396 if (!m_responsesCanBeOpaque) {
397 ResourceResponse responseWithoutTainting = response;
398 responseWithoutTainting.setTainting(ResourceResponse::Tainting::Basic);
399 didReceiveResponse(m_resource->identifier(), responseWithoutTainting);
400 } else
401 didReceiveResponse(m_resource->identifier(), response);
402
403 if (completionHandler)
404 completionHandler();
405}
406
407void DocumentThreadableLoader::didReceiveResponse(ResourceLoaderIdentifier identifier, const ResourceResponse& response)
408{
409 ASSERT(m_client);
410 ASSERT(response.type() != ResourceResponse::Type::Error);
411
412#if ENABLE(SERVICE_WORKER)
413 // https://fetch.spec.whatwg.org/commit-snapshots/6257e220d70f560a037e46f1b4206325400db8dc/#main-fetch step 17.
414 if (response.source() == ResourceResponse::Source::ServiceWorker && response.url() != m_resource->url()) {
415 if (!isResponseAllowedByContentSecurityPolicy(response)) {
416 reportContentSecurityPolicyError(response.url());
417 return;
418 }
419 }
420#endif
421
422 InspectorInstrumentation::didReceiveThreadableLoaderResponse(*this, identifier);
423
424 if (m_delayCallbacksForIntegrityCheck)
425 return;
426
427 if (options().filteringPolicy == ResponseFilteringPolicy::Disable) {
428 m_client->didReceiveResponse(identifier, response);
429 return;
430 }
431
432 if (response.type() == ResourceResponse::Type::Default) {
433 m_client->didReceiveResponse(identifier, ResourceResponse::filter(response, m_options.credentials == FetchOptions::Credentials::Include ? ResourceResponse::PerformExposeAllHeadersCheck::No : ResourceResponse::PerformExposeAllHeadersCheck::Yes));
434 if (response.tainting() == ResourceResponse::Tainting::Opaque) {
435 clearResource();
436 if (m_client)
437 m_client->didFinishLoading(identifier, { });
438 }
439 return;
440 }
441 ASSERT(response.type() == ResourceResponse::Type::Opaqueredirect || response.source() == ResourceResponse::Source::ServiceWorker || response.source() == ResourceResponse::Source::MemoryCache);
442 m_client->didReceiveResponse(identifier, response);
443}
444
445void DocumentThreadableLoader::dataReceived(CachedResource& resource, const SharedBuffer& buffer)
446{
447 ASSERT_UNUSED(resource, &resource == m_resource);
448 didReceiveData(m_resource->identifier(), buffer);
449}
450
451void DocumentThreadableLoader::didReceiveData(ResourceLoaderIdentifier, const SharedBuffer& buffer)
452{
453 ASSERT(m_client);
454
455 if (m_delayCallbacksForIntegrityCheck)
456 return;
457
458 m_client->didReceiveData(buffer);
459}
460
461void DocumentThreadableLoader::finishedTimingForWorkerLoad(CachedResource& resource, const ResourceTiming& resourceTiming)
462{
463 ASSERT(m_client);
464 ASSERT_UNUSED(resource, &resource == m_resource);
465
466 finishedTimingForWorkerLoad(resourceTiming);
467}
468
469void DocumentThreadableLoader::finishedTimingForWorkerLoad(const ResourceTiming& resourceTiming)
470{
471 ASSERT(m_options.initiatorContext == InitiatorContext::Worker);
472
473 m_client->didFinishTiming(resourceTiming);
474}
475
476void DocumentThreadableLoader::notifyFinished(CachedResource& resource, const NetworkLoadMetrics& metrics)
477{
478 ASSERT(m_client);
479 ASSERT_UNUSED(resource, &resource == m_resource);
480
481 if (m_resource->errorOccurred())
482 didFail(m_resource->identifier(), m_resource->resourceError());
483 else
484 didFinishLoading(m_resource->identifier(), metrics);
485}
486
487void DocumentThreadableLoader::didFinishLoading(ResourceLoaderIdentifier identifier, const NetworkLoadMetrics& metrics)
488{
489 ASSERT(m_client);
490
491 if (m_delayCallbacksForIntegrityCheck) {
492 if (!matchIntegrityMetadata(*m_resource, m_options.integrity)) {
493 reportIntegrityMetadataError(*m_resource, m_options.integrity);
494 return;
495 }
496
497 auto response = m_resource->response();
498
499 RefPtr<SharedBuffer> buffer;
500 if (m_resource->resourceBuffer())
501 buffer = m_resource->resourceBuffer()->makeContiguous();
502 if (options().filteringPolicy == ResponseFilteringPolicy::Disable) {
503 m_client->didReceiveResponse(identifier, response);
504 if (buffer)
505 m_client->didReceiveData(*buffer);
506 } else {
507 ASSERT(response.type() == ResourceResponse::Type::Default);
508
509 m_client->didReceiveResponse(identifier, ResourceResponse::filter(response, m_options.credentials == FetchOptions::Credentials::Include ? ResourceResponse::PerformExposeAllHeadersCheck::No : ResourceResponse::PerformExposeAllHeadersCheck::Yes));
510 if (buffer)
511 m_client->didReceiveData(*buffer);
512 }
513 }
514
515 m_client->didFinishLoading(identifier, metrics);
516}
517
518void DocumentThreadableLoader::didFail(ResourceLoaderIdentifier, const ResourceError& error)
519{
520 ASSERT(m_client);
521#if ENABLE(SERVICE_WORKER)
522 if (m_bypassingPreflightForServiceWorkerRequest && error.isCancellation()) {
523 clearResource();
524
525 m_options.serviceWorkersMode = ServiceWorkersMode::None;
526 makeCrossOriginAccessRequestWithPreflight(WTFMove(m_bypassingPreflightForServiceWorkerRequest.value()));
527 ASSERT(m_bypassingPreflightForServiceWorkerRequest->isNull());
528 m_bypassingPreflightForServiceWorkerRequest = std::nullopt;
529 return;
530 }
531#endif
532
533 if (m_shouldLogError == ShouldLogError::Yes)
534 logError(m_document, error, m_options.initiator);
535
536 m_client->didFail(error);
537}
538
539void DocumentThreadableLoader::preflightSuccess(ResourceRequest&& request)
540{
541 ResourceRequest actualRequest(WTFMove(request));
542 updateRequestForAccessControl(actualRequest, securityOrigin(), m_options.storedCredentialsPolicy);
543
544 m_preflightChecker = std::nullopt;
545
546 // It should be ok to skip the security check since we already asked about the preflight request.
547 loadRequest(WTFMove(actualRequest), SecurityCheckPolicy::SkipSecurityCheck);
548}
549
550void DocumentThreadableLoader::preflightFailure(ResourceLoaderIdentifier identifier, const ResourceError& error)
551{
552 m_preflightChecker = std::nullopt;
553
554 InspectorInstrumentation::didFailLoading(m_document.frame(), m_document.frame()->loader().documentLoader(), identifier, error);
555
556 if (m_shouldLogError == ShouldLogError::Yes)
557 logError(m_document, error, m_options.initiator);
558
559 m_client->didFail(error);
560}
561
562void DocumentThreadableLoader::loadRequest(ResourceRequest&& request, SecurityCheckPolicy securityCheck)
563{
564 Ref<DocumentThreadableLoader> protectedThis(*this);
565
566 // Any credential should have been removed from the cross-site requests.
567 const URL& requestURL = request.url();
568 m_options.securityCheck = securityCheck;
569 ASSERT(m_sameOriginRequest || !requestURL.hasCredentials());
570
571 if (!m_referrer.isNull())
572 request.setHTTPReferrer(m_referrer);
573
574 if (m_async) {
575 ResourceLoaderOptions options = m_options;
576 options.clientCredentialPolicy = m_sameOriginRequest ? ClientCredentialPolicy::MayAskClientForCredentials : ClientCredentialPolicy::CannotAskClientForCredentials;
577 options.contentSecurityPolicyImposition = ContentSecurityPolicyImposition::SkipPolicyCheck;
578
579 // If there is integrity metadata to validate, we must buffer.
580 if (!m_options.integrity.isEmpty())
581 options.dataBufferingPolicy = DataBufferingPolicy::BufferData;
582
583 request.setAllowCookies(m_options.storedCredentialsPolicy == StoredCredentialsPolicy::Use);
584 CachedResourceRequest newRequest(WTFMove(request), options);
585 newRequest.setInitiator(AtomString { m_options.initiator });
586 newRequest.setOrigin(securityOrigin());
587
588 ASSERT(!m_resource);
589 if (m_resource) {
590 CachedResourceHandle<CachedRawResource> resource = std::exchange(m_resource, nullptr);
591 resource->removeClient(*this);
592 }
593
594 auto cachedResource = m_document.cachedResourceLoader().requestRawResource(WTFMove(newRequest));
595 m_resource = cachedResource.value_or(nullptr);
596 if (m_resource)
597 m_resource->addClient(*this);
598 else
599 logErrorAndFail(cachedResource.error());
600 return;
601 }
602
603 // If credentials mode is 'Omit', we should disable cookie sending.
604 ASSERT(m_options.credentials != FetchOptions::Credentials::Omit);
605
606 ResourceLoadTiming loadTiming;
607 loadTiming.markStartTime();
608
609 // FIXME: ThreadableLoaderOptions.sniffContent is not supported for synchronous requests.
610 RefPtr<SharedBuffer> data;
611 ResourceError error;
612 ResourceResponse response;
613 auto identifier = makeObjectIdentifier<ResourceLoader>(std::numeric_limits<uint64_t>::max());
614 if (auto* frame = m_document.frame()) {
615 if (!MixedContentChecker::canRunInsecureContent(*frame, m_document.securityOrigin(), requestURL))
616 return;
617 auto& frameLoader = frame->loader();
618 identifier = frameLoader.loadResourceSynchronously(request, m_options.clientCredentialPolicy, m_options, *m_originalHeaders, error, response, data);
619 }
620
621 loadTiming.markEndTime();
622
623 if (!error.isNull() && response.httpStatusCode() <= 0) {
624 if (requestURL.isLocalFile()) {
625 // We don't want XMLHttpRequest to raise an exception for file:// resources, see <rdar://problem/4962298>.
626 // FIXME: XMLHttpRequest quirks should be in XMLHttpRequest code, not in DocumentThreadableLoader.cpp.
627 didReceiveResponse(identifier, response);
628 didFinishLoading(identifier, { });
629 return;
630 }
631 logErrorAndFail(error);
632 return;
633 }
634
635 if (response.containsInvalidHTTPHeaders()) {
636 didFail(identifier, ResourceError(errorDomainWebKitInternal, 0, request.url(), "Response contained invalid HTTP headers"_s, ResourceError::Type::General));
637 return;
638 }
639
640 if (!shouldPerformSecurityChecks()) {
641 // FIXME: FrameLoader::loadSynchronously() does not tell us whether a redirect happened or not, so we guess by comparing the
642 // request and response URLs. This isn't a perfect test though, since a server can serve a redirect to the same URL that was
643 // requested. Also comparing the request and response URLs as strings will fail if the requestURL still has its credentials.
644 bool didRedirect = requestURL != response.url();
645 if (didRedirect) {
646 if (!isAllowedByContentSecurityPolicy(response.url(), ContentSecurityPolicy::RedirectResponseReceived::Yes)) {
647 reportContentSecurityPolicyError(requestURL);
648 return;
649 }
650 if (!isAllowedRedirect(response.url())) {
651 reportCrossOriginResourceSharingError(requestURL);
652 return;
653 }
654 }
655
656 if (!m_sameOriginRequest) {
657 if (m_options.mode == FetchOptions::Mode::NoCors)
658 response.setTainting(ResourceResponse::Tainting::Opaque);
659 else {
660 ASSERT(m_options.mode == FetchOptions::Mode::Cors);
661 response.setTainting(ResourceResponse::Tainting::Cors);
662 auto accessControlCheckResult = passesAccessControlCheck(response, m_options.storedCredentialsPolicy, securityOrigin(), &CrossOriginAccessControlCheckDisabler::singleton());
663 if (!accessControlCheckResult) {
664 logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, response.url(), accessControlCheckResult.error(), ResourceError::Type::AccessControl));
665 return;
666 }
667 }
668 }
669 }
670 didReceiveResponse(identifier, response);
671
672 if (data)
673 didReceiveData(identifier, *data);
674
675 const auto* timing = response.deprecatedNetworkLoadMetricsOrNull();
676 auto resourceTiming = ResourceTiming::fromSynchronousLoad(requestURL, m_options.initiator, loadTiming, timing ? *timing : NetworkLoadMetrics::emptyMetrics(), response, securityOrigin());
677 if (options().initiatorContext == InitiatorContext::Worker)
678 finishedTimingForWorkerLoad(resourceTiming);
679 else {
680 if (auto* window = document().domWindow())
681 window->performance().addResourceTiming(WTFMove(resourceTiming));
682 }
683
684 didFinishLoading(identifier, { });
685}
686
687bool DocumentThreadableLoader::isAllowedByContentSecurityPolicy(const URL& url, ContentSecurityPolicy::RedirectResponseReceived redirectResponseReceived, const URL& preRedirectURL)
688{
689 switch (m_options.contentSecurityPolicyEnforcement) {
690 case ContentSecurityPolicyEnforcement::DoNotEnforce:
691 return true;
692 case ContentSecurityPolicyEnforcement::EnforceWorkerSrcDirective:
693 return contentSecurityPolicy().allowWorkerFromSource(url, redirectResponseReceived, preRedirectURL);
694 case ContentSecurityPolicyEnforcement::EnforceConnectSrcDirective:
695 return contentSecurityPolicy().allowConnectToSource(url, redirectResponseReceived, preRedirectURL);
696 case ContentSecurityPolicyEnforcement::EnforceScriptSrcDirective:
697 return contentSecurityPolicy().allowScriptFromSource(url, redirectResponseReceived, preRedirectURL, m_options.integrity, m_options.nonce);
698 }
699 ASSERT_NOT_REACHED();
700 return false;
701}
702
703bool DocumentThreadableLoader::isResponseAllowedByContentSecurityPolicy(const ResourceResponse& response)
704{
705 return isAllowedByContentSecurityPolicy(response.url(), ContentSecurityPolicy::RedirectResponseReceived::Yes, { });
706}
707
708bool DocumentThreadableLoader::isAllowedRedirect(const URL& url)
709{
710 if (m_options.mode == FetchOptions::Mode::NoCors)
711 return true;
712
713 return m_sameOriginRequest && securityOrigin().canRequest(url);
714}
715
716SecurityOrigin& DocumentThreadableLoader::securityOrigin() const
717{
718 return m_origin ? *m_origin : m_document.securityOrigin();
719}
720
721const ContentSecurityPolicy& DocumentThreadableLoader::contentSecurityPolicy() const
722{
723 if (m_contentSecurityPolicy)
724 return *m_contentSecurityPolicy.get();
725 ASSERT(m_document.contentSecurityPolicy());
726 return *m_document.contentSecurityPolicy();
727}
728
729const CrossOriginEmbedderPolicy& DocumentThreadableLoader::crossOriginEmbedderPolicy() const
730{
731 if (m_crossOriginEmbedderPolicy)
732 return *m_crossOriginEmbedderPolicy;
733 return m_document.crossOriginEmbedderPolicy();
734}
735
736void DocumentThreadableLoader::reportRedirectionWithBadScheme(const URL& url)
737{
738 logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, url, "Redirection to URL with a scheme that is not HTTP(S)."_s, ResourceError::Type::AccessControl));
739}
740
741void DocumentThreadableLoader::reportContentSecurityPolicyError(const URL& url)
742{
743 logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, url, "Blocked by Content Security Policy."_s, ResourceError::Type::AccessControl));
744}
745
746void DocumentThreadableLoader::reportCrossOriginResourceSharingError(const URL& url)
747{
748 logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, url, "Cross-origin redirection denied by Cross-Origin Resource Sharing policy."_s, ResourceError::Type::AccessControl));
749}
750
751void DocumentThreadableLoader::reportIntegrityMetadataError(const CachedResource& resource, const String& expectedMetadata)
752{
753 logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, resource.url(), makeString("Failed integrity metadata check. "_s, integrityMismatchDescription(resource, expectedMetadata)), ResourceError::Type::AccessControl));
754}
755
756void DocumentThreadableLoader::logErrorAndFail(const ResourceError& error)
757{
758 if (m_shouldLogError == ShouldLogError::Yes) {
759 if (error.isAccessControl() && error.domain() != InspectorNetworkAgent::errorDomain() && !error.localizedDescription().isEmpty())
760 m_document.addConsoleMessage(MessageSource::Security, MessageLevel::Error, error.localizedDescription());
761 logError(m_document, error, m_options.initiator);
762 }
763 ASSERT(m_client);
764 m_client->didFail(error);
765}
766
767} // namespace WebCore
Note: See TracBrowser for help on using the repository browser.