[Fetch API] Response should keep all ResourceResponse information
[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);
294 }
295
296 void DocumentThreadableLoader::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
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, ResourceResponseBase::filter(response));
313         if (response.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             m_client->didReceiveResponse(identifier, ResourceResponseBase::filter(response));
385             m_client->didReceiveData(m_resource->resourceBuffer()->data(), m_resource->resourceBuffer()->size());
386         }
387     }
388
389     m_client->didFinishLoading(identifier);
390 }
391
392 void DocumentThreadableLoader::didFail(unsigned long, const ResourceError& error)
393 {
394     ASSERT(m_client);
395     logErrorAndFail(error);
396 }
397
398 void DocumentThreadableLoader::preflightSuccess(ResourceRequest&& request)
399 {
400     ResourceRequest actualRequest(WTFMove(request));
401     updateRequestForAccessControl(actualRequest, securityOrigin(), m_options.allowCredentials);
402
403     m_preflightChecker = std::nullopt;
404
405     // It should be ok to skip the security check since we already asked about the preflight request.
406     loadRequest(WTFMove(actualRequest), SkipSecurityCheck);
407 }
408
409 void DocumentThreadableLoader::preflightFailure(unsigned long identifier, const ResourceError& error)
410 {
411     m_preflightChecker = std::nullopt;
412
413     InspectorInstrumentation::didFailLoading(m_document.frame(), m_document.frame()->loader().documentLoader(), identifier, error);
414     ASSERT(m_client);
415     logErrorAndFail(error);
416 }
417
418 void DocumentThreadableLoader::loadRequest(ResourceRequest&& request, SecurityCheckPolicy securityCheck)
419 {
420     Ref<DocumentThreadableLoader> protectedThis(*this);
421
422     // Any credential should have been removed from the cross-site requests.
423     const URL& requestURL = request.url();
424     m_options.securityCheck = securityCheck;
425     ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
426     ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
427
428     if (!m_referrer.isNull())
429         request.setHTTPReferrer(m_referrer);
430
431     if (m_async) {
432         ResourceLoaderOptions options = m_options;
433         options.clientCredentialPolicy = m_sameOriginRequest ? ClientCredentialPolicy::MayAskClientForCredentials : ClientCredentialPolicy::CannotAskClientForCredentials;
434         options.contentSecurityPolicyImposition = ContentSecurityPolicyImposition::SkipPolicyCheck;
435         
436         // If there is integrity metadata to validate, we must buffer.
437         if (!m_options.integrity.isEmpty())
438             options.dataBufferingPolicy = BufferData;
439
440         request.setAllowCookies(m_options.allowCredentials == AllowStoredCredentials);
441         CachedResourceRequest newRequest(WTFMove(request), options);
442         if (RuntimeEnabledFeatures::sharedFeatures().resourceTimingEnabled())
443             newRequest.setInitiator(m_options.initiator);
444         newRequest.setOrigin(securityOrigin());
445
446         ASSERT(!m_resource);
447         if (m_resource) {
448             CachedResourceHandle<CachedRawResource> resource = std::exchange(m_resource, nullptr);
449             resource->removeClient(*this);
450         }
451
452         // We create an URL here as the request will be moved in requestRawResource
453         URL requestUrl = newRequest.resourceRequest().url();
454         m_resource = m_document.cachedResourceLoader().requestRawResource(WTFMove(newRequest));
455         if (m_resource)
456             m_resource->addClient(*this);
457         else {
458             // FIXME: Since we receive a synchronous error, this is probably due to some AccessControl checks. We should try to retrieve the actual error.
459             logErrorAndFail(ResourceError(String(), 0, requestUrl, String(), ResourceError::Type::AccessControl));
460         }
461         return;
462     }
463
464     // If credentials mode is 'Omit', we should disable cookie sending.
465     ASSERT(m_options.credentials != FetchOptions::Credentials::Omit);
466
467     LoadTiming loadTiming;
468     loadTiming.markStartTimeAndFetchStart();
469
470     // FIXME: ThreadableLoaderOptions.sniffContent is not supported for synchronous requests.
471     RefPtr<SharedBuffer> data;
472     ResourceError error;
473     ResourceResponse response;
474     unsigned long identifier = std::numeric_limits<unsigned long>::max();
475     if (m_document.frame()) {
476         auto& frameLoader = m_document.frame()->loader();
477         if (!frameLoader.mixedContentChecker().canRunInsecureContent(m_document.securityOrigin(), requestURL))
478             return;
479         identifier = frameLoader.loadResourceSynchronously(request, m_options.allowCredentials, m_options.clientCredentialPolicy, error, response, data);
480     }
481
482     loadTiming.setResponseEnd(MonotonicTime::now());
483
484     if (!error.isNull() && response.httpStatusCode() <= 0) {
485         if (requestURL.isLocalFile()) {
486             // We don't want XMLHttpRequest to raise an exception for file:// resources, see <rdar://problem/4962298>.
487             // FIXME: XMLHttpRequest quirks should be in XMLHttpRequest code, not in DocumentThreadableLoader.cpp.
488             didReceiveResponse(identifier, response);
489             didFinishLoading(identifier);
490             return;
491         }
492         logErrorAndFail(error);
493         return;
494     }
495
496     // FIXME: FrameLoader::loadSynchronously() does not tell us whether a redirect happened or not, so we guess by comparing the
497     // request and response URLs. This isn't a perfect test though, since a server can serve a redirect to the same URL that was
498     // requested. Also comparing the request and response URLs as strings will fail if the requestURL still has its credentials.
499     bool didRedirect = requestURL != response.url();
500     if (didRedirect) {
501         if (!isAllowedByContentSecurityPolicy(response.url(), ContentSecurityPolicy::RedirectResponseReceived::Yes)) {
502             reportContentSecurityPolicyError(requestURL);
503             return;
504         }
505         if (!isAllowedRedirect(response.url())) {
506             reportCrossOriginResourceSharingError(requestURL);
507             return;
508         }
509     }
510
511     if (!m_sameOriginRequest) {
512         if (m_options.mode == FetchOptions::Mode::NoCors)
513             response.setTainting(ResourceResponse::Tainting::Opaque);
514         else {
515             ASSERT(m_options.mode == FetchOptions::Mode::Cors);
516             response.setTainting(ResourceResponse::Tainting::Cors);
517             String accessControlErrorDescription;
518             if (!passesAccessControlCheck(response, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription)) {
519                 logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, response.url(), accessControlErrorDescription, ResourceError::Type::AccessControl));
520                 return;
521             }
522         }
523     }
524     didReceiveResponse(identifier, response);
525
526     if (data)
527         didReceiveData(identifier, data->data(), data->size());
528
529     if (RuntimeEnabledFeatures::sharedFeatures().resourceTimingEnabled()) {
530         auto resourceTiming = ResourceTiming::fromSynchronousLoad(requestURL, m_options.initiator, loadTiming, response.deprecatedNetworkLoadMetrics(), response, securityOrigin());
531         if (options().initiatorContext == InitiatorContext::Worker)
532             finishedTimingForWorkerLoad(resourceTiming);
533         else {
534             if (document().domWindow() && document().domWindow()->performance())
535                 document().domWindow()->performance()->addResourceTiming(WTFMove(resourceTiming));
536         }
537     }
538
539     didFinishLoading(identifier);
540 }
541
542 bool DocumentThreadableLoader::isAllowedByContentSecurityPolicy(const URL& url, ContentSecurityPolicy::RedirectResponseReceived redirectResponseReceived)
543 {
544     switch (m_options.contentSecurityPolicyEnforcement) {
545     case ContentSecurityPolicyEnforcement::DoNotEnforce:
546         return true;
547     case ContentSecurityPolicyEnforcement::EnforceChildSrcDirective:
548         return contentSecurityPolicy().allowChildContextFromSource(url, redirectResponseReceived);
549     case ContentSecurityPolicyEnforcement::EnforceConnectSrcDirective:
550         return contentSecurityPolicy().allowConnectToSource(url, redirectResponseReceived);
551     case ContentSecurityPolicyEnforcement::EnforceScriptSrcDirective:
552         return contentSecurityPolicy().allowScriptFromSource(url, redirectResponseReceived);
553     }
554     ASSERT_NOT_REACHED();
555     return false;
556 }
557
558 bool DocumentThreadableLoader::isAllowedRedirect(const URL& url)
559 {
560     if (m_options.mode == FetchOptions::Mode::NoCors)
561         return true;
562
563     return m_sameOriginRequest && securityOrigin().canRequest(url);
564 }
565
566 bool DocumentThreadableLoader::isXMLHttpRequest() const
567 {
568     return m_options.initiator == cachedResourceRequestInitiators().xmlhttprequest;
569 }
570
571 SecurityOrigin& DocumentThreadableLoader::securityOrigin() const
572 {
573     return m_origin ? *m_origin : m_document.securityOrigin();
574 }
575
576 const ContentSecurityPolicy& DocumentThreadableLoader::contentSecurityPolicy() const
577 {
578     if (m_contentSecurityPolicy)
579         return *m_contentSecurityPolicy.get();
580     ASSERT(m_document.contentSecurityPolicy());
581     return *m_document.contentSecurityPolicy();
582 }
583
584 void DocumentThreadableLoader::reportRedirectionWithBadScheme(const URL& url)
585 {
586     logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, url, "Redirection to URL with a scheme that is not HTTP(S).", ResourceError::Type::AccessControl));
587 }
588
589 void DocumentThreadableLoader::reportContentSecurityPolicyError(const URL& url)
590 {
591     logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, url, "Cross-origin redirection denied by Content Security Policy.", ResourceError::Type::AccessControl));
592 }
593
594 void DocumentThreadableLoader::reportCrossOriginResourceSharingError(const URL& url)
595 {
596     logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, url, "Cross-origin redirection denied by Cross-Origin Resource Sharing policy.", ResourceError::Type::AccessControl));
597 }
598
599 void DocumentThreadableLoader::reportIntegrityMetadataError(const URL& url)
600 {
601     logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, url, "Failed integrity metadata check.", ResourceError::Type::General));
602 }
603
604 void DocumentThreadableLoader::logErrorAndFail(const ResourceError& error)
605 {
606     if (m_shouldLogError == ShouldLogError::Yes)
607         logError(m_document, error, m_options.initiator);
608     ASSERT(m_client);
609     m_client->didFail(error);
610 }
611
612 } // namespace WebCore