34997fc691cb983ec7d0bc5c3058370008011086
[WebKit-https.git] / Source / WebCore / loader / DocumentThreadableLoader.cpp
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 "Frame.h"
44 #include "FrameLoader.h"
45 #include "InspectorInstrumentation.h"
46 #include "LoadTiming.h"
47 #include "Performance.h"
48 #include "ProgressTracker.h"
49 #include "ResourceError.h"
50 #include "ResourceRequest.h"
51 #include "ResourceTiming.h"
52 #include "RuntimeEnabledFeatures.h"
53 #include "SchemeRegistry.h"
54 #include "SecurityOrigin.h"
55 #include "SharedBuffer.h"
56 #include "SubresourceIntegrity.h"
57 #include "SubresourceLoader.h"
58 #include "ThreadableLoaderClient.h"
59 #include <wtf/Assertions.h>
60 #include <wtf/Ref.h>
61
62 namespace WebCore {
63
64 void DocumentThreadableLoader::loadResourceSynchronously(Document& document, ResourceRequest&& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options, RefPtr<SecurityOrigin>&& origin, std::unique_ptr<ContentSecurityPolicy>&& contentSecurityPolicy)
65 {
66     // The loader will be deleted as soon as this function exits.
67     Ref<DocumentThreadableLoader> loader = adoptRef(*new DocumentThreadableLoader(document, client, LoadSynchronously, WTFMove(request), options, WTFMove(origin), WTFMove(contentSecurityPolicy), String(), ShouldLogError::Yes));
68     ASSERT(loader->hasOneRef());
69 }
70
71 void DocumentThreadableLoader::loadResourceSynchronously(Document& document, ResourceRequest&& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
72 {
73     loadResourceSynchronously(document, WTFMove(request), client, options, nullptr, nullptr);
74 }
75
76 RefPtr<DocumentThreadableLoader> DocumentThreadableLoader::create(Document& document, ThreadableLoaderClient& client,
77 ResourceRequest&& request, const ThreadableLoaderOptions& options, RefPtr<SecurityOrigin>&& origin,
78 std::unique_ptr<ContentSecurityPolicy>&& contentSecurityPolicy, String&& referrer, ShouldLogError shouldLogError)
79 {
80     RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, client, LoadAsynchronously, WTFMove(request), options, WTFMove(origin), WTFMove(contentSecurityPolicy), WTFMove(referrer), shouldLogError));
81     if (!loader->isLoading())
82         loader = nullptr;
83     return loader;
84 }
85
86 RefPtr<DocumentThreadableLoader> DocumentThreadableLoader::create(Document& document, ThreadableLoaderClient& client, ResourceRequest&& request, const ThreadableLoaderOptions& options, String&& referrer)
87 {
88     return create(document, client, WTFMove(request), options, nullptr, nullptr, WTFMove(referrer), ShouldLogError::Yes);
89 }
90
91 DocumentThreadableLoader::DocumentThreadableLoader(Document& document, ThreadableLoaderClient& client, BlockingBehavior blockingBehavior, ResourceRequest&& request, const ThreadableLoaderOptions& options, RefPtr<SecurityOrigin>&& origin, std::unique_ptr<ContentSecurityPolicy>&& contentSecurityPolicy, String&& referrer, ShouldLogError shouldLogError)
92     : m_client(&client)
93     , m_document(document)
94     , m_options(options)
95     , m_origin(WTFMove(origin))
96     , m_referrer(WTFMove(referrer))
97     , m_sameOriginRequest(securityOrigin().canRequest(request.url()))
98     , m_simpleRequest(true)
99     , m_async(blockingBehavior == LoadAsynchronously)
100     , m_delayCallbacksForIntegrityCheck(!m_options.integrity.isEmpty())
101     , m_contentSecurityPolicy(WTFMove(contentSecurityPolicy))
102     , m_shouldLogError(shouldLogError)
103 {
104     relaxAdoptionRequirement();
105
106     // Setting a referrer header is only supported in the async code path.
107     ASSERT(m_async || m_referrer.isEmpty());
108
109     // Referrer and Origin headers should be set after the preflight if any.
110     ASSERT(!request.hasHTTPReferrer() && !request.hasHTTPOrigin());
111
112     ASSERT_WITH_SECURITY_IMPLICATION(isAllowedByContentSecurityPolicy(request.url(), ContentSecurityPolicy::RedirectResponseReceived::No));
113
114     m_options.allowCredentials = (m_options.credentials == FetchOptions::Credentials::Include || (m_options.credentials == FetchOptions::Credentials::SameOrigin && m_sameOriginRequest)) ? AllowStoredCredentials : DoNotAllowStoredCredentials;
115
116     ASSERT(!request.httpHeaderFields().contains(HTTPHeaderName::Origin));
117
118     // Copy headers if we need to replay the request after a redirection.
119     if (m_async && m_options.mode == FetchOptions::Mode::Cors)
120         m_originalHeaders = request.httpHeaderFields();
121
122     if (document.page() && document.page()->isRunningUserScripts() && SchemeRegistry::isUserExtensionScheme(request.url().protocol().toStringWithoutCopying())) {
123         m_options.mode = FetchOptions::Mode::NoCors;
124         m_options.filteringPolicy = ResponseFilteringPolicy::Disable;
125     }
126
127     // 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.
128     if (request.url().protocolIsData())
129         m_sameOriginRequest = options.sameOriginDataURLFlag == SameOriginDataURLFlag::Set;
130
131     if (m_sameOriginRequest || m_options.mode == FetchOptions::Mode::NoCors) {
132         loadRequest(WTFMove(request), DoSecurityCheck);
133         return;
134     }
135
136     if (m_options.mode == FetchOptions::Mode::SameOrigin) {
137         logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, request.url(), "Cross origin requests are not allowed when using same-origin fetch mode."));
138         return;
139     }
140
141     makeCrossOriginAccessRequest(WTFMove(request));
142 }
143
144 void DocumentThreadableLoader::makeCrossOriginAccessRequest(ResourceRequest&& request)
145 {
146     ASSERT(m_options.mode == FetchOptions::Mode::Cors);
147
148     if ((m_options.preflightPolicy == ConsiderPreflight && isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields())) || m_options.preflightPolicy == PreventPreflight)
149         makeSimpleCrossOriginAccessRequest(WTFMove(request));
150     else {
151         m_simpleRequest = false;
152         if (CrossOriginPreflightResultCache::singleton().canSkipPreflight(securityOrigin().toString(), request.url(), m_options.allowCredentials, request.httpMethod(), request.httpHeaderFields()))
153             preflightSuccess(WTFMove(request));
154         else
155             makeCrossOriginAccessRequestWithPreflight(WTFMove(request));
156     }
157 }
158
159 void DocumentThreadableLoader::makeSimpleCrossOriginAccessRequest(ResourceRequest&& request)
160 {
161     ASSERT(m_options.preflightPolicy != ForcePreflight);
162     ASSERT(m_options.preflightPolicy == PreventPreflight || isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields()));
163
164     // 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.
165     if (!SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(request.url().protocol().toStringWithoutCopying())) {
166         logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, request.url(), "Cross origin requests are only supported for HTTP.", ResourceError::Type::AccessControl));
167         return;
168     }
169
170     updateRequestForAccessControl(request, securityOrigin(), m_options.allowCredentials);
171     loadRequest(WTFMove(request), DoSecurityCheck);
172 }
173
174 void DocumentThreadableLoader::makeCrossOriginAccessRequestWithPreflight(ResourceRequest&& request)
175 {
176     if (m_async) {
177         m_preflightChecker.emplace(*this, WTFMove(request));
178         m_preflightChecker->startPreflight();
179         return;
180     }
181     CrossOriginPreflightChecker::doPreflight(*this, WTFMove(request));
182 }
183
184 DocumentThreadableLoader::~DocumentThreadableLoader()
185 {
186     if (m_resource)
187         m_resource->removeClient(*this);
188 }
189
190 void DocumentThreadableLoader::cancel()
191 {
192     Ref<DocumentThreadableLoader> protectedThis(*this);
193
194     // Cancel can re-enter and m_resource might be null here as a result.
195     if (m_client && m_resource) {
196         // FIXME: This error is sent to the client in didFail(), so it should not be an internal one. Use FrameLoaderClient::cancelledError() instead.
197         ResourceError error(errorDomainWebKitInternal, 0, m_resource->url(), "Load cancelled", ResourceError::Type::Cancellation);
198         m_client->didFail(error);
199     }
200     clearResource();
201     m_client = nullptr;
202 }
203
204 void DocumentThreadableLoader::setDefersLoading(bool value)
205 {
206     if (m_resource)
207         m_resource->setDefersLoading(value);
208     if (m_preflightChecker)
209         m_preflightChecker->setDefersLoading(value);
210 }
211
212 void DocumentThreadableLoader::clearResource()
213 {
214     // Script can cancel and restart a request reentrantly within removeClient(),
215     // which could lead to calling CachedResource::removeClient() multiple times for
216     // this DocumentThreadableLoader. Save off a copy of m_resource and clear it to
217     // prevent the reentrancy.
218     if (CachedResourceHandle<CachedRawResource> resource = m_resource) {
219         m_resource = nullptr;
220         resource->removeClient(*this);
221     }
222     if (m_preflightChecker)
223         m_preflightChecker = std::nullopt;
224 }
225
226 void DocumentThreadableLoader::redirectReceived(CachedResource& resource, ResourceRequest& request, const ResourceResponse& redirectResponse)
227 {
228     ASSERT(m_client);
229     ASSERT_UNUSED(resource, &resource == m_resource);
230
231     Ref<DocumentThreadableLoader> protectedThis(*this);
232     --m_options.maxRedirectCount;
233
234     // FIXME: We restrict this check to Fetch API for the moment, as this might disrupt WorkerScriptLoader.
235     // Reassess this check based on https://github.com/whatwg/fetch/issues/393 discussions.
236     // We should also disable that check in navigation mode.
237     if (!request.url().protocolIsInHTTPFamily() && m_options.initiator == cachedResourceRequestInitiators().fetch) {
238         reportRedirectionWithBadScheme(request.url());
239         clearResource();
240         return;
241     }
242
243     if (!isAllowedByContentSecurityPolicy(request.url(), redirectResponse.isNull() ? ContentSecurityPolicy::RedirectResponseReceived::No : ContentSecurityPolicy::RedirectResponseReceived::Yes)) {
244         reportContentSecurityPolicyError(redirectResponse.url());
245         clearResource();
246         return;
247     }
248
249     // Allow same origin requests to continue after allowing clients to audit the redirect.
250     if (isAllowedRedirect(request.url()))
251         return;
252
253     // Force any subsequent request to use these checks.
254     m_sameOriginRequest = false;
255
256     ASSERT(m_resource);
257     ASSERT(m_originalHeaders);
258
259     // Use a unique for subsequent loads if needed.
260     // https://fetch.spec.whatwg.org/#concept-http-redirect-fetch (Step 10).
261     ASSERT(m_options.mode == FetchOptions::Mode::Cors);
262     if (!securityOrigin().canRequest(redirectResponse.url()) && !protocolHostAndPortAreEqual(redirectResponse.url(), request.url()))
263         m_origin = SecurityOrigin::createUnique();
264
265     // Except in case where preflight is needed, loading should be able to continue on its own.
266     // But we also handle credentials here if it is restricted to SameOrigin.
267     if (m_options.credentials != FetchOptions::Credentials::SameOrigin && m_simpleRequest && isSimpleCrossOriginAccessRequest(request.httpMethod(), *m_originalHeaders))
268         return;
269
270     m_options.allowCredentials = DoNotAllowStoredCredentials;
271
272     clearResource();
273
274     // Let's fetch the request with the original headers (equivalent to request cloning specified by fetch algorithm).
275     // Do not copy the Authorization header if removed by the network layer.
276     if (!request.httpHeaderFields().contains(HTTPHeaderName::Authorization))
277         m_originalHeaders->remove(HTTPHeaderName::Authorization);
278     request.setHTTPHeaderFields(*m_originalHeaders);
279
280     makeCrossOriginAccessRequest(ResourceRequest(request));
281 }
282
283 void DocumentThreadableLoader::dataSent(CachedResource& resource, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
284 {
285     ASSERT(m_client);
286     ASSERT_UNUSED(resource, &resource == m_resource);
287     m_client->didSendData(bytesSent, totalBytesToBeSent);
288 }
289
290 void DocumentThreadableLoader::responseReceived(CachedResource& resource, const ResourceResponse& response)
291 {
292     ASSERT_UNUSED(resource, &resource == m_resource);
293     didReceiveResponse(m_resource->identifier(), response, m_resource->responseTainting());
294 }
295
296 void DocumentThreadableLoader::didReceiveResponse(unsigned long identifier, const ResourceResponse& response, ResourceResponse::Tainting tainting)
297 {
298     ASSERT(m_client);
299     ASSERT(response.type() != ResourceResponse::Type::Error);
300
301     InspectorInstrumentation::didReceiveThreadableLoaderResponse(*this, identifier);
302
303     if (m_delayCallbacksForIntegrityCheck)
304         return;
305
306     if (options().filteringPolicy == ResponseFilteringPolicy::Disable) {
307         m_client->didReceiveResponse(identifier, response);
308         return;
309     }
310
311     if (response.type() == ResourceResponse::Type::Default) {
312         m_client->didReceiveResponse(identifier, ResourceResponse::filterResponse(response, tainting));
313         if (tainting == ResourceResponse::Tainting::Opaque) {
314             clearResource();
315             if (m_client)
316                 m_client->didFinishLoading(identifier);
317         }
318     } else {
319         ASSERT(response.type() == ResourceResponse::Type::Opaqueredirect);
320         m_client->didReceiveResponse(identifier, response);
321     }
322 }
323
324 void DocumentThreadableLoader::dataReceived(CachedResource& resource, const char* data, int dataLength)
325 {
326     ASSERT_UNUSED(resource, &resource == m_resource);
327     didReceiveData(m_resource->identifier(), data, dataLength);
328 }
329
330 void DocumentThreadableLoader::didReceiveData(unsigned long, const char* data, int dataLength)
331 {
332     ASSERT(m_client);
333
334     if (m_delayCallbacksForIntegrityCheck)
335         return;
336
337     m_client->didReceiveData(data, dataLength);
338 }
339
340 void DocumentThreadableLoader::finishedTimingForWorkerLoad(CachedResource& resource, const ResourceTiming& resourceTiming)
341 {
342     ASSERT(m_client);
343     ASSERT_UNUSED(resource, &resource == m_resource);
344
345     finishedTimingForWorkerLoad(resourceTiming);
346 }
347
348 void DocumentThreadableLoader::finishedTimingForWorkerLoad(const ResourceTiming& resourceTiming)
349 {
350     ASSERT(m_options.initiatorContext == InitiatorContext::Worker);
351
352     m_client->didFinishTiming(resourceTiming);
353 }
354
355 void DocumentThreadableLoader::notifyFinished(CachedResource& resource)
356 {
357     ASSERT(m_client);
358     ASSERT_UNUSED(resource, &resource == m_resource);
359
360     if (m_resource->errorOccurred())
361         didFail(m_resource->identifier(), m_resource->resourceError());
362     else
363         didFinishLoading(m_resource->identifier());
364 }
365
366 void DocumentThreadableLoader::didFinishLoading(unsigned long identifier)
367 {
368     ASSERT(m_client);
369
370     if (m_delayCallbacksForIntegrityCheck) {
371         if (!matchIntegrityMetadata(*m_resource, m_options.integrity)) {
372             reportIntegrityMetadataError(m_resource->url());
373             return;
374         }
375
376         auto response = m_resource->response();
377
378         if (options().filteringPolicy == ResponseFilteringPolicy::Disable) {
379             m_client->didReceiveResponse(identifier, response);
380             m_client->didReceiveData(m_resource->resourceBuffer()->data(), m_resource->resourceBuffer()->size());
381         } else {
382             ASSERT(response.type() == ResourceResponse::Type::Default);
383             
384             auto tainting = m_resource->responseTainting();
385             m_client->didReceiveResponse(identifier, ResourceResponse::filterResponse(response, tainting));
386             m_client->didReceiveData(m_resource->resourceBuffer()->data(), m_resource->resourceBuffer()->size());
387         }
388     }
389
390     m_client->didFinishLoading(identifier);
391 }
392
393 void DocumentThreadableLoader::didFail(unsigned long, const ResourceError& error)
394 {
395     ASSERT(m_client);
396     logErrorAndFail(error);
397 }
398
399 void DocumentThreadableLoader::preflightSuccess(ResourceRequest&& request)
400 {
401     ResourceRequest actualRequest(WTFMove(request));
402     updateRequestForAccessControl(actualRequest, securityOrigin(), m_options.allowCredentials);
403
404     m_preflightChecker = std::nullopt;
405
406     // It should be ok to skip the security check since we already asked about the preflight request.
407     loadRequest(WTFMove(actualRequest), SkipSecurityCheck);
408 }
409
410 void DocumentThreadableLoader::preflightFailure(unsigned long identifier, const ResourceError& error)
411 {
412     m_preflightChecker = std::nullopt;
413
414     InspectorInstrumentation::didFailLoading(m_document.frame(), m_document.frame()->loader().documentLoader(), identifier, error);
415     ASSERT(m_client);
416     logErrorAndFail(error);
417 }
418
419 void DocumentThreadableLoader::loadRequest(ResourceRequest&& request, SecurityCheckPolicy securityCheck)
420 {
421     Ref<DocumentThreadableLoader> protectedThis(*this);
422
423     // Any credential should have been removed from the cross-site requests.
424     const URL& requestURL = request.url();
425     m_options.securityCheck = securityCheck;
426     ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
427     ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
428
429     if (!m_referrer.isNull())
430         request.setHTTPReferrer(m_referrer);
431
432     if (m_async) {
433         ResourceLoaderOptions options = m_options;
434         options.clientCredentialPolicy = m_sameOriginRequest ? ClientCredentialPolicy::MayAskClientForCredentials : ClientCredentialPolicy::CannotAskClientForCredentials;
435         options.contentSecurityPolicyImposition = ContentSecurityPolicyImposition::SkipPolicyCheck;
436         
437         // If there is integrity metadata to validate, we must buffer.
438         if (!m_options.integrity.isEmpty())
439             options.dataBufferingPolicy = BufferData;
440
441         request.setAllowCookies(m_options.allowCredentials == AllowStoredCredentials);
442         CachedResourceRequest newRequest(WTFMove(request), options);
443         if (RuntimeEnabledFeatures::sharedFeatures().resourceTimingEnabled())
444             newRequest.setInitiator(m_options.initiator);
445         newRequest.setOrigin(securityOrigin());
446
447         ASSERT(!m_resource);
448         if (m_resource) {
449             CachedResourceHandle<CachedRawResource> resource = std::exchange(m_resource, nullptr);
450             resource->removeClient(*this);
451         }
452
453         // We create an URL here as the request will be moved in requestRawResource
454         URL requestUrl = newRequest.resourceRequest().url();
455         m_resource = m_document.cachedResourceLoader().requestRawResource(WTFMove(newRequest));
456         if (m_resource)
457             m_resource->addClient(*this);
458         else {
459             // FIXME: Since we receive a synchronous error, this is probably due to some AccessControl checks. We should try to retrieve the actual error.
460             logErrorAndFail(ResourceError(String(), 0, requestUrl, String(), ResourceError::Type::AccessControl));
461         }
462         return;
463     }
464
465     // If credentials mode is 'Omit', we should disable cookie sending.
466     ASSERT(m_options.credentials != FetchOptions::Credentials::Omit);
467
468     LoadTiming loadTiming;
469     loadTiming.markStartTimeAndFetchStart();
470
471     // FIXME: ThreadableLoaderOptions.sniffContent is not supported for synchronous requests.
472     RefPtr<SharedBuffer> data;
473     ResourceError error;
474     ResourceResponse response;
475     unsigned long identifier = std::numeric_limits<unsigned long>::max();
476     if (m_document.frame()) {
477         auto& frameLoader = m_document.frame()->loader();
478         if (!frameLoader.mixedContentChecker().canRunInsecureContent(m_document.securityOrigin(), requestURL))
479             return;
480         identifier = frameLoader.loadResourceSynchronously(request, m_options.allowCredentials, m_options.clientCredentialPolicy, error, response, data);
481     }
482
483     loadTiming.setResponseEnd(MonotonicTime::now());
484
485     if (!error.isNull() && response.httpStatusCode() <= 0) {
486         if (requestURL.isLocalFile()) {
487             // We don't want XMLHttpRequest to raise an exception for file:// resources, see <rdar://problem/4962298>.
488             // FIXME: XMLHttpRequest quirks should be in XMLHttpRequest code, not in DocumentThreadableLoader.cpp.
489             didReceiveResponse(identifier, response, ResourceResponse::Tainting::Basic);
490             didFinishLoading(identifier);
491             return;
492         }
493         logErrorAndFail(error);
494         return;
495     }
496
497     // FIXME: FrameLoader::loadSynchronously() does not tell us whether a redirect happened or not, so we guess by comparing the
498     // request and response URLs. This isn't a perfect test though, since a server can serve a redirect to the same URL that was
499     // requested. Also comparing the request and response URLs as strings will fail if the requestURL still has its credentials.
500     bool didRedirect = requestURL != response.url();
501     if (didRedirect) {
502         if (!isAllowedByContentSecurityPolicy(response.url(), ContentSecurityPolicy::RedirectResponseReceived::Yes)) {
503             reportContentSecurityPolicyError(requestURL);
504             return;
505         }
506         if (!isAllowedRedirect(response.url())) {
507             reportCrossOriginResourceSharingError(requestURL);
508             return;
509         }
510     }
511
512     ResourceResponse::Tainting tainting = ResourceResponse::Tainting::Basic;
513     if (!m_sameOriginRequest) {
514         if (m_options.mode == FetchOptions::Mode::NoCors)
515             tainting = ResourceResponse::Tainting::Opaque;
516         else {
517             ASSERT(m_options.mode == FetchOptions::Mode::Cors);
518             tainting = ResourceResponse::Tainting::Cors;
519             String accessControlErrorDescription;
520             if (!passesAccessControlCheck(response, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription)) {
521                 logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, response.url(), accessControlErrorDescription, ResourceError::Type::AccessControl));
522                 return;
523             }
524         }
525     }
526     didReceiveResponse(identifier, response, tainting);
527
528     if (data)
529         didReceiveData(identifier, data->data(), data->size());
530
531     if (RuntimeEnabledFeatures::sharedFeatures().resourceTimingEnabled()) {
532         auto resourceTiming = ResourceTiming::fromSynchronousLoad(requestURL, m_options.initiator, loadTiming, response.deprecatedNetworkLoadMetrics(), response, securityOrigin());
533         if (options().initiatorContext == InitiatorContext::Worker)
534             finishedTimingForWorkerLoad(resourceTiming);
535         else {
536             if (document().domWindow() && document().domWindow()->performance())
537                 document().domWindow()->performance()->addResourceTiming(WTFMove(resourceTiming));
538         }
539     }
540
541     didFinishLoading(identifier);
542 }
543
544 bool DocumentThreadableLoader::isAllowedByContentSecurityPolicy(const URL& url, ContentSecurityPolicy::RedirectResponseReceived redirectResponseReceived)
545 {
546     switch (m_options.contentSecurityPolicyEnforcement) {
547     case ContentSecurityPolicyEnforcement::DoNotEnforce:
548         return true;
549     case ContentSecurityPolicyEnforcement::EnforceChildSrcDirective:
550         return contentSecurityPolicy().allowChildContextFromSource(url, redirectResponseReceived);
551     case ContentSecurityPolicyEnforcement::EnforceConnectSrcDirective:
552         return contentSecurityPolicy().allowConnectToSource(url, redirectResponseReceived);
553     case ContentSecurityPolicyEnforcement::EnforceScriptSrcDirective:
554         return contentSecurityPolicy().allowScriptFromSource(url, redirectResponseReceived);
555     }
556     ASSERT_NOT_REACHED();
557     return false;
558 }
559
560 bool DocumentThreadableLoader::isAllowedRedirect(const URL& url)
561 {
562     if (m_options.mode == FetchOptions::Mode::NoCors)
563         return true;
564
565     return m_sameOriginRequest && securityOrigin().canRequest(url);
566 }
567
568 bool DocumentThreadableLoader::isXMLHttpRequest() const
569 {
570     return m_options.initiator == cachedResourceRequestInitiators().xmlhttprequest;
571 }
572
573 SecurityOrigin& DocumentThreadableLoader::securityOrigin() const
574 {
575     return m_origin ? *m_origin : m_document.securityOrigin();
576 }
577
578 const ContentSecurityPolicy& DocumentThreadableLoader::contentSecurityPolicy() const
579 {
580     if (m_contentSecurityPolicy)
581         return *m_contentSecurityPolicy.get();
582     ASSERT(m_document.contentSecurityPolicy());
583     return *m_document.contentSecurityPolicy();
584 }
585
586 void DocumentThreadableLoader::reportRedirectionWithBadScheme(const URL& url)
587 {
588     logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, url, "Redirection to URL with a scheme that is not HTTP(S).", ResourceError::Type::AccessControl));
589 }
590
591 void DocumentThreadableLoader::reportContentSecurityPolicyError(const URL& url)
592 {
593     logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, url, "Cross-origin redirection denied by Content Security Policy.", ResourceError::Type::AccessControl));
594 }
595
596 void DocumentThreadableLoader::reportCrossOriginResourceSharingError(const URL& url)
597 {
598     logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, url, "Cross-origin redirection denied by Cross-Origin Resource Sharing policy.", ResourceError::Type::AccessControl));
599 }
600
601 void DocumentThreadableLoader::reportIntegrityMetadataError(const URL& url)
602 {
603     logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, url, "Failed integrity metadata check.", ResourceError::Type::General));
604 }
605
606 void DocumentThreadableLoader::logErrorAndFail(const ResourceError& error)
607 {
608     if (m_shouldLogError == ShouldLogError::Yes)
609         logError(m_document, error, m_options.initiator);
610     ASSERT(m_client);
611     m_client->didFail(error);
612 }
613
614 } // namespace WebCore